]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/attributes.rs
Auto merge of #84228 - SkiFire13:fix-84213, r=estebank
[rust.git] / compiler / rustc_codegen_llvm / src / attributes.rs
1 //! Set and unset common attributes on LLVM values.
2
3 use std::ffi::CString;
4
5 use cstr::cstr;
6 use rustc_codegen_ssa::traits::*;
7 use rustc_data_structures::fx::FxHashMap;
8 use rustc_data_structures::small_c_str::SmallCStr;
9 use rustc_hir::def_id::DefId;
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;
15 use rustc_session::Session;
16 use rustc_target::spec::abi::Abi;
17 use rustc_target::spec::{SanitizerSet, StackProbeType};
18
19 use crate::attributes;
20 use crate::llvm::AttributePlace::Function;
21 use crate::llvm::{self, Attribute};
22 use crate::llvm_util;
23 pub use rustc_attr::{InlineAttr, InstructionSetAttr, OptimizeAttr};
24
25 use crate::context::CodegenCx;
26 use crate::value::Value;
27
28 /// Mark LLVM function to use provided inline heuristic.
29 #[inline]
30 fn inline(cx: &CodegenCx<'ll, '_>, val: &'ll Value, inline: InlineAttr) {
31     use self::InlineAttr::*;
32     match inline {
33         Hint => Attribute::InlineHint.apply_llfn(Function, val),
34         Always => Attribute::AlwaysInline.apply_llfn(Function, val),
35         Never => {
36             if cx.tcx().sess.target.arch != "amdgpu" {
37                 Attribute::NoInline.apply_llfn(Function, val);
38             }
39         }
40         None => {}
41     };
42 }
43
44 /// Apply LLVM sanitize attributes.
45 #[inline]
46 pub fn sanitize(cx: &CodegenCx<'ll, '_>, no_sanitize: SanitizerSet, llfn: &'ll Value) {
47     let enabled = cx.tcx.sess.opts.debugging_opts.sanitizer - no_sanitize;
48     if enabled.contains(SanitizerSet::ADDRESS) {
49         llvm::Attribute::SanitizeAddress.apply_llfn(Function, llfn);
50     }
51     if enabled.contains(SanitizerSet::MEMORY) {
52         llvm::Attribute::SanitizeMemory.apply_llfn(Function, llfn);
53     }
54     if enabled.contains(SanitizerSet::THREAD) {
55         llvm::Attribute::SanitizeThread.apply_llfn(Function, llfn);
56     }
57     if enabled.contains(SanitizerSet::HWADDRESS) {
58         llvm::Attribute::SanitizeHWAddress.apply_llfn(Function, llfn);
59     }
60 }
61
62 /// Tell LLVM to emit or not emit the information necessary to unwind the stack for the function.
63 #[inline]
64 pub fn emit_uwtable(val: &'ll Value, emit: bool) {
65     Attribute::UWTable.toggle_llfn(Function, val, emit);
66 }
67
68 /// Tell LLVM if this function should be 'naked', i.e., skip the epilogue and prologue.
69 #[inline]
70 fn naked(val: &'ll Value, is_naked: bool) {
71     Attribute::Naked.toggle_llfn(Function, val, is_naked);
72 }
73
74 pub fn set_frame_pointer_elimination(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
75     if cx.sess().must_not_eliminate_frame_pointers() {
76         llvm::AddFunctionAttrStringValue(
77             llfn,
78             llvm::AttributePlace::Function,
79             cstr!("frame-pointer"),
80             cstr!("all"),
81         );
82     }
83 }
84
85 /// Tell LLVM what instrument function to insert.
86 #[inline]
87 fn set_instrument_function(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
88     if cx.sess().instrument_mcount() {
89         // Similar to `clang -pg` behavior. Handled by the
90         // `post-inline-ee-instrument` LLVM pass.
91
92         // The function name varies on platforms.
93         // See test/CodeGen/mcount.c in clang.
94         let mcount_name = CString::new(cx.sess().target.mcount.as_str().as_bytes()).unwrap();
95
96         llvm::AddFunctionAttrStringValue(
97             llfn,
98             llvm::AttributePlace::Function,
99             cstr!("instrument-function-entry-inlined"),
100             &mcount_name,
101         );
102     }
103 }
104
105 fn set_probestack(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
106     // Currently stack probes seem somewhat incompatible with the address
107     // sanitizer and thread sanitizer. With asan we're already protected from
108     // stack overflow anyway so we don't really need stack probes regardless.
109     if cx
110         .sess()
111         .opts
112         .debugging_opts
113         .sanitizer
114         .intersects(SanitizerSet::ADDRESS | SanitizerSet::THREAD)
115     {
116         return;
117     }
118
119     // probestack doesn't play nice either with `-C profile-generate`.
120     if cx.sess().opts.cg.profile_generate.enabled() {
121         return;
122     }
123
124     // probestack doesn't play nice either with gcov profiling.
125     if cx.sess().opts.debugging_opts.profile {
126         return;
127     }
128
129     let attr_value = match cx.sess().target.stack_probes {
130         StackProbeType::None => None,
131         // Request LLVM to generate the probes inline. If the given LLVM version does not support
132         // this, no probe is generated at all (even if the attribute is specified).
133         StackProbeType::Inline => Some(cstr!("inline-asm")),
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         StackProbeType::Call => Some(cstr!("__rust_probestack")),
137         // Pick from the two above based on the LLVM version.
138         StackProbeType::InlineOrCall { min_llvm_version_for_inline } => {
139             if llvm_util::get_version() < min_llvm_version_for_inline {
140                 Some(cstr!("__rust_probestack"))
141             } else {
142                 Some(cstr!("inline-asm"))
143             }
144         }
145     };
146     if let Some(attr_value) = attr_value {
147         llvm::AddFunctionAttrStringValue(
148             llfn,
149             llvm::AttributePlace::Function,
150             cstr!("probe-stack"),
151             attr_value,
152         );
153     }
154 }
155
156 pub fn apply_target_cpu_attr(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
157     let target_cpu = SmallCStr::new(llvm_util::target_cpu(cx.tcx.sess));
158     llvm::AddFunctionAttrStringValue(
159         llfn,
160         llvm::AttributePlace::Function,
161         cstr!("target-cpu"),
162         target_cpu.as_c_str(),
163     );
164 }
165
166 pub fn apply_tune_cpu_attr(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
167     if let Some(tune) = llvm_util::tune_cpu(cx.tcx.sess) {
168         let tune_cpu = SmallCStr::new(tune);
169         llvm::AddFunctionAttrStringValue(
170             llfn,
171             llvm::AttributePlace::Function,
172             cstr!("tune-cpu"),
173             tune_cpu.as_c_str(),
174         );
175     }
176 }
177
178 /// Sets the `NonLazyBind` LLVM attribute on a given function,
179 /// assuming the codegen options allow skipping the PLT.
180 pub fn non_lazy_bind(sess: &Session, llfn: &'ll Value) {
181     // Don't generate calls through PLT if it's not necessary
182     if !sess.needs_plt() {
183         Attribute::NonLazyBind.apply_llfn(Function, llfn);
184     }
185 }
186
187 pub(crate) fn default_optimisation_attrs(sess: &Session, llfn: &'ll Value) {
188     match sess.opts.optimize {
189         OptLevel::Size => {
190             llvm::Attribute::MinSize.unapply_llfn(Function, llfn);
191             llvm::Attribute::OptimizeForSize.apply_llfn(Function, llfn);
192             llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
193         }
194         OptLevel::SizeMin => {
195             llvm::Attribute::MinSize.apply_llfn(Function, llfn);
196             llvm::Attribute::OptimizeForSize.apply_llfn(Function, llfn);
197             llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
198         }
199         OptLevel::No => {
200             llvm::Attribute::MinSize.unapply_llfn(Function, llfn);
201             llvm::Attribute::OptimizeForSize.unapply_llfn(Function, llfn);
202             llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
203         }
204         _ => {}
205     }
206 }
207
208 /// Composite function which sets LLVM attributes for function depending on its AST (`#[attribute]`)
209 /// attributes.
210 pub fn from_fn_attrs(cx: &CodegenCx<'ll, 'tcx>, llfn: &'ll Value, instance: ty::Instance<'tcx>) {
211     let codegen_fn_attrs = cx.tcx.codegen_fn_attrs(instance.def_id());
212
213     match codegen_fn_attrs.optimize {
214         OptimizeAttr::None => {
215             default_optimisation_attrs(cx.tcx.sess, llfn);
216         }
217         OptimizeAttr::Speed => {
218             llvm::Attribute::MinSize.unapply_llfn(Function, llfn);
219             llvm::Attribute::OptimizeForSize.unapply_llfn(Function, llfn);
220             llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
221         }
222         OptimizeAttr::Size => {
223             llvm::Attribute::MinSize.apply_llfn(Function, llfn);
224             llvm::Attribute::OptimizeForSize.apply_llfn(Function, llfn);
225             llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
226         }
227     }
228
229     let inline_attr = if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
230         InlineAttr::Never
231     } else if codegen_fn_attrs.inline == InlineAttr::None && instance.def.requires_inline(cx.tcx) {
232         InlineAttr::Hint
233     } else {
234         codegen_fn_attrs.inline
235     };
236     inline(cx, llfn, inline_attr);
237
238     // The `uwtable` attribute according to LLVM is:
239     //
240     //     This attribute indicates that the ABI being targeted requires that an
241     //     unwind table entry be produced for this function even if we can show
242     //     that no exceptions passes by it. This is normally the case for the
243     //     ELF x86-64 abi, but it can be disabled for some compilation units.
244     //
245     // Typically when we're compiling with `-C panic=abort` (which implies this
246     // `no_landing_pads` check) we don't need `uwtable` because we can't
247     // generate any exceptions! On Windows, however, exceptions include other
248     // events such as illegal instructions, segfaults, etc. This means that on
249     // Windows we end up still needing the `uwtable` attribute even if the `-C
250     // panic=abort` flag is passed.
251     //
252     // You can also find more info on why Windows always requires uwtables here:
253     //      https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
254     if cx.sess().must_emit_unwind_tables() {
255         attributes::emit_uwtable(llfn, true);
256     }
257
258     // FIXME: none of these three functions interact with source level attributes.
259     set_frame_pointer_elimination(cx, llfn);
260     set_instrument_function(cx, llfn);
261     set_probestack(cx, llfn);
262
263     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
264         Attribute::Cold.apply_llfn(Function, llfn);
265     }
266     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::FFI_RETURNS_TWICE) {
267         Attribute::ReturnsTwice.apply_llfn(Function, llfn);
268     }
269     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::FFI_PURE) {
270         Attribute::ReadOnly.apply_llfn(Function, llfn);
271     }
272     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::FFI_CONST) {
273         Attribute::ReadNone.apply_llfn(Function, llfn);
274     }
275     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
276         naked(llfn, true);
277     }
278     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::ALLOCATOR) {
279         Attribute::NoAlias.apply_llfn(llvm::AttributePlace::ReturnValue, llfn);
280     }
281     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::CMSE_NONSECURE_ENTRY) {
282         llvm::AddFunctionAttrString(llfn, Function, cstr!("cmse_nonsecure_entry"));
283     }
284     if let Some(align) = codegen_fn_attrs.alignment {
285         llvm::set_alignment(llfn, align as usize);
286     }
287     sanitize(cx, codegen_fn_attrs.no_sanitize, llfn);
288
289     // Always annotate functions with the target-cpu they are compiled for.
290     // Without this, ThinLTO won't inline Rust functions into Clang generated
291     // functions (because Clang annotates functions this way too).
292     apply_target_cpu_attr(cx, llfn);
293     // tune-cpu is only conveyed through the attribute for our purpose.
294     // The target doesn't care; the subtarget reads our attribute.
295     apply_tune_cpu_attr(cx, llfn);
296
297     let mut function_features = codegen_fn_attrs
298         .target_features
299         .iter()
300         .map(|f| {
301             let feature = &f.as_str();
302             format!("+{}", llvm_util::to_llvm_feature(cx.tcx.sess, feature))
303         })
304         .chain(codegen_fn_attrs.instruction_set.iter().map(|x| match x {
305             InstructionSetAttr::ArmA32 => "-thumb-mode".to_string(),
306             InstructionSetAttr::ArmT32 => "+thumb-mode".to_string(),
307         }))
308         .collect::<Vec<String>>();
309
310     if cx.tcx.sess.target.is_like_wasm {
311         // If this function is an import from the environment but the wasm
312         // import has a specific module/name, apply them here.
313         if let Some(module) = wasm_import_module(cx.tcx, instance.def_id()) {
314             llvm::AddFunctionAttrStringValue(
315                 llfn,
316                 llvm::AttributePlace::Function,
317                 cstr!("wasm-import-module"),
318                 &module,
319             );
320
321             let name =
322                 codegen_fn_attrs.link_name.unwrap_or_else(|| cx.tcx.item_name(instance.def_id()));
323             let name = CString::new(&name.as_str()[..]).unwrap();
324             llvm::AddFunctionAttrStringValue(
325                 llfn,
326                 llvm::AttributePlace::Function,
327                 cstr!("wasm-import-name"),
328                 &name,
329             );
330         }
331
332         // The `"wasm"` abi on wasm targets automatically enables the
333         // `+multivalue` feature because the purpose of the wasm abi is to match
334         // the WebAssembly specification, which has this feature. This won't be
335         // needed when LLVM enables this `multivalue` feature by default.
336         if !cx.tcx.is_closure(instance.def_id()) {
337             let abi = cx.tcx.fn_sig(instance.def_id()).abi();
338             if abi == Abi::Wasm {
339                 function_features.push("+multivalue".to_string());
340             }
341         }
342     }
343
344     if !function_features.is_empty() {
345         let mut global_features = llvm_util::llvm_global_features(cx.tcx.sess);
346         global_features.extend(function_features.into_iter());
347         let features = global_features.join(",");
348         let val = CString::new(features).unwrap();
349         llvm::AddFunctionAttrStringValue(
350             llfn,
351             llvm::AttributePlace::Function,
352             cstr!("target-features"),
353             &val,
354         );
355     }
356 }
357
358 pub fn provide_both(providers: &mut Providers) {
359     providers.wasm_import_module_map = |tcx, cnum| {
360         // Build up a map from DefId to a `NativeLib` structure, where
361         // `NativeLib` internally contains information about
362         // `#[link(wasm_import_module = "...")]` for example.
363         let native_libs = tcx.native_libraries(cnum);
364
365         let def_id_to_native_lib = native_libs
366             .iter()
367             .filter_map(|lib| lib.foreign_module.map(|id| (id, lib)))
368             .collect::<FxHashMap<_, _>>();
369
370         let mut ret = FxHashMap::default();
371         for (def_id, lib) in tcx.foreign_modules(cnum).iter() {
372             let module = def_id_to_native_lib.get(&def_id).and_then(|s| s.wasm_import_module);
373             let module = match module {
374                 Some(s) => s,
375                 None => continue,
376             };
377             ret.extend(lib.foreign_items.iter().map(|id| {
378                 assert_eq!(id.krate, cnum);
379                 (*id, module.to_string())
380             }));
381         }
382
383         ret
384     };
385 }
386
387 fn wasm_import_module(tcx: TyCtxt<'_>, id: DefId) -> Option<CString> {
388     tcx.wasm_import_module_map(id.krate).get(&id).map(|s| CString::new(&s[..]).unwrap())
389 }