]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/declare.rs
Auto merge of #53134 - alexcrichton:tweak-travis, r=Mark-Simulacrum
[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_target::spec::PanicStrategy;
29 use abi::{Abi, FnType, FnTypeExt};
30 use attributes;
31 use context::CodegenCx;
32 use common;
33 use type_::Type;
34 use value::Value;
35
36 use std::ffi::CString;
37
38
39 /// Declare a global value.
40 ///
41 /// If there’s a value with the same name already declared, the function will
42 /// return its Value instead.
43 pub fn declare_global(cx: &CodegenCx<'ll, '_>, name: &str, ty: &'ll Type) -> &'ll Value {
44     debug!("declare_global(name={:?})", name);
45     let namebuf = CString::new(name).unwrap_or_else(|_|{
46         bug!("name {:?} contains an interior null byte", name)
47     });
48     unsafe {
49         llvm::LLVMRustGetOrInsertGlobal(cx.llmod, namebuf.as_ptr(), ty)
50     }
51 }
52
53
54 /// Declare a function.
55 ///
56 /// If there’s a value with the same name already declared, the function will
57 /// update the declaration and return existing Value instead.
58 fn declare_raw_fn(
59     cx: &CodegenCx<'ll, '_>,
60     name: &str,
61     callconv: llvm::CallConv,
62     ty: &'ll Type,
63 ) -> &'ll Value {
64     debug!("declare_raw_fn(name={:?}, ty={:?})", name, ty);
65     let namebuf = CString::new(name).unwrap_or_else(|_|{
66         bug!("name {:?} contains an interior null byte", name)
67     });
68     let llfn = unsafe {
69         llvm::LLVMRustGetOrInsertFunction(cx.llmod, namebuf.as_ptr(), ty)
70     };
71
72     llvm::SetFunctionCallConv(llfn, callconv);
73     // Function addresses in Rust are never significant, allowing functions to
74     // be merged.
75     llvm::SetUnnamedAddr(llfn, true);
76
77     if cx.tcx.sess.opts.cg.no_redzone
78         .unwrap_or(cx.tcx.sess.target.target.options.disable_redzone) {
79         llvm::Attribute::NoRedZone.apply_llfn(Function, llfn);
80     }
81
82     if let Some(ref sanitizer) = cx.tcx.sess.opts.debugging_opts.sanitizer {
83         match *sanitizer {
84             Sanitizer::Address => {
85                 llvm::Attribute::SanitizeAddress.apply_llfn(Function, llfn);
86             },
87             Sanitizer::Memory => {
88                 llvm::Attribute::SanitizeMemory.apply_llfn(Function, llfn);
89             },
90             Sanitizer::Thread => {
91                 llvm::Attribute::SanitizeThread.apply_llfn(Function, llfn);
92             },
93             _ => {}
94         }
95     }
96
97     match cx.tcx.sess.opts.cg.opt_level.as_ref().map(String::as_ref) {
98         Some("s") => {
99             llvm::Attribute::OptimizeForSize.apply_llfn(Function, llfn);
100         },
101         Some("z") => {
102             llvm::Attribute::MinSize.apply_llfn(Function, llfn);
103             llvm::Attribute::OptimizeForSize.apply_llfn(Function, llfn);
104         },
105         _ => {},
106     }
107
108     if cx.tcx.sess.panic_strategy() != PanicStrategy::Unwind {
109         attributes::unwind(llfn, false);
110     }
111
112     llfn
113 }
114
115
116 /// Declare a C ABI function.
117 ///
118 /// Only use this for foreign function ABIs and glue. For Rust functions use
119 /// `declare_fn` instead.
120 ///
121 /// If there’s a value with the same name already declared, the function will
122 /// update the declaration and return existing Value instead.
123 pub fn declare_cfn(cx: &CodegenCx<'ll, '_>, name: &str, fn_type: &'ll Type) -> &'ll Value {
124     declare_raw_fn(cx, name, llvm::CCallConv, fn_type)
125 }
126
127
128 /// Declare a Rust function.
129 ///
130 /// If there’s a value with the same name already declared, the function will
131 /// update the declaration and return existing Value instead.
132 pub fn declare_fn(
133     cx: &CodegenCx<'ll, 'tcx>,
134     name: &str,
135     fn_type: Ty<'tcx>,
136 ) -> &'ll Value {
137     debug!("declare_rust_fn(name={:?}, fn_type={:?})", name, fn_type);
138     let sig = common::ty_fn_sig(cx, fn_type);
139     let sig = cx.tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
140     debug!("declare_rust_fn (after region erasure) sig={:?}", sig);
141
142     let fty = FnType::new(cx, sig, &[]);
143     let llfn = declare_raw_fn(cx, name, fty.llvm_cconv(), fty.llvm_type(cx));
144
145     if cx.layout_of(sig.output()).abi == layout::Abi::Uninhabited {
146         llvm::Attribute::NoReturn.apply_llfn(Function, llfn);
147     }
148
149     if sig.abi != Abi::Rust && sig.abi != Abi::RustCall {
150         attributes::unwind(llfn, false);
151     }
152
153     fty.apply_attrs_llfn(llfn);
154
155     llfn
156 }
157
158
159 /// Declare a global with an intention to define it.
160 ///
161 /// Use this function when you intend to define a global. This function will
162 /// return None if the name already has a definition associated with it. In that
163 /// case an error should be reported to the user, because it usually happens due
164 /// to user’s fault (e.g. misuse of #[no_mangle] or #[export_name] attributes).
165 pub fn define_global(cx: &CodegenCx<'ll, '_>, name: &str, ty: &'ll Type) -> Option<&'ll Value> {
166     if get_defined_value(cx, name).is_some() {
167         None
168     } else {
169         Some(declare_global(cx, name, ty))
170     }
171 }
172
173 /// Declare a Rust function with an intention to define it.
174 ///
175 /// Use this function when you intend to define a function. This function will
176 /// return panic if the name already has a definition associated with it. This
177 /// can happen with #[no_mangle] or #[export_name], for example.
178 pub fn define_fn(
179     cx: &CodegenCx<'ll, 'tcx>,
180     name: &str,
181     fn_type: Ty<'tcx>,
182 ) -> &'ll Value {
183     if get_defined_value(cx, name).is_some() {
184         cx.sess().fatal(&format!("symbol `{}` already defined", name))
185     } else {
186         declare_fn(cx, name, fn_type)
187     }
188 }
189
190 /// Declare a Rust function with an intention to define it.
191 ///
192 /// Use this function when you intend to define a function. This function will
193 /// return panic if the name already has a definition associated with it. This
194 /// can happen with #[no_mangle] or #[export_name], for example.
195 pub fn define_internal_fn(
196     cx: &CodegenCx<'ll, 'tcx>,
197     name: &str,
198     fn_type: Ty<'tcx>,
199 ) -> &'ll Value {
200     let llfn = define_fn(cx, name, fn_type);
201     unsafe { llvm::LLVMRustSetLinkage(llfn, llvm::Linkage::InternalLinkage) };
202     llfn
203 }
204
205
206 /// Get declared value by name.
207 pub fn get_declared_value(cx: &CodegenCx<'ll, '_>, name: &str) -> Option<&'ll Value> {
208     debug!("get_declared_value(name={:?})", name);
209     let namebuf = CString::new(name).unwrap_or_else(|_|{
210         bug!("name {:?} contains an interior null byte", name)
211     });
212     unsafe { llvm::LLVMRustGetNamedValue(cx.llmod, namebuf.as_ptr()) }
213 }
214
215 /// Get defined or externally defined (AvailableExternally linkage) value by
216 /// name.
217 pub fn get_defined_value(cx: &CodegenCx<'ll, '_>, name: &str) -> Option<&'ll Value> {
218     get_declared_value(cx, name).and_then(|val|{
219         let declaration = unsafe {
220             llvm::LLVMIsDeclaration(val) != 0
221         };
222         if !declaration {
223             Some(val)
224         } else {
225             None
226         }
227     })
228 }