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