]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/attributes.rs
Auto merge of #102417 - oli-obk:opaque_lifetimes2, r=jackh726
[rust.git] / compiler / rustc_codegen_llvm / src / attributes.rs
1 //! Set and unset common attributes on LLVM values.
2
3 use rustc_codegen_ssa::traits::*;
4 use rustc_data_structures::small_str::SmallStr;
5 use rustc_hir::def_id::DefId;
6 use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
7 use rustc_middle::ty::{self, TyCtxt};
8 use rustc_session::config::OptLevel;
9 use rustc_span::symbol::sym;
10 use rustc_target::spec::abi::Abi;
11 use rustc_target::spec::{FramePointer, SanitizerSet, StackProbeType, StackProtector};
12 use smallvec::SmallVec;
13
14 use crate::attributes;
15 use crate::llvm::AttributePlace::Function;
16 use crate::llvm::{self, AllocKindFlags, Attribute, AttributeKind, AttributePlace};
17 use crate::llvm_util;
18 pub use rustc_attr::{InlineAttr, InstructionSetAttr, OptimizeAttr};
19
20 use crate::context::CodegenCx;
21 use crate::value::Value;
22
23 pub fn apply_to_llfn(llfn: &Value, idx: AttributePlace, attrs: &[&Attribute]) {
24     if !attrs.is_empty() {
25         llvm::AddFunctionAttributes(llfn, idx, attrs);
26     }
27 }
28
29 pub fn apply_to_callsite(callsite: &Value, idx: AttributePlace, attrs: &[&Attribute]) {
30     if !attrs.is_empty() {
31         llvm::AddCallSiteAttributes(callsite, idx, attrs);
32     }
33 }
34
35 /// Get LLVM attribute for the provided inline heuristic.
36 #[inline]
37 fn inline_attr<'ll>(cx: &CodegenCx<'ll, '_>, inline: InlineAttr) -> Option<&'ll Attribute> {
38     if !cx.tcx.sess.opts.unstable_opts.inline_llvm {
39         // disable LLVM inlining
40         return Some(AttributeKind::NoInline.create_attr(cx.llcx));
41     }
42     match inline {
43         InlineAttr::Hint => Some(AttributeKind::InlineHint.create_attr(cx.llcx)),
44         InlineAttr::Always => Some(AttributeKind::AlwaysInline.create_attr(cx.llcx)),
45         InlineAttr::Never => {
46             if cx.sess().target.arch != "amdgpu" {
47                 Some(AttributeKind::NoInline.create_attr(cx.llcx))
48             } else {
49                 None
50             }
51         }
52         InlineAttr::None => None,
53     }
54 }
55
56 /// Get LLVM sanitize attributes.
57 #[inline]
58 pub fn sanitize_attrs<'ll>(
59     cx: &CodegenCx<'ll, '_>,
60     no_sanitize: SanitizerSet,
61 ) -> SmallVec<[&'ll Attribute; 4]> {
62     let mut attrs = SmallVec::new();
63     let enabled = cx.tcx.sess.opts.unstable_opts.sanitizer - no_sanitize;
64     if enabled.contains(SanitizerSet::ADDRESS) {
65         attrs.push(llvm::AttributeKind::SanitizeAddress.create_attr(cx.llcx));
66     }
67     if enabled.contains(SanitizerSet::MEMORY) {
68         attrs.push(llvm::AttributeKind::SanitizeMemory.create_attr(cx.llcx));
69     }
70     if enabled.contains(SanitizerSet::THREAD) {
71         attrs.push(llvm::AttributeKind::SanitizeThread.create_attr(cx.llcx));
72     }
73     if enabled.contains(SanitizerSet::HWADDRESS) {
74         attrs.push(llvm::AttributeKind::SanitizeHWAddress.create_attr(cx.llcx));
75     }
76     if enabled.contains(SanitizerSet::SHADOWCALLSTACK) {
77         attrs.push(llvm::AttributeKind::ShadowCallStack.create_attr(cx.llcx));
78     }
79     if enabled.contains(SanitizerSet::MEMTAG) {
80         // Check to make sure the mte target feature is actually enabled.
81         let features = cx.tcx.global_backend_features(());
82         let mte_feature =
83             features.iter().map(|s| &s[..]).rfind(|n| ["+mte", "-mte"].contains(&&n[..]));
84         if let None | Some("-mte") = mte_feature {
85             cx.tcx.sess.err("`-Zsanitizer=memtag` requires `-Ctarget-feature=+mte`");
86         }
87
88         attrs.push(llvm::AttributeKind::SanitizeMemTag.create_attr(cx.llcx));
89     }
90     attrs
91 }
92
93 /// Tell LLVM to emit or not emit the information necessary to unwind the stack for the function.
94 #[inline]
95 pub fn uwtable_attr(llcx: &llvm::Context) -> &Attribute {
96     // NOTE: We should determine if we even need async unwind tables, as they
97     // take have more overhead and if we can use sync unwind tables we
98     // probably should.
99     llvm::CreateUWTableAttr(llcx, true)
100 }
101
102 pub fn frame_pointer_type_attr<'ll>(cx: &CodegenCx<'ll, '_>) -> Option<&'ll Attribute> {
103     let mut fp = cx.sess().target.frame_pointer;
104     // "mcount" function relies on stack pointer.
105     // See <https://sourceware.org/binutils/docs/gprof/Implementation.html>.
106     if cx.sess().instrument_mcount() || matches!(cx.sess().opts.cg.force_frame_pointers, Some(true))
107     {
108         fp = FramePointer::Always;
109     }
110     let attr_value = match fp {
111         FramePointer::Always => "all",
112         FramePointer::NonLeaf => "non-leaf",
113         FramePointer::MayOmit => return None,
114     };
115     Some(llvm::CreateAttrStringValue(cx.llcx, "frame-pointer", attr_value))
116 }
117
118 /// Tell LLVM what instrument function to insert.
119 #[inline]
120 fn instrument_function_attr<'ll>(cx: &CodegenCx<'ll, '_>) -> Option<&'ll Attribute> {
121     if cx.sess().instrument_mcount() {
122         // Similar to `clang -pg` behavior. Handled by the
123         // `post-inline-ee-instrument` LLVM pass.
124
125         // The function name varies on platforms.
126         // See test/CodeGen/mcount.c in clang.
127         let mcount_name = cx.sess().target.mcount.as_ref();
128
129         Some(llvm::CreateAttrStringValue(
130             cx.llcx,
131             "instrument-function-entry-inlined",
132             &mcount_name,
133         ))
134     } else {
135         None
136     }
137 }
138
139 fn probestack_attr<'ll>(cx: &CodegenCx<'ll, '_>) -> Option<&'ll Attribute> {
140     // Currently stack probes seem somewhat incompatible with the address
141     // sanitizer and thread sanitizer. With asan we're already protected from
142     // stack overflow anyway so we don't really need stack probes regardless.
143     if cx
144         .sess()
145         .opts
146         .unstable_opts
147         .sanitizer
148         .intersects(SanitizerSet::ADDRESS | SanitizerSet::THREAD)
149     {
150         return None;
151     }
152
153     // probestack doesn't play nice either with `-C profile-generate`.
154     if cx.sess().opts.cg.profile_generate.enabled() {
155         return None;
156     }
157
158     // probestack doesn't play nice either with gcov profiling.
159     if cx.sess().opts.unstable_opts.profile {
160         return None;
161     }
162
163     let attr_value = match cx.sess().target.stack_probes {
164         StackProbeType::None => return None,
165         // Request LLVM to generate the probes inline. If the given LLVM version does not support
166         // this, no probe is generated at all (even if the attribute is specified).
167         StackProbeType::Inline => "inline-asm",
168         // Flag our internal `__rust_probestack` function as the stack probe symbol.
169         // This is defined in the `compiler-builtins` crate for each architecture.
170         StackProbeType::Call => "__rust_probestack",
171         // Pick from the two above based on the LLVM version.
172         StackProbeType::InlineOrCall { min_llvm_version_for_inline } => {
173             if llvm_util::get_version() < min_llvm_version_for_inline {
174                 "__rust_probestack"
175             } else {
176                 "inline-asm"
177             }
178         }
179     };
180     Some(llvm::CreateAttrStringValue(cx.llcx, "probe-stack", attr_value))
181 }
182
183 fn stackprotector_attr<'ll>(cx: &CodegenCx<'ll, '_>) -> Option<&'ll Attribute> {
184     let sspattr = match cx.sess().stack_protector() {
185         StackProtector::None => return None,
186         StackProtector::All => AttributeKind::StackProtectReq,
187         StackProtector::Strong => AttributeKind::StackProtectStrong,
188         StackProtector::Basic => AttributeKind::StackProtect,
189     };
190
191     Some(sspattr.create_attr(cx.llcx))
192 }
193
194 pub fn target_cpu_attr<'ll>(cx: &CodegenCx<'ll, '_>) -> &'ll Attribute {
195     let target_cpu = llvm_util::target_cpu(cx.tcx.sess);
196     llvm::CreateAttrStringValue(cx.llcx, "target-cpu", target_cpu)
197 }
198
199 pub fn tune_cpu_attr<'ll>(cx: &CodegenCx<'ll, '_>) -> Option<&'ll Attribute> {
200     llvm_util::tune_cpu(cx.tcx.sess)
201         .map(|tune_cpu| llvm::CreateAttrStringValue(cx.llcx, "tune-cpu", tune_cpu))
202 }
203
204 /// Get the `NonLazyBind` LLVM attribute,
205 /// if the codegen options allow skipping the PLT.
206 pub fn non_lazy_bind_attr<'ll>(cx: &CodegenCx<'ll, '_>) -> Option<&'ll Attribute> {
207     // Don't generate calls through PLT if it's not necessary
208     if !cx.sess().needs_plt() {
209         Some(AttributeKind::NonLazyBind.create_attr(cx.llcx))
210     } else {
211         None
212     }
213 }
214
215 /// Get the default optimizations attrs for a function.
216 #[inline]
217 pub(crate) fn default_optimisation_attrs<'ll>(
218     cx: &CodegenCx<'ll, '_>,
219 ) -> SmallVec<[&'ll Attribute; 2]> {
220     let mut attrs = SmallVec::new();
221     match cx.sess().opts.optimize {
222         OptLevel::Size => {
223             attrs.push(llvm::AttributeKind::OptimizeForSize.create_attr(cx.llcx));
224         }
225         OptLevel::SizeMin => {
226             attrs.push(llvm::AttributeKind::MinSize.create_attr(cx.llcx));
227             attrs.push(llvm::AttributeKind::OptimizeForSize.create_attr(cx.llcx));
228         }
229         _ => {}
230     }
231     attrs
232 }
233
234 fn create_alloc_family_attr(llcx: &llvm::Context) -> &llvm::Attribute {
235     llvm::CreateAttrStringValue(llcx, "alloc-family", "__rust_alloc")
236 }
237
238 /// Composite function which sets LLVM attributes for function depending on its AST (`#[attribute]`)
239 /// attributes.
240 pub fn from_fn_attrs<'ll, 'tcx>(
241     cx: &CodegenCx<'ll, 'tcx>,
242     llfn: &'ll Value,
243     instance: ty::Instance<'tcx>,
244 ) {
245     let codegen_fn_attrs = cx.tcx.codegen_fn_attrs(instance.def_id());
246
247     let mut to_add = SmallVec::<[_; 16]>::new();
248
249     match codegen_fn_attrs.optimize {
250         OptimizeAttr::None => {
251             to_add.extend(default_optimisation_attrs(cx));
252         }
253         OptimizeAttr::Size => {
254             to_add.push(llvm::AttributeKind::MinSize.create_attr(cx.llcx));
255             to_add.push(llvm::AttributeKind::OptimizeForSize.create_attr(cx.llcx));
256         }
257         OptimizeAttr::Speed => {}
258     }
259
260     let inline = if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
261         InlineAttr::Never
262     } else if codegen_fn_attrs.inline == InlineAttr::None && instance.def.requires_inline(cx.tcx) {
263         InlineAttr::Hint
264     } else {
265         codegen_fn_attrs.inline
266     };
267     to_add.extend(inline_attr(cx, inline));
268
269     // The `uwtable` attribute according to LLVM is:
270     //
271     //     This attribute indicates that the ABI being targeted requires that an
272     //     unwind table entry be produced for this function even if we can show
273     //     that no exceptions passes by it. This is normally the case for the
274     //     ELF x86-64 abi, but it can be disabled for some compilation units.
275     //
276     // Typically when we're compiling with `-C panic=abort` (which implies this
277     // `no_landing_pads` check) we don't need `uwtable` because we can't
278     // generate any exceptions! On Windows, however, exceptions include other
279     // events such as illegal instructions, segfaults, etc. This means that on
280     // Windows we end up still needing the `uwtable` attribute even if the `-C
281     // panic=abort` flag is passed.
282     //
283     // You can also find more info on why Windows always requires uwtables here:
284     //      https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
285     if cx.sess().must_emit_unwind_tables() {
286         to_add.push(uwtable_attr(cx.llcx));
287     }
288
289     if cx.sess().opts.unstable_opts.profile_sample_use.is_some() {
290         to_add.push(llvm::CreateAttrString(cx.llcx, "use-sample-profile"));
291     }
292
293     // FIXME: none of these three functions interact with source level attributes.
294     to_add.extend(frame_pointer_type_attr(cx));
295     to_add.extend(instrument_function_attr(cx));
296     to_add.extend(probestack_attr(cx));
297     to_add.extend(stackprotector_attr(cx));
298
299     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
300         to_add.push(AttributeKind::Cold.create_attr(cx.llcx));
301     }
302     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::FFI_RETURNS_TWICE) {
303         to_add.push(AttributeKind::ReturnsTwice.create_attr(cx.llcx));
304     }
305     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::FFI_PURE) {
306         to_add.push(AttributeKind::ReadOnly.create_attr(cx.llcx));
307     }
308     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::FFI_CONST) {
309         to_add.push(AttributeKind::ReadNone.create_attr(cx.llcx));
310     }
311     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
312         to_add.push(AttributeKind::Naked.create_attr(cx.llcx));
313         // HACK(jubilee): "indirect branch tracking" works by attaching prologues to functions.
314         // And it is a module-level attribute, so the alternative is pulling naked functions into new LLVM modules.
315         // Otherwise LLVM's "naked" functions come with endbr prefixes per https://github.com/rust-lang/rust/issues/98768
316         to_add.push(AttributeKind::NoCfCheck.create_attr(cx.llcx));
317         // Need this for AArch64.
318         to_add.push(llvm::CreateAttrStringValue(cx.llcx, "branch-target-enforcement", "false"));
319     }
320     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::ALLOCATOR)
321         || codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::ALLOCATOR_ZEROED)
322     {
323         if llvm_util::get_version() >= (15, 0, 0) {
324             to_add.push(create_alloc_family_attr(cx.llcx));
325             // apply to argument place instead of function
326             let alloc_align = AttributeKind::AllocAlign.create_attr(cx.llcx);
327             attributes::apply_to_llfn(llfn, AttributePlace::Argument(1), &[alloc_align]);
328             to_add.push(llvm::CreateAllocSizeAttr(cx.llcx, 0));
329             let mut flags = AllocKindFlags::Alloc | AllocKindFlags::Aligned;
330             if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::ALLOCATOR) {
331                 flags |= AllocKindFlags::Uninitialized;
332             } else {
333                 flags |= AllocKindFlags::Zeroed;
334             }
335             to_add.push(llvm::CreateAllocKindAttr(cx.llcx, flags));
336         }
337         // apply to return place instead of function (unlike all other attributes applied in this function)
338         let no_alias = AttributeKind::NoAlias.create_attr(cx.llcx);
339         attributes::apply_to_llfn(llfn, AttributePlace::ReturnValue, &[no_alias]);
340     }
341     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::REALLOCATOR) {
342         if llvm_util::get_version() >= (15, 0, 0) {
343             to_add.push(create_alloc_family_attr(cx.llcx));
344             to_add.push(llvm::CreateAllocKindAttr(
345                 cx.llcx,
346                 AllocKindFlags::Realloc | AllocKindFlags::Aligned,
347             ));
348             // applies to argument place instead of function place
349             let allocated_pointer = AttributeKind::AllocatedPointer.create_attr(cx.llcx);
350             attributes::apply_to_llfn(llfn, AttributePlace::Argument(0), &[allocated_pointer]);
351             // apply to argument place instead of function
352             let alloc_align = AttributeKind::AllocAlign.create_attr(cx.llcx);
353             attributes::apply_to_llfn(llfn, AttributePlace::Argument(2), &[alloc_align]);
354             to_add.push(llvm::CreateAllocSizeAttr(cx.llcx, 3));
355         }
356         let no_alias = AttributeKind::NoAlias.create_attr(cx.llcx);
357         attributes::apply_to_llfn(llfn, AttributePlace::ReturnValue, &[no_alias]);
358     }
359     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::DEALLOCATOR) {
360         if llvm_util::get_version() >= (15, 0, 0) {
361             to_add.push(create_alloc_family_attr(cx.llcx));
362             to_add.push(llvm::CreateAllocKindAttr(cx.llcx, AllocKindFlags::Free));
363             // applies to argument place instead of function place
364             let allocated_pointer = AttributeKind::AllocatedPointer.create_attr(cx.llcx);
365             attributes::apply_to_llfn(llfn, AttributePlace::Argument(0), &[allocated_pointer]);
366         }
367     }
368     if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::CMSE_NONSECURE_ENTRY) {
369         to_add.push(llvm::CreateAttrString(cx.llcx, "cmse_nonsecure_entry"));
370     }
371     if let Some(align) = codegen_fn_attrs.alignment {
372         llvm::set_alignment(llfn, align as usize);
373     }
374     to_add.extend(sanitize_attrs(cx, codegen_fn_attrs.no_sanitize));
375
376     // Always annotate functions with the target-cpu they are compiled for.
377     // Without this, ThinLTO won't inline Rust functions into Clang generated
378     // functions (because Clang annotates functions this way too).
379     to_add.push(target_cpu_attr(cx));
380     // tune-cpu is only conveyed through the attribute for our purpose.
381     // The target doesn't care; the subtarget reads our attribute.
382     to_add.extend(tune_cpu_attr(cx));
383
384     let function_features =
385         codegen_fn_attrs.target_features.iter().map(|f| f.as_str()).collect::<Vec<&str>>();
386
387     if let Some(f) = llvm_util::check_tied_features(
388         cx.tcx.sess,
389         &function_features.iter().map(|f| (*f, true)).collect(),
390     ) {
391         let span = cx
392             .tcx
393             .get_attrs(instance.def_id(), sym::target_feature)
394             .next()
395             .map_or_else(|| cx.tcx.def_span(instance.def_id()), |a| a.span);
396         let msg = format!(
397             "the target features {} must all be either enabled or disabled together",
398             f.join(", ")
399         );
400         let mut err = cx.tcx.sess.struct_span_err(span, &msg);
401         err.help("add the missing features in a `target_feature` attribute");
402         err.emit();
403         return;
404     }
405
406     let mut function_features = function_features
407         .iter()
408         .flat_map(|feat| {
409             llvm_util::to_llvm_features(cx.tcx.sess, feat).into_iter().map(|f| format!("+{}", f))
410         })
411         .chain(codegen_fn_attrs.instruction_set.iter().map(|x| match x {
412             InstructionSetAttr::ArmA32 => "-thumb-mode".to_string(),
413             InstructionSetAttr::ArmT32 => "+thumb-mode".to_string(),
414         }))
415         .collect::<Vec<String>>();
416
417     if cx.tcx.sess.target.is_like_wasm {
418         // If this function is an import from the environment but the wasm
419         // import has a specific module/name, apply them here.
420         if let Some(module) = wasm_import_module(cx.tcx, instance.def_id()) {
421             to_add.push(llvm::CreateAttrStringValue(cx.llcx, "wasm-import-module", &module));
422
423             let name =
424                 codegen_fn_attrs.link_name.unwrap_or_else(|| cx.tcx.item_name(instance.def_id()));
425             let name = name.as_str();
426             to_add.push(llvm::CreateAttrStringValue(cx.llcx, "wasm-import-name", name));
427         }
428
429         // The `"wasm"` abi on wasm targets automatically enables the
430         // `+multivalue` feature because the purpose of the wasm abi is to match
431         // the WebAssembly specification, which has this feature. This won't be
432         // needed when LLVM enables this `multivalue` feature by default.
433         if !cx.tcx.is_closure(instance.def_id()) {
434             let abi = cx.tcx.fn_sig(instance.def_id()).abi();
435             if abi == Abi::Wasm {
436                 function_features.push("+multivalue".to_string());
437             }
438         }
439     }
440
441     let global_features = cx.tcx.global_backend_features(()).iter().map(|s| s.as_str());
442     let function_features = function_features.iter().map(|s| s.as_str());
443     let target_features =
444         global_features.chain(function_features).intersperse(",").collect::<SmallStr<1024>>();
445     if !target_features.is_empty() {
446         to_add.push(llvm::CreateAttrStringValue(cx.llcx, "target-features", &target_features));
447     }
448
449     attributes::apply_to_llfn(llfn, Function, &to_add);
450 }
451
452 fn wasm_import_module(tcx: TyCtxt<'_>, id: DefId) -> Option<&String> {
453     tcx.wasm_import_module_map(id.krate).get(&id)
454 }