]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/declare.rs
Rollup merge of #54967 - holmgr:master, r=estebank
[rust.git] / src / librustc_codegen_llvm / declare.rs
1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10 //! Declare various LLVM values.
11 //!
12 //! Prefer using functions and methods from this module rather than calling LLVM
13 //! functions directly. These functions do some additional work to ensure we do
14 //! the right thing given the preconceptions of codegen.
15 //!
16 //! Some useful guidelines:
17 //!
18 //! * Use declare_* family of methods if you are declaring, but are not
19 //!   interested in defining the Value they return.
20 //! * Use define_* family of methods when you might be defining the Value.
21 //! * When in doubt, define.
22
23 use llvm;
24 use llvm::AttributePlace::Function;
25 use rustc::ty::{self, Ty};
26 use rustc::ty::layout::LayoutOf;
27 use rustc::session::config::Sanitizer;
28 use rustc_data_structures::small_c_str::SmallCStr;
29 use rustc_target::spec::PanicStrategy;
30 use abi::{Abi, FnType, FnTypeExt};
31 use attributes;
32 use context::CodegenCx;
33 use common;
34 use type_::Type;
35 use value::Value;
36
37
38 /// Declare a global value.
39 ///
40 /// If there’s a value with the same name already declared, the function will
41 /// return its Value instead.
42 pub fn declare_global(cx: &CodegenCx<'ll, '_>, name: &str, ty: &'ll Type) -> &'ll Value {
43     debug!("declare_global(name={:?})", name);
44     let namebuf = SmallCStr::new(name);
45     unsafe {
46         llvm::LLVMRustGetOrInsertGlobal(cx.llmod, namebuf.as_ptr(), ty)
47     }
48 }
49
50
51 /// Declare a function.
52 ///
53 /// If there’s a value with the same name already declared, the function will
54 /// update the declaration and return existing Value instead.
55 fn declare_raw_fn(
56     cx: &CodegenCx<'ll, '_>,
57     name: &str,
58     callconv: llvm::CallConv,
59     ty: &'ll Type,
60 ) -> &'ll Value {
61     debug!("declare_raw_fn(name={:?}, ty={:?})", name, ty);
62     let namebuf = SmallCStr::new(name);
63     let llfn = unsafe {
64         llvm::LLVMRustGetOrInsertFunction(cx.llmod, namebuf.as_ptr(), ty)
65     };
66
67     llvm::SetFunctionCallConv(llfn, callconv);
68     // Function addresses in Rust are never significant, allowing functions to
69     // be merged.
70     llvm::SetUnnamedAddr(llfn, true);
71
72     if cx.tcx.sess.opts.cg.no_redzone
73         .unwrap_or(cx.tcx.sess.target.target.options.disable_redzone) {
74         llvm::Attribute::NoRedZone.apply_llfn(Function, llfn);
75     }
76
77     if let Some(ref sanitizer) = cx.tcx.sess.opts.debugging_opts.sanitizer {
78         match *sanitizer {
79             Sanitizer::Address => {
80                 llvm::Attribute::SanitizeAddress.apply_llfn(Function, llfn);
81             },
82             Sanitizer::Memory => {
83                 llvm::Attribute::SanitizeMemory.apply_llfn(Function, llfn);
84             },
85             Sanitizer::Thread => {
86                 llvm::Attribute::SanitizeThread.apply_llfn(Function, llfn);
87             },
88             _ => {}
89         }
90     }
91
92     match cx.tcx.sess.opts.cg.opt_level.as_ref().map(String::as_ref) {
93         Some("s") => {
94             llvm::Attribute::OptimizeForSize.apply_llfn(Function, llfn);
95         },
96         Some("z") => {
97             llvm::Attribute::MinSize.apply_llfn(Function, llfn);
98             llvm::Attribute::OptimizeForSize.apply_llfn(Function, llfn);
99         },
100         _ => {},
101     }
102
103     if cx.tcx.sess.panic_strategy() != PanicStrategy::Unwind {
104         attributes::unwind(llfn, false);
105     }
106
107     attributes::non_lazy_bind(cx.sess(), llfn);
108
109     llfn
110 }
111
112
113 /// Declare a C ABI function.
114 ///
115 /// Only use this for foreign function ABIs and glue. For Rust functions use
116 /// `declare_fn` instead.
117 ///
118 /// If there’s a value with the same name already declared, the function will
119 /// update the declaration and return existing Value instead.
120 pub fn declare_cfn(cx: &CodegenCx<'ll, '_>, name: &str, fn_type: &'ll Type) -> &'ll Value {
121     declare_raw_fn(cx, name, llvm::CCallConv, fn_type)
122 }
123
124
125 /// Declare a Rust function.
126 ///
127 /// If there’s a value with the same name already declared, the function will
128 /// update the declaration and return existing Value instead.
129 pub fn declare_fn(
130     cx: &CodegenCx<'ll, 'tcx>,
131     name: &str,
132     fn_type: Ty<'tcx>,
133 ) -> &'ll Value {
134     debug!("declare_rust_fn(name={:?}, fn_type={:?})", name, fn_type);
135     let sig = common::ty_fn_sig(cx, fn_type);
136     let sig = cx.tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
137     debug!("declare_rust_fn (after region erasure) sig={:?}", sig);
138
139     let fty = FnType::new(cx, sig, &[]);
140     let llfn = declare_raw_fn(cx, name, fty.llvm_cconv(), fty.llvm_type(cx));
141
142     if cx.layout_of(sig.output()).abi.is_uninhabited() {
143         llvm::Attribute::NoReturn.apply_llfn(Function, llfn);
144     }
145
146     if sig.abi != Abi::Rust && sig.abi != Abi::RustCall {
147         attributes::unwind(llfn, false);
148     }
149
150     fty.apply_attrs_llfn(llfn);
151
152     llfn
153 }
154
155
156 /// Declare a global with an intention to define it.
157 ///
158 /// Use this function when you intend to define a global. This function will
159 /// return None if the name already has a definition associated with it. In that
160 /// case an error should be reported to the user, because it usually happens due
161 /// to user’s fault (e.g. misuse of #[no_mangle] or #[export_name] attributes).
162 pub fn define_global(cx: &CodegenCx<'ll, '_>, name: &str, ty: &'ll Type) -> Option<&'ll Value> {
163     if get_defined_value(cx, name).is_some() {
164         None
165     } else {
166         Some(declare_global(cx, name, ty))
167     }
168 }
169
170 /// Declare a private global
171 ///
172 /// Use this function when you intend to define a global without a name.
173 pub fn define_private_global(cx: &CodegenCx<'ll, '_>, ty: &'ll Type) -> &'ll Value {
174     unsafe {
175         llvm::LLVMRustInsertPrivateGlobal(cx.llmod, ty)
176     }
177 }
178
179 /// Declare a Rust function with an intention to define it.
180 ///
181 /// Use this function when you intend to define a function. This function will
182 /// return panic if the name already has a definition associated with it. This
183 /// can happen with #[no_mangle] or #[export_name], for example.
184 pub fn define_fn(
185     cx: &CodegenCx<'ll, 'tcx>,
186     name: &str,
187     fn_type: Ty<'tcx>,
188 ) -> &'ll Value {
189     if get_defined_value(cx, name).is_some() {
190         cx.sess().fatal(&format!("symbol `{}` already defined", name))
191     } else {
192         declare_fn(cx, name, fn_type)
193     }
194 }
195
196 /// Declare a Rust function with an intention to define it.
197 ///
198 /// Use this function when you intend to define a function. This function will
199 /// return panic if the name already has a definition associated with it. This
200 /// can happen with #[no_mangle] or #[export_name], for example.
201 pub fn define_internal_fn(
202     cx: &CodegenCx<'ll, 'tcx>,
203     name: &str,
204     fn_type: Ty<'tcx>,
205 ) -> &'ll Value {
206     let llfn = define_fn(cx, name, fn_type);
207     unsafe { llvm::LLVMRustSetLinkage(llfn, llvm::Linkage::InternalLinkage) };
208     llfn
209 }
210
211
212 /// Get declared value by name.
213 pub fn get_declared_value(cx: &CodegenCx<'ll, '_>, name: &str) -> Option<&'ll Value> {
214     debug!("get_declared_value(name={:?})", name);
215     let namebuf = SmallCStr::new(name);
216     unsafe { llvm::LLVMRustGetNamedValue(cx.llmod, namebuf.as_ptr()) }
217 }
218
219 /// Get defined or externally defined (AvailableExternally linkage) value by
220 /// name.
221 pub fn get_defined_value(cx: &CodegenCx<'ll, '_>, name: &str) -> Option<&'ll Value> {
222     get_declared_value(cx, name).and_then(|val|{
223         let declaration = unsafe {
224             llvm::LLVMIsDeclaration(val) != 0
225         };
226         if !declaration {
227             Some(val)
228         } else {
229             None
230         }
231     })
232 }