]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/attributes.rs
4ed4e8ac6efab44c3765ae77aea8e84493e3ce72
[rust.git] / src / librustc_codegen_llvm / attributes.rs
1 //! Set and unset common attributes on LLVM values.
2
3 use std::ffi::CString;
4
5 use rustc::middle::codegen_fn_attrs::CodegenFnAttrFlags;
6 use rustc::session::config::{OptLevel, Sanitizer};
7 use rustc::session::Session;
8 use rustc::ty::layout::HasTyCtxt;
9 use rustc::ty::query::Providers;
10 use rustc::ty::{self, Ty, TyCtxt};
11 use rustc_codegen_ssa::traits::*;
12 use rustc_data_structures::const_cstr;
13 use rustc_data_structures::fx::FxHashMap;
14 use rustc_data_structures::small_c_str::SmallCStr;
15 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
16 use rustc_target::abi::call::Conv;
17 use rustc_target::spec::PanicStrategy;
18
19 use crate::abi::FnAbi;
20 use crate::attributes;
21 use crate::llvm::AttributePlace::Function;
22 use crate::llvm::{self, Attribute};
23 use crate::llvm_util;
24 pub use syntax::attr::{self, InlineAttr, OptimizeAttr};
25
26 use crate::context::CodegenCx;
27 use crate::value::Value;
28
29 /// Mark LLVM function to use provided inline heuristic.
30 #[inline]
31 fn inline(cx: &CodegenCx<'ll, '_>, val: &'ll Value, inline: InlineAttr) {
32     use self::InlineAttr::*;
33     match inline {
34         Hint => Attribute::InlineHint.apply_llfn(Function, val),
35         Always => Attribute::AlwaysInline.apply_llfn(Function, val),
36         Never => {
37             if cx.tcx().sess.target.target.arch != "amdgpu" {
38                 Attribute::NoInline.apply_llfn(Function, val);
39             }
40         }
41         None => {
42             Attribute::InlineHint.unapply_llfn(Function, val);
43             Attribute::AlwaysInline.unapply_llfn(Function, val);
44             Attribute::NoInline.unapply_llfn(Function, val);
45         }
46     };
47 }
48
49 /// Tell LLVM to emit or not emit the information necessary to unwind the stack for the function.
50 #[inline]
51 pub fn emit_uwtable(val: &'ll Value, emit: bool) {
52     Attribute::UWTable.toggle_llfn(Function, val, emit);
53 }
54
55 /// Tell LLVM whether the function can or cannot unwind.
56 #[inline]
57 fn unwind(val: &'ll Value, can_unwind: bool) {
58     Attribute::NoUnwind.toggle_llfn(Function, val, !can_unwind);
59 }
60
61 /// Tell LLVM if this function should be 'naked', i.e., skip the epilogue and prologue.
62 #[inline]
63 fn naked(val: &'ll Value, is_naked: bool) {
64     Attribute::Naked.toggle_llfn(Function, val, is_naked);
65 }
66
67 pub fn set_frame_pointer_elimination(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
68     if cx.sess().must_not_eliminate_frame_pointers() {
69         if llvm_util::get_major_version() >= 8 {
70             llvm::AddFunctionAttrStringValue(
71                 llfn,
72                 llvm::AttributePlace::Function,
73                 const_cstr!("frame-pointer"),
74                 const_cstr!("all"),
75             );
76         } else {
77             llvm::AddFunctionAttrStringValue(
78                 llfn,
79                 llvm::AttributePlace::Function,
80                 const_cstr!("no-frame-pointer-elim"),
81                 const_cstr!("true"),
82             );
83         }
84     }
85 }
86
87 /// Tell LLVM what instrument function to insert.
88 #[inline]
89 fn set_instrument_function(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
90     if cx.sess().instrument_mcount() {
91         // Similar to `clang -pg` behavior. Handled by the
92         // `post-inline-ee-instrument` LLVM pass.
93
94         // The function name varies on platforms.
95         // See test/CodeGen/mcount.c in clang.
96         let mcount_name =
97             CString::new(cx.sess().target.target.options.target_mcount.as_str().as_bytes())
98                 .unwrap();
99
100         llvm::AddFunctionAttrStringValue(
101             llfn,
102             llvm::AttributePlace::Function,
103             const_cstr!("instrument-function-entry-inlined"),
104             &mcount_name,
105         );
106     }
107 }
108
109 fn set_probestack(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
110     // Only use stack probes if the target specification indicates that we
111     // should be using stack probes
112     if !cx.sess().target.target.options.stack_probes {
113         return;
114     }
115
116     // Currently stack probes seem somewhat incompatible with the address
117     // sanitizer and thread sanitizer. With asan we're already protected from
118     // stack overflow anyway so we don't really need stack probes regardless.
119     match cx.sess().opts.debugging_opts.sanitizer {
120         Some(Sanitizer::Address) | Some(Sanitizer::Thread) => return,
121         _ => {}
122     }
123
124     // probestack doesn't play nice either with `-C profile-generate`.
125     if cx.sess().opts.cg.profile_generate.enabled() {
126         return;
127     }
128
129     // probestack doesn't play nice either with gcov profiling.
130     if cx.sess().opts.debugging_opts.profile {
131         return;
132     }
133
134     // Flag our internal `__rust_probestack` function as the stack probe symbol.
135     // This is defined in the `compiler-builtins` crate for each architecture.
136     llvm::AddFunctionAttrStringValue(
137         llfn,
138         llvm::AttributePlace::Function,
139         const_cstr!("probe-stack"),
140         const_cstr!("__rust_probestack"),
141     );
142 }
143
144 fn translate_obsolete_target_features(feature: &str) -> &str {
145     const LLVM9_FEATURE_CHANGES: &[(&str, &str)] =
146         &[("+fp-only-sp", "-fp64"), ("-fp-only-sp", "+fp64"), ("+d16", "-d32"), ("-d16", "+d32")];
147     if llvm_util::get_major_version() >= 9 {
148         for &(old, new) in LLVM9_FEATURE_CHANGES {
149             if feature == old {
150                 return new;
151             }
152         }
153     } else {
154         for &(old, new) in LLVM9_FEATURE_CHANGES {
155             if feature == new {
156                 return old;
157             }
158         }
159     }
160     feature
161 }
162
163 pub fn llvm_target_features(sess: &Session) -> impl Iterator<Item = &str> {
164     const RUSTC_SPECIFIC_FEATURES: &[&str] = &["crt-static"];
165
166     let cmdline = sess
167         .opts
168         .cg
169         .target_feature
170         .split(',')
171         .filter(|f| !RUSTC_SPECIFIC_FEATURES.iter().any(|s| f.contains(s)));
172     sess.target
173         .target
174         .options
175         .features
176         .split(',')
177         .chain(cmdline)
178         .filter(|l| !l.is_empty())
179         .map(translate_obsolete_target_features)
180 }
181
182 pub fn apply_target_cpu_attr(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
183     let target_cpu = SmallCStr::new(llvm_util::target_cpu(cx.tcx.sess));
184     llvm::AddFunctionAttrStringValue(
185         llfn,
186         llvm::AttributePlace::Function,
187         const_cstr!("target-cpu"),
188         target_cpu.as_c_str(),
189     );
190 }
191
192 /// Sets the `NonLazyBind` LLVM attribute on a given function,
193 /// assuming the codegen options allow skipping the PLT.
194 pub fn non_lazy_bind(sess: &Session, llfn: &'ll Value) {
195     // Don't generate calls through PLT if it's not necessary
196     if !sess.needs_plt() {
197         Attribute::NonLazyBind.apply_llfn(Function, llfn);
198     }
199 }
200
201 pub(crate) fn default_optimisation_attrs(sess: &Session, llfn: &'ll Value) {
202     match sess.opts.optimize {
203         OptLevel::Size => {
204             llvm::Attribute::MinSize.unapply_llfn(Function, llfn);
205             llvm::Attribute::OptimizeForSize.apply_llfn(Function, llfn);
206             llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
207         }
208         OptLevel::SizeMin => {
209             llvm::Attribute::MinSize.apply_llfn(Function, llfn);
210             llvm::Attribute::OptimizeForSize.apply_llfn(Function, llfn);
211             llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
212         }
213         OptLevel::No => {
214             llvm::Attribute::MinSize.unapply_llfn(Function, llfn);
215             llvm::Attribute::OptimizeForSize.unapply_llfn(Function, llfn);
216             llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
217         }
218         _ => {}
219     }
220 }
221
222 /// Composite function which sets LLVM attributes for function depending on its AST (`#[attribute]`)
223 /// attributes.
224 pub fn from_fn_attrs(
225     cx: &CodegenCx<'ll, 'tcx>,
226     llfn: &'ll Value,
227     instance: ty::Instance<'tcx>,
228     fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
229 ) {
230     let codegen_fn_attrs = cx.tcx.codegen_fn_attrs(instance.def_id());
231
232     match codegen_fn_attrs.optimize {
233         OptimizeAttr::None => {
234             default_optimisation_attrs(cx.tcx.sess, llfn);
235         }
236         OptimizeAttr::Speed => {
237             llvm::Attribute::MinSize.unapply_llfn(Function, llfn);
238             llvm::Attribute::OptimizeForSize.unapply_llfn(Function, llfn);
239             llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
240         }
241         OptimizeAttr::Size => {
242             llvm::Attribute::MinSize.apply_llfn(Function, llfn);
243             llvm::Attribute::OptimizeForSize.apply_llfn(Function, llfn);
244             llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
245         }
246     }
247
248     // FIXME(eddyb) consolidate these two `inline` calls (and avoid overwrites).
249     if instance.def.is_inline(cx.tcx) {
250         inline(cx, llfn, attributes::InlineAttr::Hint);
251     }
252
253     inline(cx, llfn, codegen_fn_attrs.inline);
254
255     // The `uwtable` attribute according to LLVM is:
256     //
257     //     This attribute indicates that the ABI being targeted requires that an
258     //     unwind table entry be produced for this function even if we can show
259     //     that no exceptions passes by it. This is normally the case for the
260     //     ELF x86-64 abi, but it can be disabled for some compilation units.
261     //
262     // Typically when we're compiling with `-C panic=abort` (which implies this
263     // `no_landing_pads` check) we don't need `uwtable` because we can't
264     // generate any exceptions! On Windows, however, exceptions include other
265     // events such as illegal instructions, segfaults, etc. This means that on
266     // Windows we end up still needing the `uwtable` attribute even if the `-C
267     // panic=abort` flag is passed.
268     //
269     // You can also find more info on why Windows is whitelisted here in:
270     //      https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
271     if !cx.sess().no_landing_pads() || cx.sess().target.target.options.requires_uwtable {
272         attributes::emit_uwtable(llfn, true);
273     }
274
275     set_frame_pointer_elimination(cx, llfn);
276     set_instrument_function(cx, llfn);
277     set_probestack(cx, llfn);
278
279     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
280         Attribute::Cold.apply_llfn(Function, llfn);
281     }
282     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::FFI_RETURNS_TWICE) {
283         Attribute::ReturnsTwice.apply_llfn(Function, llfn);
284     }
285     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
286         naked(llfn, true);
287     }
288     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::ALLOCATOR) {
289         Attribute::NoAlias.apply_llfn(llvm::AttributePlace::ReturnValue, llfn);
290     }
291
292     unwind(
293         llfn,
294         if cx.tcx.sess.panic_strategy() != PanicStrategy::Unwind {
295             // In panic=abort mode we assume nothing can unwind anywhere, so
296             // optimize based on this!
297             false
298         } else if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::UNWIND) {
299             // If a specific #[unwind] attribute is present, use that.
300             true
301         } else if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_ALLOCATOR_NOUNWIND) {
302             // Special attribute for allocator functions, which can't unwind.
303             false
304         } else {
305             if fn_abi.conv == Conv::Rust {
306                 // Any Rust method (or `extern "Rust" fn` or `extern
307                 // "rust-call" fn`) is explicitly allowed to unwind
308                 // (unless it has no-unwind attribute, handled above).
309                 true
310             } else {
311                 // Anything else is either:
312                 //
313                 //  1. A foreign item using a non-Rust ABI (like `extern "C" { fn foo(); }`), or
314                 //
315                 //  2. A Rust item using a non-Rust ABI (like `extern "C" fn foo() { ... }`).
316                 //
317                 // Foreign items (case 1) are assumed to not unwind; it is
318                 // UB otherwise. (At least for now; see also
319                 // rust-lang/rust#63909 and Rust RFC 2753.)
320                 //
321                 // Items defined in Rust with non-Rust ABIs (case 2) are also
322                 // not supposed to unwind. Whether this should be enforced
323                 // (versus stating it is UB) and *how* it would be enforced
324                 // is currently under discussion; see rust-lang/rust#58794.
325                 //
326                 // In either case, we mark item as explicitly nounwind.
327                 false
328             }
329         },
330     );
331
332     // Always annotate functions with the target-cpu they are compiled for.
333     // Without this, ThinLTO won't inline Rust functions into Clang generated
334     // functions (because Clang annotates functions this way too).
335     apply_target_cpu_attr(cx, llfn);
336
337     let features = llvm_target_features(cx.tcx.sess)
338         .map(|s| s.to_string())
339         .chain(codegen_fn_attrs.target_features.iter().map(|f| {
340             let feature = &f.as_str();
341             format!("+{}", llvm_util::to_llvm_feature(cx.tcx.sess, feature))
342         }))
343         .collect::<Vec<String>>()
344         .join(",");
345
346     if !features.is_empty() {
347         let val = CString::new(features).unwrap();
348         llvm::AddFunctionAttrStringValue(
349             llfn,
350             llvm::AttributePlace::Function,
351             const_cstr!("target-features"),
352             &val,
353         );
354     }
355
356     // Note that currently the `wasm-import-module` doesn't do anything, but
357     // eventually LLVM 7 should read this and ferry the appropriate import
358     // module to the output file.
359     if cx.tcx.sess.target.target.arch == "wasm32" {
360         if let Some(module) = wasm_import_module(cx.tcx, instance.def_id()) {
361             llvm::AddFunctionAttrStringValue(
362                 llfn,
363                 llvm::AttributePlace::Function,
364                 const_cstr!("wasm-import-module"),
365                 &module,
366             );
367
368             let name =
369                 codegen_fn_attrs.link_name.unwrap_or_else(|| cx.tcx.item_name(instance.def_id()));
370             let name = CString::new(&name.as_str()[..]).unwrap();
371             llvm::AddFunctionAttrStringValue(
372                 llfn,
373                 llvm::AttributePlace::Function,
374                 const_cstr!("wasm-import-name"),
375                 &name,
376             );
377         }
378     }
379 }
380
381 pub fn provide(providers: &mut Providers<'_>) {
382     providers.target_features_whitelist = |tcx, cnum| {
383         assert_eq!(cnum, LOCAL_CRATE);
384         if tcx.sess.opts.actually_rustdoc {
385             // rustdoc needs to be able to document functions that use all the features, so
386             // whitelist them all
387             tcx.arena
388                 .alloc(llvm_util::all_known_features().map(|(a, b)| (a.to_string(), b)).collect())
389         } else {
390             tcx.arena.alloc(
391                 llvm_util::target_feature_whitelist(tcx.sess)
392                     .iter()
393                     .map(|&(a, b)| (a.to_string(), b))
394                     .collect(),
395             )
396         }
397     };
398
399     provide_extern(providers);
400 }
401
402 pub fn provide_extern(providers: &mut Providers<'_>) {
403     providers.wasm_import_module_map = |tcx, cnum| {
404         // Build up a map from DefId to a `NativeLibrary` structure, where
405         // `NativeLibrary` internally contains information about
406         // `#[link(wasm_import_module = "...")]` for example.
407         let native_libs = tcx.native_libraries(cnum);
408
409         let def_id_to_native_lib = native_libs
410             .iter()
411             .filter_map(|lib| lib.foreign_module.map(|id| (id, lib)))
412             .collect::<FxHashMap<_, _>>();
413
414         let mut ret = FxHashMap::default();
415         for lib in tcx.foreign_modules(cnum).iter() {
416             let module = def_id_to_native_lib.get(&lib.def_id).and_then(|s| s.wasm_import_module);
417             let module = match module {
418                 Some(s) => s,
419                 None => continue,
420             };
421             ret.extend(lib.foreign_items.iter().map(|id| {
422                 assert_eq!(id.krate, cnum);
423                 (*id, module.to_string())
424             }));
425         }
426
427         tcx.arena.alloc(ret)
428     };
429 }
430
431 fn wasm_import_module(tcx: TyCtxt<'_>, id: DefId) -> Option<CString> {
432     tcx.wasm_import_module_map(id.krate).get(&id).map(|s| CString::new(&s[..]).unwrap())
433 }