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