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