Skip to main content

rustc_codegen_llvm/
attributes.rs

1//! Set and unset common attributes on LLVM values.
2use rustc_hir::attrs::{InlineAttr, InstructionSetAttr, OptimizeAttr, RtsanSetting};
3use rustc_hir::def_id::DefId;
4use rustc_hir::find_attr;
5use rustc_middle::middle::codegen_fn_attrs::{
6    CodegenFnAttrFlags, CodegenFnAttrs, PatchableFunctionEntry, SanitizerFnAttrs, TargetFeature,
7};
8use rustc_middle::ty::{self, Instance, TyCtxt};
9use rustc_session::config::{BranchProtection, FunctionReturn, OptLevel, PAuthKey, PacRet};
10use rustc_span::sym;
11use rustc_symbol_mangling::mangle_internal_symbol;
12use rustc_target::spec::{Arch, FramePointer, SanitizerSet, StackProbeType, StackProtector};
13use smallvec::SmallVec;
14
15use crate::context::SimpleCx;
16use crate::errors::{PackedStackBackchainNeedsSoftfloat, SanitizerMemtagRequiresMte};
17use crate::llvm::AttributePlace::Function;
18use crate::llvm::{
19    self, AllocKindFlags, Attribute, AttributeKind, AttributePlace, MemoryEffects, Value,
20};
21use crate::{Session, attributes, llvm_util};
22
23pub(crate) fn apply_to_llfn(llfn: &Value, idx: AttributePlace, attrs: &[&Attribute]) {
24    if !attrs.is_empty() {
25        llvm::AddFunctionAttributes(llfn, idx, attrs);
26    }
27}
28
29pub(crate) fn apply_to_callsite(callsite: &Value, idx: AttributePlace, attrs: &[&Attribute]) {
30    if !attrs.is_empty() {
31        llvm::AddCallSiteAttributes(callsite, idx, attrs);
32    }
33}
34
35pub(crate) fn has_string_attr(llfn: &Value, name: &str) -> bool {
36    llvm::HasStringAttribute(llfn, name)
37}
38
39pub(crate) fn remove_string_attr_from_llfn(llfn: &Value, name: &str) {
40    llvm::RemoveStringAttrFromFn(llfn, name);
41}
42
43/// Get LLVM attribute for the provided inline heuristic.
44#[inline]
45pub(crate) fn inline_attr<'tcx, 'll>(
46    cx: &SimpleCx<'ll>,
47    tcx: TyCtxt<'tcx>,
48    instance: Instance<'tcx>,
49    codegen_fn_attrs: &CodegenFnAttrs,
50) -> Option<&'ll Attribute> {
51    if !tcx.sess.opts.unstable_opts.inline_llvm {
52        // disable LLVM inlining
53        return Some(AttributeKind::NoInline.create_attr(cx.llcx));
54    }
55
56    // `optnone` requires `noinline`
57    let inline = match (codegen_fn_attrs.inline, &codegen_fn_attrs.optimize) {
58        (_, OptimizeAttr::DoNotOptimize) => InlineAttr::Never,
59        (InlineAttr::None, _) if instance.def.requires_inline(tcx) => InlineAttr::Hint,
60        (inline, _) => inline,
61    };
62
63    match inline {
64        InlineAttr::Hint => Some(AttributeKind::InlineHint.create_attr(cx.llcx)),
65        InlineAttr::Always | InlineAttr::Force { .. } => {
66            Some(AttributeKind::AlwaysInline.create_attr(cx.llcx))
67        }
68        InlineAttr::Never => {
69            if tcx.sess.target.arch != Arch::AmdGpu {
70                Some(AttributeKind::NoInline.create_attr(cx.llcx))
71            } else {
72                None
73            }
74        }
75        InlineAttr::None => None,
76    }
77}
78
79#[inline]
80fn patchable_function_entry_attrs<'ll>(
81    cx: &SimpleCx<'ll>,
82    sess: &Session,
83    attr: Option<PatchableFunctionEntry>,
84) -> SmallVec<[&'ll Attribute; 2]> {
85    let mut attrs = SmallVec::new();
86    let patchable_spec = attr.unwrap_or_else(|| {
87        PatchableFunctionEntry::from_config(sess.opts.unstable_opts.patchable_function_entry)
88    });
89    let entry = patchable_spec.entry();
90    let prefix = patchable_spec.prefix();
91    if entry > 0 {
92        attrs.push(llvm::CreateAttrStringValue(
93            cx.llcx,
94            "patchable-function-entry",
95            &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}", entry))
    })format!("{}", entry),
96        ));
97    }
98    if prefix > 0 {
99        attrs.push(llvm::CreateAttrStringValue(
100            cx.llcx,
101            "patchable-function-prefix",
102            &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}", prefix))
    })format!("{}", prefix),
