]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/declare.rs
Rollup merge of #53545 - FelixMcFelix:fix-50865-beta, r=petrochenkov
[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::{self, 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     llfn
108 }
109
110
111 /// Declare a C ABI function.
112 ///
113 /// Only use this for foreign function ABIs and glue. For Rust functions use
114 /// `declare_fn` instead.
115 ///
116 /// If there’s a value with the same name already declared, the function will
117 /// update the declaration and return existing Value instead.
118 pub fn declare_cfn(cx: &CodegenCx<'ll, '_>, name: &str, fn_type: &'ll Type) -> &'ll Value {
119     declare_raw_fn(cx, name, llvm::CCallConv, fn_type)
120 }
121
122
123 /// Declare a Rust function.
124 ///
125 /// If there’s a value with the same name already declared, the function will
126 /// update the declaration and return existing Value instead.
127 pub fn declare_fn(
128     cx: &CodegenCx<'ll, 'tcx>,
129     name: &str,
130     fn_type: Ty<'tcx>,
131 ) -> &'ll Value {
132     debug!("declare_rust_fn(name={:?}, fn_type={:?})", name, fn_type);
133     let sig = common::ty_fn_sig(cx, fn_type);
134     let sig = cx.tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
135     debug!("declare_rust_fn (after region erasure) sig={:?}", sig);
136
137     let fty = FnType::new(cx, sig, &[]);
138     let llfn = declare_raw_fn(cx, name, fty.llvm_cconv(), fty.llvm_type(cx));
139
140     if cx.layout_of(sig.output()).abi == layout::Abi::Uninhabited {
141         llvm::Attribute::NoReturn.apply_llfn(Function, llfn);
142     }
143
144     if sig.abi != Abi::Rust && sig.abi != Abi::RustCall {
145         attributes::unwind(llfn, false);
146     }
147
148     fty.apply_attrs_llfn(llfn);
149
150     llfn
151 }
152
153
154 /// Declare a global with an intention to define it.
155 ///
156 /// Use this function when you intend to define a global. This function will
157 /// return None if the name already has a definition associated with it. In that
158 /// case an error should be reported to the user, because it usually happens due
159 /// to user’s fault (e.g. misuse of #[no_mangle] or #[export_name] attributes).
160 pub fn define_global(cx: &CodegenCx<'ll, '_>, name: &str, ty: &'ll Type) -> Option<&'ll Value> {
161     if get_defined_value(cx, name).is_some() {
162         None
163     } else {
164         Some(declare_global(cx, name, ty))
165     }
166 }
167
168 /// Declare a private global
169 ///
170 /// Use this function when you intend to define a global without a name.
171 pub fn define_private_global(cx: &CodegenCx<'ll, '_>, ty: &'ll Type) -> &'ll Value {
172     unsafe {
173         llvm::LLVMRustInsertPrivateGlobal(cx.llmod, ty)
174     }
175 }
176
177 /// Declare a Rust function with an intention to define it.
178 ///
179 /// Use this function when you intend to define a function. This function will
180 /// return panic if the name already has a definition associated with it. This
181 /// can happen with #[no_mangle] or #[export_name], for example.
182 pub fn define_fn(
183     cx: &CodegenCx<'ll, 'tcx>,
184     name: &str,
185     fn_type: Ty<'tcx>,
186 ) -> &'ll Value {
187     if get_defined_value(cx, name).is_some() {
188         cx.sess().fatal(&format!("symbol `{}` already defined", name))
189     } else {
190         declare_fn(cx, name, fn_type)
191     }
192 }
193
194 /// Declare a Rust function with an intention to define it.
195 ///
196 /// Use this function when you intend to define a function. This function will
197 /// return panic if the name already has a definition associated with it. This
198 /// can happen with #[no_mangle] or #[export_name], for example.
199 pub fn define_internal_fn(
200     cx: &CodegenCx<'ll, 'tcx>,
201     name: &str,
202     fn_type: Ty<'tcx>,
203 ) -> &'ll Value {
204     let llfn = define_fn(cx, name, fn_type);
205     unsafe { llvm::LLVMRustSetLinkage(llfn, llvm::Linkage::InternalLinkage) };
206     llfn
207 }
208
209
210 /// Get declared value by name.
211 pub fn get_declared_value(cx: &CodegenCx<'ll, '_>, name: &str) -> Option<&'ll Value> {
212     debug!("get_declared_value(name={:?})", name);
213     let namebuf = SmallCStr::new(name);
214     unsafe { llvm::LLVMRustGetNamedValue(cx.llmod, namebuf.as_ptr()) }
215 }
216
217 /// Get defined or externally defined (AvailableExternally linkage) value by
218 /// name.
219 pub fn get_defined_value(cx: &CodegenCx<'ll, '_>, name: &str) -> Option<&'ll Value> {
220     get_declared_value(cx, name).and_then(|val|{
221         let declaration = unsafe {
222             llvm::LLVMIsDeclaration(val) != 0
223         };
224         if !declaration {
225             Some(val)
226         } else {
227             None
228         }
229     })
230 }