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