103        ));
104    }
105    attrs
106}
107
108/// Get LLVM sanitize attributes.
109#[inline]
110pub(crate) fn sanitize_attrs<'ll, 'tcx>(
111    cx: &SimpleCx<'ll>,
112    tcx: TyCtxt<'tcx>,
113    sanitizer_fn_attr: SanitizerFnAttrs,
114) -> SmallVec<[&'ll Attribute; 4]> {
115    let mut attrs = SmallVec::new();
116    let enabled = tcx.sess.sanitizers() - sanitizer_fn_attr.disabled;
117    if enabled.contains(SanitizerSet::ADDRESS) || enabled.contains(SanitizerSet::KERNELADDRESS) {
118        attrs.push(llvm::AttributeKind::SanitizeAddress.create_attr(cx.llcx));
119    }
120    if enabled.contains(SanitizerSet::MEMORY) {
121        attrs.push(llvm::AttributeKind::SanitizeMemory.create_attr(cx.llcx));
122    }
123    if enabled.contains(SanitizerSet::THREAD) {
124        attrs.push(llvm::AttributeKind::SanitizeThread.create_attr(cx.llcx));
125    }
126    if enabled.contains(SanitizerSet::HWADDRESS) || enabled.contains(SanitizerSet::KERNELHWADDRESS)
127    {
128        attrs.push(llvm::AttributeKind::SanitizeHWAddress.create_attr(cx.llcx));
129    }
130    if enabled.contains(SanitizerSet::SHADOWCALLSTACK) {
131        attrs.push(llvm::AttributeKind::ShadowCallStack.create_attr(cx.llcx));
132    }
133    if enabled.contains(SanitizerSet::MEMTAG) {
134        // Check to make sure the mte target feature is actually enabled.
135        let features = tcx.global_backend_features(());
136        let mte_feature =
137            features.iter().map(|s| &s[..]).rfind(|n| ["+mte", "-mte"].contains(&&n[..]));
138        if let None | Some("-mte") = mte_feature {
139            tcx.dcx().emit_err(SanitizerMemtagRequiresMte);
140        }
141
142        attrs.push(llvm::AttributeKind::SanitizeMemTag.create_attr(cx.llcx));
143    }
144    if enabled.contains(SanitizerSet::SAFESTACK) {
145        attrs.push(llvm::AttributeKind::SanitizeSafeStack.create_attr(cx.llcx));
146    }
147    if tcx.sess.sanitizers().contains(SanitizerSet::REALTIME) {
148        match sanitizer_fn_attr.rtsan_setting {
149            RtsanSetting::Nonblocking => {
150                attrs.push(llvm::AttributeKind::SanitizeRealtimeNonblocking.create_attr(cx.llcx))
151            }
152            RtsanSetting::Blocking => {
153                attrs.push(llvm::AttributeKind::SanitizeRealtimeBlocking.create_attr(cx.llcx))
154            }
155            // caller is the default, so no llvm attribute
156            RtsanSetting::Caller => (),
157        }
158    }
159    attrs
160}
161
162/// Tell LLVM to emit or not emit the information necessary to unwind the stack for the function.
163#[inline]
164pub(crate) fn uwtable_attr(llcx: &llvm::Context, use_sync_unwind: Option<bool>) -> &Attribute {
165    // NOTE: We should determine if we even need async unwind tables, as they
166    // take have more overhead and if we can use sync unwind tables we
167    // probably should.
168    let async_unwind = !use_sync_unwind.unwrap_or(false);
169    llvm::CreateUWTableAttr(llcx, async_unwind)
170}
171
172pub(crate) fn frame_pointer_type_attr<'ll>(
173    cx: &SimpleCx<'ll>,
174    sess: &Session,
175) -> Option<&'ll Attribute> {
176    let mut fp = sess.target.frame_pointer;
177    let opts = &sess.opts;
178    // "mcount" function relies on stack pointer.
179    // See <https://sourceware.org/binutils/docs/gprof/Implementation.html>.
180    if opts.unstable_opts.instrument_mcount {
181        fp.ratchet(FramePointer::Always);
182    }
183    fp.ratchet(opts.cg.force_frame_pointers);
184    let attr_value = match fp {
185        FramePointer::Always => "all",
186        FramePointer::NonLeaf => "non-leaf",
187        FramePointer::MayOmit => return None,
188    };
189    Some(llvm::CreateAttrStringValue(cx.llcx, "frame-pointer", attr_value))
190}
191
192fn function_return_attr<'ll>(cx: &SimpleCx<'ll>, sess: &Session) -> Option<&'ll Attribute> {
193    let function_return_attr = match sess.opts.unstable_opts.function_return {
194        FunctionReturn::Keep => return None,
195        FunctionReturn::ThunkExtern => AttributeKind::FnRetThunkExtern,
196    };
197
198    Some(function_return_attr.create_attr(cx.llcx))
199}
200
201/// Tell LLVM what instrument function to insert.
202#[inline]
203fn instrument_function_attr<'ll>(
204    cx: &SimpleCx<'ll>,
205    sess: &Session,
206) -> SmallVec<[&'ll Attribute; 4]> {
207    let mut attrs = SmallVec::new();
208    if sess.opts.unstable_opts.instrument_mcount {
209        // Similar to `clang -pg` behavior. Handled by the
210        // `post-inline-ee-instrument` LLVM pass.
211
212        // The function name varies on platforms.
213        // See test/CodeGen/mcount.c in clang.
214        let mcount_name = match &sess.target.llvm_mcount_intrinsic {
215            Some(llvm_mcount_intrinsic) => llvm_mcount_intrinsic.as_ref(),
216            None => sess.target.mcount.as_ref(),
217        };
218
219        attrs.push(llvm::CreateAttrStringValue(
220            cx.llcx,
221            "instrument-function-entry-inlined",
222            mcount_name,
223        ));
224    }
225    if let Some(options) = &sess.opts.unstable_opts.instrument_xray {
226        // XRay instrumentation is similar to __cyg_profile_func_{enter,exit}.
227        // Function prologue and epilogue are instrumented with NOP sleds,
228        // a runtime library later replaces them with detours into tracing code.
229        if options.always {
230            attrs.push(llvm::CreateAttrStringValue(cx.llcx, "function-instrument", "xray-always"));
231        }
232        if options.never {
233            attrs.push(llvm::CreateAttrStringValue(cx.llcx, "function-instrument", "xray-never"));
234        }
235        if options.ignore_loops {
236            attrs.push(llvm::CreateAttrString(cx.llcx, "xray-ignore-loops"));
237        }
238        // LLVM will not choose the default for us, but rather requires specific
239        // threshold in absence of "xray-always". Use the same default as Clang.
240        let threshold = options.instruction_threshold.unwrap_or(200);
241        attrs.push(llvm::CreateAttrStringValue(
242            cx.llcx,
243            "xray-instruction-threshold",
244            &threshold.to_string(),
245        ));
246        if options.skip_entry {
247            attrs.push(llvm::CreateAttrString(cx.llcx, "xray-skip-entry"));
248        }
249        if options.skip_exit {
250            attrs.push(llvm::CreateAttrString(cx.llcx, "xray-skip-exit"));
251        }
252    }
253    attrs
254}
255
256fn nojumptables_attr<'ll>(cx: &SimpleCx<'ll>, sess: &Session) -> Option<&'ll Attribute> {
257    if sess.opts.cg.jump_tables {
258        return None;
259    }
260
261    Some(llvm::CreateAttrStringValue(cx.llcx, "no-jump-tables", "true"))
262}
263
264fn probestack_attr<'ll, 'tcx>(cx: &SimpleCx<'ll>, tcx: TyCtxt<'tcx>) -> Option<&'ll Attribute> {
265    // Currently stack probes seem somewhat incompatible with the address
266    // sanitizer and thread sanitizer. With asan we're already protected from
267    // stack overflow anyway so we don't really need stack probes regardless.
268    if tcx.sess.sanitizers().intersects(SanitizerSet::ADDRESS | SanitizerSet::THREAD) {
269        return None;
270    }
271
272    // probestack doesn't play nice either with `-C profile-generate`.
273    if tcx.sess.opts.cg.profile_generate.enabled() {
274        return None;
275    }
276
277    let attr_value = match tcx.sess.target.stack_probes {
278        StackProbeType::None => return None,
279        // Request LLVM to generate the probes inline. If the given LLVM version does not support
280        // this, no probe is generated at all (even if the attribute is specified).
281        StackProbeType::Inline => "inline-asm",
282        // Flag our internal `__rust_probestack` function as the stack probe symbol.
283        // This is defined in the `compiler-builtins` crate for each architecture.
284        StackProbeType::Call => &mangle_internal_symbol(tcx, "__rust_probestack"),
285        // Pick from the two above based on the LLVM version.
286        StackProbeType::InlineOrCall { min_llvm_version_for_inline } => {
287            if llvm_util::get_version() < min_llvm_version_for_inline {
288                &mangle_internal_symbol(tcx, "__rust_probestack")
289            } else {
290                "inline-asm"
291            }
292        }
293    };
294    Some(llvm::CreateAttrStringValue(cx.llcx, "probe-stack", attr_value))
295}
296
297fn stackprotector_attr<'ll>(cx: &SimpleCx<'ll>, sess: &Session) -> Option<&'ll Attribute> {
298    let sspattr = match sess.stack_protector() {
299        StackProtector::None => return None,
300        StackProtector::All => AttributeKind::StackProtectReq,
301        StackProtector::Strong => AttributeKind::StackProtectStrong,
302        StackProtector::Basic => AttributeKind::StackProtect,
303    };
304
305    Some(sspattr.create_attr(cx.llcx))
306}
307
308fn packed_stack_attr<'ll>(
309    cx: &SimpleCx<'ll>,
310    sess: &Session,
311    function_attributes: &Vec<TargetFeature>,
312) -> Option<&'ll Attribute> {
313    if sess.target.arch != Arch::S390x {
314        return None;
315    }
316    if !sess.opts.unstable_opts.packed_stack {
317        return None;
318    }
319
320    // The backchain and softfloat flags can be set via -Ctarget-features=...
321    // or via #[target_features(enable = ...)] so we have to check both possibilities
322    let have_backchain = sess.unstable_target_features.contains(&sym::backchain)
323        || function_attributes.iter().any(|feature| feature.name == sym::backchain);
324    let have_softfloat = sess.unstable_target_features.contains(&sym::soft_float)
325        || function_attributes.iter().any(|feature| feature.name == sym::soft_float);
326
327    // If both, backchain and packedstack, are enabled LLVM cannot generate valid function entry points
328    // with the default ABI. However if the softfloat flag is set LLVM will switch to the softfloat
329    // ABI, where this works.
330    if have_backchain && !have_softfloat {
331        sess.dcx().emit_err(PackedStackBackchainNeedsSoftfloat);
332        return None;
333    }
334
335    Some(llvm::CreateAttrString(cx.llcx, "packed-stack"))
336}
337
338pub(crate) fn target_cpu_attr<'ll>(cx: &SimpleCx<'ll>, sess: &Session) -> &'ll Attribute {
339    let target_cpu = llvm_util::target_cpu(sess);
340    llvm::CreateAttrStringValue(cx.llcx, "target-cpu", target_cpu)
341}
342
343pub(crate) fn tune_cpu_attr<'ll>(cx: &SimpleCx<'ll>, sess: &Session) -> Option<&'ll Attribute> {
344    llvm_util::tune_cpu(sess)
345        .map(|tune_cpu| llvm::CreateAttrStringValue(cx.llcx, "tune-cpu", tune_cpu))
346}
347
348/// Get the `target-features` LLVM attribute.
349pub(crate) fn target_features_attr<'ll, 'tcx>(
350    cx: &SimpleCx<'ll>,
351    tcx: TyCtxt<'tcx>,
352    function_features: Vec<String>,
353) -> Option<&'ll Attribute> {
354    let global_features = tcx.global_backend_features(()).iter().map(String::as_str);
355    let function_features = function_features.iter().map(String::as_str);
356    let target_features =
357        global_features.chain(function_features).intersperse(",").collect::<String>();
358    (!target_features.is_empty())
359        .then(|| llvm::CreateAttrStringValue(cx.llcx, "target-features", &target_features))
360}
361
362/// Get the `NonLazyBind` LLVM attribute,
363/// if the codegen options allow skipping the PLT.
364pub(crate) fn non_lazy_bind_attr<'ll>(
365    cx: &SimpleCx<'ll>,
366    sess: &Session,
367) -> Option<&'ll Attribute> {
368    // Don't generate calls through PLT if it's not necessary
369    if !sess.needs_plt() { Some(AttributeKind::NonLazyBind.create_attr(cx.llcx)) } else { None }
370}
371
372/// Get the default optimizations attrs for a function.
373#[inline]
374pub(crate) fn default_optimisation_attrs<'ll>(
375    cx: &SimpleCx<'ll>,
376    sess: &Session,
377) -> SmallVec<[&'ll Attribute; 2]> {
378    let mut attrs = SmallVec::new();
379    match sess.opts.optimize {
380        OptLevel::Size => {
381            attrs.push(llvm::AttributeKind::OptimizeForSize.create_attr(cx.llcx));
382        }
383        OptLevel::SizeMin => {
384            attrs.push(llvm::AttributeKind::MinSize.create_attr(cx.llcx));
385            attrs.push(llvm::AttributeKind::OptimizeForSize.create_attr(cx.llcx));
386        }
387        _ => {}
388    }
389    attrs
390}
391
392fn create_alloc_family_attr(llcx: &llvm::Context) -> &llvm::Attribute {
393    llvm::CreateAttrStringValue(llcx, "alloc-family", "__rust_alloc")
394}
395
396/// Helper for `FnAbiLlvmExt::apply_attrs_llfn`:
397/// Composite function which sets LLVM attributes for function depending on its AST (`#[attribute]`)
398/// attributes.
399pub(crate) fn llfn_attrs_from_instance<'ll, 'tcx>(
400    cx: &SimpleCx<'ll>,
401    tcx: TyCtxt<'tcx>,
402    llfn: &'ll Value,
403    codegen_fn_attrs: &CodegenFnAttrs,
404    instance: Option<ty::Instance<'tcx>>,
405) {
406    let sess = tcx.sess;
407    let mut to_add = SmallVec::<[_; 16]>::new();
408
409    match codegen_fn_attrs.optimize {
410        OptimizeAttr::Default => {
411            to_add.extend(default_optimisation_attrs(cx, sess));
412        }
413        OptimizeAttr::DoNotOptimize => {
414            to_add.push(llvm::AttributeKind::OptimizeNone.create_attr(cx.llcx));
415        }
416        OptimizeAttr::Size => {
417            to_add.push(llvm::AttributeKind::MinSize.create_attr(cx.llcx));
418            to_add.push(llvm::AttributeKind::OptimizeForSize.create_attr(cx.llcx));
419        }
420        OptimizeAttr::Speed => {}
421    }
422
423    if let Some(instance) = instance {
424        to_add.extend(inline_attr(cx, tcx, instance, codegen_fn_attrs));
425    }
426
427    if sess.must_emit_unwind_tables() {
428        to_add.push(uwtable_attr(cx.llcx, sess.opts.unstable_opts.use_sync_unwind));
429    }
430
431    if sess.opts.unstable_opts.profile_sample_use.is_some() {
432        to_add.push(llvm::CreateAttrString(cx.llcx, "use-sample-profile"));
433    }
434
435    // FIXME: none of these functions interact with source level attributes.
436    to_add.extend(frame_pointer_type_attr(cx, sess));
437    to_add.extend(function_return_attr(cx, sess));
438    to_add.extend(instrument_function_attr(cx, sess));
439    to_add.extend(nojumptables_attr(cx, sess));
440    to_add.extend(probestack_attr(cx, tcx));
441    to_add.extend(stackprotector_attr(cx, sess));
442
443    if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NO_BUILTINS) {
444        to_add.push(llvm::CreateAttrString(cx.llcx, "no-builtins"));
445    }
446
447    if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::OFFLOAD_KERNEL) {
448        to_add.push(llvm::CreateAttrString(cx.llcx, "offload-kernel"))
449    }
450
451    if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
452        to_add.push(AttributeKind::Cold.create_attr(cx.llcx));
453    }
454    if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::FFI_PURE) {
455        to_add.push(MemoryEffects::ReadOnly.create_attr(cx.llcx));
456    }
457    if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::FFI_CONST) {
458        to_add.push(MemoryEffects::None.create_attr(cx.llcx));
459    }
460    if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
461        // do nothing; a naked function is converted into an extern function
462        // and a global assembly block. LLVM's support for naked functions is
463        // not used.
464    } else {
465        // Do not set sanitizer attributes for naked functions.
466        to_add.extend(sanitize_attrs(cx, tcx, codegen_fn_attrs.sanitizers));
467
468        // For non-naked functions, set branch protection attributes on aarch64.
469        if let Some(BranchProtection { bti, pac_ret, gcs }) =
470            sess.opts.unstable_opts.branch_protection
471        {
472            if !(sess.target.arch == Arch::AArch64) {
    ::core::panicking::panic("assertion failed: sess.target.arch == Arch::AArch64")
};assert!(sess.target.arch == Arch::AArch64);
473            if bti {
474                to_add.push(llvm::CreateAttrString(cx.llcx, "branch-target-enforcement"));
475            }
476            if gcs {
477                to_add.push(llvm::CreateAttrString(cx.llcx, "guarded-control-stack"));
478            }
479            if let Some(PacRet { leaf, pc, key }) = pac_ret {
480                if pc {
481                    to_add.push(llvm::CreateAttrString(cx.llcx, "branch-protection-pauth-lr"));
482                }
483                to_add.push(llvm::CreateAttrStringValue(
484                    cx.llcx,
485                    "sign-return-address",
486                    if leaf { "all" } else { "non-leaf" },
487                ));
488                to_add.push(llvm::CreateAttrStringValue(
489                    cx.llcx,
490                    "sign-return-address-key",
491                    if key == PAuthKey::A { "a_key" } else { "b_key" },
492                ));
493            }
494        }
495    }
496    if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::ALLOCATOR)
497        || codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::ALLOCATOR_ZEROED)
498    {
499        to_add.push(create_alloc_family_attr(cx.llcx));
500        if let Some(instance) = instance
501            && let Some(name) =
502                {
    {
        'done:
            {
            for i in
                ::rustc_hir::attrs::HasAttrs::get_attrs(instance.def_id(),
                    &tcx) {
                #[allow(unused_imports)]
                use rustc_hir::attrs::AttributeKind::*;
                let i: &rustc_hir::Attribute = i;
                match i {
                    rustc_hir::Attribute::Parsed(RustcAllocatorZeroedVariant {
                        name }) => {
                        break 'done Some(name);
                    }
                    rustc_hir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(tcx, instance.def_id(), RustcAllocatorZeroedVariant {name} => name)
503        {
504            to_add.push(llvm::CreateAttrStringValue(
505                cx.llcx,
506                "alloc-variant-zeroed",
507                &mangle_internal_symbol(tcx, name.as_str()),
508            ));
509        }
510        // apply to argument place instead of function
511        let alloc_align = AttributeKind::AllocAlign.create_attr(cx.llcx);
512        attributes::apply_to_llfn(llfn, AttributePlace::Argument(1), &[alloc_align]);
513        to_add.push(llvm::CreateAllocSizeAttr(cx.llcx, 0));
514        let mut flags = AllocKindFlags::Alloc | AllocKindFlags::Aligned;
515        if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::ALLOCATOR) {
516            flags |= AllocKindFlags::Uninitialized;
517        } else {
518            flags |= AllocKindFlags::Zeroed;
519        }
520        to_add.push(llvm::CreateAllocKindAttr(cx.llcx, flags));
521        // apply to return place instead of function (unlike all other attributes applied in this
522        // function)
523        let no_alias = AttributeKind::NoAlias.create_attr(cx.llcx);
524        attributes::apply_to_llfn(llfn, AttributePlace::ReturnValue, &[no_alias]);
525    }
526    if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::REALLOCATOR) {
527        to_add.push(create_alloc_family_attr(cx.llcx));
528        to_add.push(llvm::CreateAllocKindAttr(
529            cx.llcx,
530            AllocKindFlags::Realloc | AllocKindFlags::Aligned,
531        ));
532        // applies to argument place instead of function place
533        let allocated_pointer = AttributeKind::AllocatedPointer.create_attr(cx.llcx);
534        attributes::apply_to_llfn(llfn, AttributePlace::Argument(0), &[allocated_pointer]);
535        // apply to argument place instead of function
536        let alloc_align = AttributeKind::AllocAlign.create_attr(cx.llcx);
537        attributes::apply_to_llfn(llfn, AttributePlace::Argument(2), &[alloc_align]);
538        to_add.push(llvm::CreateAllocSizeAttr(cx.llcx, 3));
539        let no_alias = AttributeKind::NoAlias.create_attr(cx.llcx);
540        attributes::apply_to_llfn(llfn, AttributePlace::ReturnValue, &[no_alias]);
541    }
542    if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::DEALLOCATOR) {
543        to_add.push(create_alloc_family_attr(cx.llcx));
544        to_add.push(llvm::CreateAllocKindAttr(cx.llcx, AllocKindFlags::Free));
545        // applies to argument place instead of function place
546        let allocated_pointer = AttributeKind::AllocatedPointer.create_attr(cx.llcx);
547        // "Does not capture provenance" means "if the function call stashes the pointer somewhere,
548        // accessing that pointer after the function returns is UB". That is definitely the case here since
549        // freeing will destroy the provenance.
550        let captures_addr = AttributeKind::CapturesAddress.create_attr(cx.llcx);
551        let attrs = &[allocated_pointer, captures_addr];
552        attributes::apply_to_llfn(llfn, AttributePlace::Argument(0), attrs);
553    }
554    if let Some(align) = codegen_fn_attrs.alignment {
555        llvm::set_alignment(llfn, align);
556    }
557    if let Some(packed_stack) = packed_stack_attr(cx, sess, &codegen_fn_attrs.target_features) {
558        to_add.push(packed_stack);
559    }
560    to_add.extend(patchable_function_entry_attrs(
561        cx,
562        sess,
563        codegen_fn_attrs.patchable_function_entry,
564    ));
565
566    // Always annotate functions with the target-cpu they are compiled for.
567    // Without this, ThinLTO won't inline Rust functions into Clang generated
568    // functions (because Clang annotates functions this way too).
569    to_add.push(target_cpu_attr(cx, sess));
570    // tune-cpu is only conveyed through the attribute for our purpose.
571    // The target doesn't care; the subtarget reads our attribute.
572    to_add.extend(tune_cpu_attr(cx, sess));
573
574    let function_features =
575        codegen_fn_attrs.target_features.iter().map(|f| f.name.as_str()).collect::<Vec<&str>>();
576
577    let function_features = function_features
578        .iter()
579        // Convert to LLVMFeatures and filter out unavailable ones
580        .flat_map(|feat| llvm_util::to_llvm_features(sess, feat))
581        // Convert LLVMFeatures & dependencies to +<feats>s
582        .flat_map(|feat| feat.into_iter().map(|f| ::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("+{0}", f)) })format!("+{f}")))
583        .chain(codegen_fn_attrs.instruction_set.iter().map(|x| match x {
584            InstructionSetAttr::ArmA32 => "-thumb-mode".to_string(),
585            InstructionSetAttr::ArmT32 => "+thumb-mode".to_string(),
586        }))
587        .collect::<Vec<String>>();
588
589    if sess.target.is_like_wasm {
590        // If this function is an import from the environment but the wasm
591        // import has a specific module/name, apply them here.
592        if let Some(instance) = instance
593            && let Some(module) = wasm_import_module(tcx, instance.def_id())
594        {
595            to_add.push(llvm::CreateAttrStringValue(cx.llcx, "wasm-import-module", module));
596
597            let name =
598                codegen_fn_attrs.symbol_name.unwrap_or_else(|| tcx.item_name(instance.def_id()));
599            let name = name.as_str();
600            to_add.push(llvm::CreateAttrStringValue(cx.llcx, "wasm-import-name", name));
601        }
602    }
603
604    to_add.extend(target_features_attr(cx, tcx, function_features));
605
606    attributes::apply_to_llfn(llfn, Function, &to_add);
607}
608
609fn wasm_import_module(tcx: TyCtxt<'_>, id: DefId) -> Option<&String> {
610    tcx.wasm_import_module_map(id.krate).get(&id)
611}