]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/attributes.rs
Generalized base.rs#call_memcpy and everything that it uses
[rust.git] / src / librustc_codegen_llvm / attributes.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 //! Set and unset common attributes on LLVM values.
11
12 use std::ffi::CString;
13
14 use rustc::hir::{CodegenFnAttrFlags, CodegenFnAttrs};
15 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
16 use rustc::session::Session;
17 use rustc::session::config::Sanitizer;
18 use rustc::ty::TyCtxt;
19 use rustc::ty::layout::HasTyCtxt;
20 use rustc::ty::query::Providers;
21 use rustc_data_structures::sync::Lrc;
22 use rustc_data_structures::fx::FxHashMap;
23 use rustc_target::spec::PanicStrategy;
24
25 use attributes;
26 use llvm::{self, Attribute};
27 use llvm::AttributePlace::Function;
28 use llvm_util;
29 pub use syntax::attr::{self, InlineAttr};
30
31 use context::CodegenCx;
32 use value::Value;
33
34 /// Mark LLVM function to use provided inline heuristic.
35 #[inline]
36 pub fn inline(cx: &CodegenCx<'ll, '_>, val: &'ll Value, inline: InlineAttr) {
37     use self::InlineAttr::*;
38     match inline {
39         Hint   => Attribute::InlineHint.apply_llfn(Function, val),
40         Always => Attribute::AlwaysInline.apply_llfn(Function, val),
41         Never  => {
42             if cx.tcx().sess.target.target.arch != "amdgpu" {
43                 Attribute::NoInline.apply_llfn(Function, val);
44             }
45         },
46         None   => {
47             Attribute::InlineHint.unapply_llfn(Function, val);
48             Attribute::AlwaysInline.unapply_llfn(Function, val);
49             Attribute::NoInline.unapply_llfn(Function, val);
50         },
51     };
52 }
53
54 /// Tell LLVM to emit or not emit the information necessary to unwind the stack for the function.
55 #[inline]
56 pub fn emit_uwtable(val: &'ll Value, emit: bool) {
57     Attribute::UWTable.toggle_llfn(Function, val, emit);
58 }
59
60 /// Tell LLVM whether the function can or cannot unwind.
61 #[inline]
62 pub fn unwind(val: &'ll Value, can_unwind: bool) {
63     Attribute::NoUnwind.toggle_llfn(Function, val, !can_unwind);
64 }
65
66 /// Tell LLVM whether it should optimize function for size.
67 #[inline]
68 #[allow(dead_code)] // possibly useful function
69 pub fn set_optimize_for_size(val: &'ll Value, optimize: bool) {
70     Attribute::OptimizeForSize.toggle_llfn(Function, val, optimize);
71 }
72
73 /// Tell LLVM if this function should be 'naked', i.e. skip the epilogue and prologue.
74 #[inline]
75 pub fn naked(val: &'ll Value, is_naked: bool) {
76     Attribute::Naked.toggle_llfn(Function, val, is_naked);
77 }
78
79 pub fn set_frame_pointer_elimination(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
80     if cx.sess().must_not_eliminate_frame_pointers() {
81         llvm::AddFunctionAttrStringValue(
82             llfn, llvm::AttributePlace::Function,
83             const_cstr!("no-frame-pointer-elim"), const_cstr!("true"));
84     }
85 }
86
87 pub fn set_probestack(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
88     // Only use stack probes if the target specification indicates that we
89     // should be using stack probes
90     if !cx.sess().target.target.options.stack_probes {
91         return
92     }
93
94     // Currently stack probes seem somewhat incompatible with the address
95     // sanitizer. With asan we're already protected from stack overflow anyway
96     // so we don't really need stack probes regardless.
97     if let Some(Sanitizer::Address) = cx.sess().opts.debugging_opts.sanitizer {
98         return
99     }
100
101     // probestack doesn't play nice either with pgo-gen.
102     if cx.sess().opts.debugging_opts.pgo_gen.is_some() {
103         return;
104     }
105
106     // probestack doesn't play nice either with gcov profiling.
107     if cx.sess().opts.debugging_opts.profile {
108         return;
109     }
110
111     // Flag our internal `__rust_probestack` function as the stack probe symbol.
112     // This is defined in the `compiler-builtins` crate for each architecture.
113     llvm::AddFunctionAttrStringValue(
114         llfn, llvm::AttributePlace::Function,
115         const_cstr!("probe-stack"), const_cstr!("__rust_probestack"));
116 }
117
118 pub fn llvm_target_features(sess: &Session) -> impl Iterator<Item = &str> {
119     const RUSTC_SPECIFIC_FEATURES: &[&str] = &[
120         "crt-static",
121     ];
122
123     let cmdline = sess.opts.cg.target_feature.split(',')
124         .filter(|f| !RUSTC_SPECIFIC_FEATURES.iter().any(|s| f.contains(s)));
125     sess.target.target.options.features.split(',')
126         .chain(cmdline)
127         .filter(|l| !l.is_empty())
128 }
129
130 pub fn apply_target_cpu_attr(cx: &CodegenCx<'ll, '_, &'ll Value>, llfn: &'ll Value) {
131     let cpu = llvm_util::target_cpu(cx.tcx.sess);
132     let target_cpu = CString::new(cpu).unwrap();
133     llvm::AddFunctionAttrStringValue(
134             llfn,
135             llvm::AttributePlace::Function,
136             const_cstr!("target-cpu"),
137             target_cpu.as_c_str());
138 }
139
140 /// Sets the `NonLazyBind` LLVM attribute on a given function,
141 /// assuming the codegen options allow skipping the PLT.
142 pub fn non_lazy_bind(sess: &Session, llfn: &'ll Value) {
143     // Don't generate calls through PLT if it's not necessary
144     if !sess.needs_plt() {
145         Attribute::NonLazyBind.apply_llfn(Function, llfn);
146     }
147 }
148
149 /// Composite function which sets LLVM attributes for function depending on its AST (#[attribute])
150 /// attributes.
151 pub fn from_fn_attrs(
152     cx: &CodegenCx<'ll, '_>,
153     llfn: &'ll Value,
154     id: Option<DefId>,
155 ) {
156     let codegen_fn_attrs = id.map(|id| cx.tcx.codegen_fn_attrs(id))
157         .unwrap_or_else(|| CodegenFnAttrs::new());
158
159     inline(cx, llfn, codegen_fn_attrs.inline);
160
161     // The `uwtable` attribute according to LLVM is:
162     //
163     //     This attribute indicates that the ABI being targeted requires that an
164     //     unwind table entry be produced for this function even if we can show
165     //     that no exceptions passes by it. This is normally the case for the
166     //     ELF x86-64 abi, but it can be disabled for some compilation units.
167     //
168     // Typically when we're compiling with `-C panic=abort` (which implies this
169     // `no_landing_pads` check) we don't need `uwtable` because we can't
170     // generate any exceptions! On Windows, however, exceptions include other
171     // events such as illegal instructions, segfaults, etc. This means that on
172     // Windows we end up still needing the `uwtable` attribute even if the `-C
173     // panic=abort` flag is passed.
174     //
175     // You can also find more info on why Windows is whitelisted here in:
176     //      https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
177     if !cx.sess().no_landing_pads() ||
178        cx.sess().target.target.options.requires_uwtable {
179         attributes::emit_uwtable(llfn, true);
180     }
181
182     set_frame_pointer_elimination(cx, llfn);
183     set_probestack(cx, llfn);
184
185     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
186         Attribute::Cold.apply_llfn(Function, llfn);
187     }
188     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
189         naked(llfn, true);
190     }
191     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::ALLOCATOR) {
192         Attribute::NoAlias.apply_llfn(
193             llvm::AttributePlace::ReturnValue, llfn);
194     }
195
196     let can_unwind = if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::UNWIND) {
197         Some(true)
198     } else if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_ALLOCATOR_NOUNWIND) {
199         Some(false)
200
201     // Perhaps questionable, but we assume that anything defined
202     // *in Rust code* may unwind. Foreign items like `extern "C" {
203     // fn foo(); }` are assumed not to unwind **unless** they have
204     // a `#[unwind]` attribute.
205     } else if id.map(|id| !cx.tcx.is_foreign_item(id)).unwrap_or(false) {
206         Some(true)
207     } else {
208         None
209     };
210
211     match can_unwind {
212         Some(false) => attributes::unwind(llfn, false),
213         Some(true) if cx.tcx.sess.panic_strategy() == PanicStrategy::Unwind => {
214             attributes::unwind(llfn, true);
215         }
216         Some(true) | None => {}
217     }
218
219     // Always annotate functions with the target-cpu they are compiled for.
220     // Without this, ThinLTO won't inline Rust functions into Clang generated
221     // functions (because Clang annotates functions this way too).
222     // NOTE: For now we just apply this if -Zcross-lang-lto is specified, since
223     //       it introduce a little overhead and isn't really necessary otherwise.
224     if cx.tcx.sess.opts.debugging_opts.cross_lang_lto.enabled() {
225         apply_target_cpu_attr(cx, llfn);
226     }
227
228     let features = llvm_target_features(cx.tcx.sess)
229         .map(|s| s.to_string())
230         .chain(
231             codegen_fn_attrs.target_features
232                 .iter()
233                 .map(|f| {
234                     let feature = &*f.as_str();
235                     format!("+{}", llvm_util::to_llvm_feature(cx.tcx.sess, feature))
236                 })
237         )
238         .collect::<Vec<String>>()
239         .join(",");
240
241     if !features.is_empty() {
242         let val = CString::new(features).unwrap();
243         llvm::AddFunctionAttrStringValue(
244             llfn, llvm::AttributePlace::Function,
245             const_cstr!("target-features"), &val);
246     }
247
248     // Note that currently the `wasm-import-module` doesn't do anything, but
249     // eventually LLVM 7 should read this and ferry the appropriate import
250     // module to the output file.
251     if let Some(id) = id {
252         if cx.tcx.sess.target.target.arch == "wasm32" {
253             if let Some(module) = wasm_import_module(cx.tcx, id) {
254                 llvm::AddFunctionAttrStringValue(
255                     llfn,
256                     llvm::AttributePlace::Function,
257                     const_cstr!("wasm-import-module"),
258                     &module,
259                 );
260             }
261         }
262     }
263 }
264
265 pub fn provide(providers: &mut Providers) {
266     providers.target_features_whitelist = |tcx, cnum| {
267         assert_eq!(cnum, LOCAL_CRATE);
268         if tcx.sess.opts.actually_rustdoc {
269             // rustdoc needs to be able to document functions that use all the features, so
270             // whitelist them all
271             Lrc::new(llvm_util::all_known_features()
272                 .map(|(a, b)| (a.to_string(), b.map(|s| s.to_string())))
273                 .collect())
274         } else {
275             Lrc::new(llvm_util::target_feature_whitelist(tcx.sess)
276                 .iter()
277                 .map(|&(a, b)| (a.to_string(), b.map(|s| s.to_string())))
278                 .collect())
279         }
280     };
281
282     provide_extern(providers);
283 }
284
285 pub fn provide_extern(providers: &mut Providers) {
286     providers.wasm_import_module_map = |tcx, cnum| {
287         // Build up a map from DefId to a `NativeLibrary` structure, where
288         // `NativeLibrary` internally contains information about
289         // `#[link(wasm_import_module = "...")]` for example.
290         let native_libs = tcx.native_libraries(cnum);
291
292         let def_id_to_native_lib = native_libs.iter().filter_map(|lib|
293             if let Some(id) = lib.foreign_module {
294                 Some((id, lib))
295             } else {
296                 None
297             }
298         ).collect::<FxHashMap<_, _>>();
299
300         let mut ret = FxHashMap::default();
301         for lib in tcx.foreign_modules(cnum).iter() {
302             let module = def_id_to_native_lib
303                 .get(&lib.def_id)
304                 .and_then(|s| s.wasm_import_module);
305             let module = match module {
306                 Some(s) => s,
307                 None => continue,
308             };
309             ret.extend(lib.foreign_items.iter().map(|id| {
310                 assert_eq!(id.krate, cnum);
311                 (*id, module.to_string())
312             }));
313         }
314
315         Lrc::new(ret)
316     };
317 }
318
319 fn wasm_import_module(tcx: TyCtxt, id: DefId) -> Option<CString> {
320     tcx.wasm_import_module_map(id.krate)
321         .get(&id)
322         .map(|s| CString::new(&s[..]).unwrap())
323 }