Skip to main content

rustc_codegen_ssa/
codegen_attrs.rs

1use rustc_abi::{Align, ExternAbi};
2use rustc_hir::attrs::{
3    AttributeKind, EiiImplResolution, InlineAttr, InstrumentFnAttr as HirInstrumentFnAttr, Linkage,
4    OptimizeAttr, RtsanSetting, UsedBy,
5};
6use rustc_hir::def::DefKind;
7use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId};
8use rustc_hir::{self as hir, Attribute, find_attr};
9use rustc_macros::Diagnostic;
10use rustc_middle::bug;
11use rustc_middle::middle::codegen_fn_attrs::{
12    CodegenFnAttrFlags, CodegenFnAttrs, InstrumentFnAttr, PatchableFunctionEntry, SanitizerFnAttrs,
13};
14use rustc_middle::mono::Visibility;
15use rustc_middle::query::Providers;
16use rustc_middle::ty::{self as ty, TyCtxt};
17use rustc_session::diagnostics::feature_err;
18use rustc_session::lint;
19use rustc_span::{Span, sym};
20use rustc_target::spec::Os;
21
22use crate::diagnostics;
23use crate::target_features::{
24    check_target_feature_trait_unsafe, check_tied_features, from_target_feature_attr,
25};
26
27/// In some cases, attributes are only valid on functions, but it's the `check_attr`
28/// pass that checks that they aren't used anywhere else, rather than this module.
29/// In these cases, we bail from performing further checks that are only meaningful for
30/// functions (such as calling `fn_sig`, which ICEs if given a non-function). We also
31/// report a delayed bug, just in case `check_attr` isn't doing its job.
32fn try_fn_sig<'tcx>(
33    tcx: TyCtxt<'tcx>,
34    did: LocalDefId,
35    attr_span: Span,
36) -> Option<ty::EarlyBinder<'tcx, ty::PolyFnSig<'tcx>>> {
37    use DefKind::*;
38
39    let def_kind = tcx.def_kind(did);
40    if let Fn | AssocFn | Variant | Ctor(..) = def_kind {
41        Some(tcx.fn_sig(did))
42    } else {
43        tcx.dcx().span_delayed_bug(attr_span, "this attribute can only be applied to functions");
44        None
45    }
46}
47
48/// Spans that are collected when processing built-in attributes,
49/// that are useful for emitting diagnostics later.
50#[derive(#[automatically_derived]
impl ::core::default::Default for InterestingAttributeDiagnosticSpans {
    #[inline]
    fn default() -> InterestingAttributeDiagnosticSpans {
        InterestingAttributeDiagnosticSpans {
            link_ordinal: ::core::default::Default::default(),
            sanitize: ::core::default::Default::default(),
            inline: ::core::default::Default::default(),
            no_mangle: ::core::default::Default::default(),
        }
    }
}Default)]
51struct InterestingAttributeDiagnosticSpans {
52    link_ordinal: Option<Span>,
53    sanitize: Option<Span>,
54    inline: Option<Span>,
55    no_mangle: Option<Span>,
56}
57
58/// Process the builtin attrs ([`hir::Attribute`]) on the item.
59/// Many of them directly translate to codegen attrs.
60fn process_builtin_attrs(
61    tcx: TyCtxt<'_>,
62    did: LocalDefId,
63    attrs: &[Attribute],
64    codegen_fn_attrs: &mut CodegenFnAttrs,
65) -> InterestingAttributeDiagnosticSpans {
66    let mut interesting_spans = InterestingAttributeDiagnosticSpans::default();
67    let rust_target_features = tcx.rust_target_features(LOCAL_CRATE);
68
69    let parsed_attrs = attrs
70        .iter()
71        .filter_map(|attr| if let hir::Attribute::Parsed(attr) = attr { Some(attr) } else { None });
72    for attr in parsed_attrs {
73        match attr {
74            AttributeKind::Cold => codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD,
75            AttributeKind::ExportName { name, .. } => codegen_fn_attrs.symbol_name = Some(*name),
76            AttributeKind::Inline(inline, span) => {
77                codegen_fn_attrs.inline = *inline;
78                interesting_spans.inline = Some(*span);
79            }
80            AttributeKind::Naked(_) => codegen_fn_attrs.flags |= CodegenFnAttrFlags::NAKED,
81            AttributeKind::RustcAlign { align, .. } => codegen_fn_attrs.alignment = Some(*align),
82            AttributeKind::LinkName { name, .. } => {
83                // FIXME Remove check for foreign functions once #[link_name] on non-foreign
84                // functions is a hard error
85                if tcx.is_foreign_item(did) {
86                    codegen_fn_attrs.symbol_name = Some(*name);
87                }
88            }
89            AttributeKind::LinkOrdinal { ordinal, span } => {
90                codegen_fn_attrs.link_ordinal = Some(*ordinal);
91                interesting_spans.link_ordinal = Some(*span);
92            }
93            AttributeKind::LinkSection { name } => codegen_fn_attrs.link_section = Some(*name),
94            AttributeKind::NoMangle(attr_span) => {
95                interesting_spans.no_mangle = Some(*attr_span);
96                if tcx.opt_item_name(did.to_def_id()).is_some() {
97                    codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
98                } else {
99                    tcx.dcx()
100                        .span_delayed_bug(*attr_span, "no_mangle should be on a named function");
101                }
102            }
103            AttributeKind::Optimize(optimize, _) => codegen_fn_attrs.optimize = *optimize,
104            AttributeKind::TargetFeature { features, attr_span, was_forced } => {
105                let Some(sig) = tcx.hir_node_by_def_id(did).fn_sig() else {
106                    tcx.dcx().span_delayed_bug(*attr_span, "target_feature applied to non-fn");
107                    continue;
108                };
109                let safe_target_features =
110                    #[allow(non_exhaustive_omitted_patterns)] match sig.header.safety {
    hir::HeaderSafety::SafeTargetFeatures => true,
    _ => false,
}matches!(sig.header.safety, hir::HeaderSafety::SafeTargetFeatures);
111                codegen_fn_attrs.safe_target_features = safe_target_features;
112                if safe_target_features && !was_forced {
113                    if tcx.sess.target.is_like_wasm || tcx.sess.opts.actually_rustdoc {
114                        // The `#[target_feature]` attribute is allowed on
115                        // WebAssembly targets on all functions. Prior to stabilizing
116                        // the `target_feature_11` feature, `#[target_feature]` was
117                        // only permitted on unsafe functions because on most targets
118                        // execution of instructions that are not supported is
119                        // considered undefined behavior. For WebAssembly which is a
120                        // 100% safe target at execution time it's not possible to
121                        // execute undefined instructions, and even if a future
122                        // feature was added in some form for this it would be a
123                        // deterministic trap. There is no undefined behavior when
124                        // executing WebAssembly so `#[target_feature]` is allowed
125                        // on safe functions (but again, only for WebAssembly)
126                        //
127                        // Note that this is also allowed if `actually_rustdoc` so
128                        // if a target is documenting some wasm-specific code then
129                        // it's not spuriously denied.
130                        //
131                        // Now that `#[target_feature]` is permitted on safe functions,
132                        // this exception must still exist for allowing the attribute on
133                        // `main`, `start`, and other functions that are not usually
134                        // allowed.
135                    } else {
136                        check_target_feature_trait_unsafe(tcx, did, *attr_span);
137                    }
138                }
139                from_target_feature_attr(
140                    tcx,
141                    did,
142                    features,
143                    *was_forced,
144                    rust_target_features,
145                    &mut codegen_fn_attrs.target_features,
146                );
147            }
148            AttributeKind::TrackCaller(attr_span) => {
149                let is_closure = tcx.is_closure_like(did.to_def_id());
150
151                if !is_closure
152                    && let Some(fn_sig) = try_fn_sig(tcx, did, *attr_span)
153                    && fn_sig.skip_binder().abi() != ExternAbi::Rust
154                {
155                    // This error is already reported in `rustc_ast_passes/src/ast_validation.rs`.
156                    tcx.dcx().delayed_bug("`#[track_caller]` requires the Rust ABI");
157                }
158                if is_closure
159                    && !tcx.features().closure_track_caller()
160                    && !attr_span.allows_unstable(sym::closure_track_caller)
161                {
162                    feature_err(
163                        &tcx.sess,
164                        sym::closure_track_caller,
165                        *attr_span,
166                        "`#[track_caller]` on closures is currently unstable",
167                    )
168                    .emit();
169                }
170                codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER
171            }
172            AttributeKind::Used { used_by } => match used_by {
173                UsedBy::Compiler => codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED_COMPILER,
174                UsedBy::Linker => codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED_LINKER,
175                UsedBy::Default => {
176                    let used_form = if tcx.sess.target.os == Os::Illumos {
177                        // illumos' `ld` doesn't support a section header that would represent
178                        // `#[used(linker)]`, see
179                        // https://github.com/rust-lang/rust/issues/146169. For that target,
180                        // downgrade as if `#[used(compiler)]` was requested and hope for the
181                        // best.
182                        CodegenFnAttrFlags::USED_COMPILER
183                    } else {
184                        CodegenFnAttrFlags::USED_LINKER
185                    };
186                    codegen_fn_attrs.flags |= used_form;
187                }
188            },
189            AttributeKind::FfiConst => codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_CONST,
190            AttributeKind::FfiPure(_) => codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_PURE,
191            AttributeKind::RustcStdInternalSymbol => {
192                codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL
193            }
194            AttributeKind::Linkage(linkage, span) => {
195                let linkage = Some(*linkage);
196
197                if tcx.is_foreign_item(did) {
198                    codegen_fn_attrs.import_linkage = linkage;
199
200                    if tcx.is_mutable_static(did.into()) {
201                        let mut diag = tcx.dcx().struct_span_err(
202                            *span,
203                            "extern mutable statics are not allowed with `#[linkage]`",
204                        );
205                        diag.note(
206                            "marking the extern static mutable would allow changing which \
207                            symbol the static references rather than make the target of the \
208                            symbol mutable",
209                        );
210                        diag.emit();
211                    }
212                } else {
213                    codegen_fn_attrs.linkage = linkage;
214                }
215            }
216            AttributeKind::Sanitize { span, .. } => {
217                interesting_spans.sanitize = Some(*span);
218            }
219            AttributeKind::RustcObjcClass { classname } => {
220                codegen_fn_attrs.objc_class = Some(*classname);
221            }
222            AttributeKind::RustcObjcSelector { methname } => {
223                codegen_fn_attrs.objc_selector = Some(*methname);
224            }
225            AttributeKind::RustcEiiForeignItem => {
226                codegen_fn_attrs.flags |= CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM;
227            }
228            AttributeKind::EiiImpls(impls) => {
229                for i in impls {
230                    let foreign_item = match i.resolution {
231                        EiiImplResolution::Macro(def_id) => {
232                            let Some(extern_item) = {
    {
        'done:
            {
            for i in ::rustc_hir::attrs::HasAttrs::get_attrs(def_id, &tcx) {
                #[allow(unused_imports)]
                use rustc_hir::attrs::AttributeKind::*;
                let i: &rustc_hir::Attribute = i;
                match i {
                    rustc_hir::Attribute::Parsed(EiiDeclaration(target)) => {
                        break 'done Some(target.foreign_item);
                    }
                    rustc_hir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(tcx, def_id, EiiDeclaration(target) => target.foreign_item
233                            ) else {
234                                tcx.dcx().span_delayed_bug(
235                                    i.span,
236                                    "resolved to something that's not an EII",
237                                );
238                                continue;
239                            };
240                            extern_item
241                        }
242                        EiiImplResolution::Known(def_id) => def_id,
243                        EiiImplResolution::Error(_eg) => continue,
244                    };
245
246                    // this is to prevent a bug where a single crate defines both the default and explicit implementation
247                    // for an EII. In that case, both of them may be part of the same final object file. I'm not 100% sure
248                    // what happens, either rustc deduplicates the symbol or llvm, or it's random/order-dependent.
249                    // However, the fact that the default one of has weak linkage isn't considered and you sometimes get that
250                    // the default implementation is used while an explicit implementation is given.
251                    if
252                    // if this is a default impl
253                    i.is_default
254                        // iterate over all implementations *in the current crate*
255                        // (this is ok since we generate codegen fn attrs in the local crate)
256                        // if any of them is *not default* then don't emit the alias.
257                        && {
258                            let (_, impls) = tcx.externally_implementable_items(LOCAL_CRATE).get(&foreign_item).unwrap_or_else(|| ::rustc_middle::util::bug::bug_fmt(format_args!("EII impl should have an entry"))bug!("EII impl should have an entry"));
259                            impls.iter().any(|(_, imp)| !imp.is_default)
260                        }
261                    {
262                        continue;
263                    }
264
265                    codegen_fn_attrs.foreign_item_symbol_aliases.push((
266                        foreign_item,
267                        if i.is_default { Linkage::WeakAny } else { Linkage::External },
268                        Visibility::Default,
269                    ));
270                    codegen_fn_attrs.flags |= CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM;
271
272                    // If the declaration is `#[track_caller]`, derive it onto the implementation
273                    // too. The shim that forwards to this impl (see `add_function_aliases`) takes
274                    // its ABI from the impl's `fn_abi`, so every impl must agree on whether the
275                    // caller-location argument is present, otherwise it would be silently dropped.
276                    if tcx
277                        .codegen_fn_attrs(foreign_item)
278                        .flags
279                        .contains(CodegenFnAttrFlags::TRACK_CALLER)
280                    {
281                        codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
282                    }
283                }
284            }
285            AttributeKind::ThreadLocal => {
286                codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL
287            }
288            AttributeKind::InstructionSet(instruction_set) => {
289                codegen_fn_attrs.instruction_set = Some(*instruction_set)
290            }
291            AttributeKind::RustcAllocator => {
292                codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR
293            }
294            AttributeKind::RustcDeallocator => {
295                codegen_fn_attrs.flags |= CodegenFnAttrFlags::DEALLOCATOR
296            }
297            AttributeKind::RustcReallocator => {
298                codegen_fn_attrs.flags |= CodegenFnAttrFlags::REALLOCATOR
299            }
300            AttributeKind::RustcAllocatorZeroed => {
301                codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR_ZEROED
302            }
303            AttributeKind::RustcNounwind => {
304                codegen_fn_attrs.flags |= CodegenFnAttrFlags::NEVER_UNWIND
305            }
306            AttributeKind::RustcOffloadKernel => {
307                codegen_fn_attrs.flags |= CodegenFnAttrFlags::OFFLOAD_KERNEL
308            }
309            AttributeKind::PatchableFunctionEntry { prefix, entry, section } => {
310                codegen_fn_attrs.patchable_function_entry =
311                    Some(PatchableFunctionEntry::from_prefix_entry_and_section(
312                        *prefix, *entry, *section,
313                    ));
314            }
315            AttributeKind::InstrumentFn(instrument_fn) => {
316                codegen_fn_attrs.instrument_fn = match instrument_fn {
317                    HirInstrumentFnAttr::On => InstrumentFnAttr::On,
318                    HirInstrumentFnAttr::Off => InstrumentFnAttr::Off,
319                };
320            }
321            _ => {}
322        }
323    }
324
325    interesting_spans
326}
327
328/// Applies overrides for codegen fn attrs. These often have a specific reason why they're necessary.
329/// Please comment why when adding a new one!
330fn apply_overrides(tcx: TyCtxt<'_>, did: LocalDefId, codegen_fn_attrs: &mut CodegenFnAttrs) {
331    // Apply the minimum function alignment here. This ensures that a function's alignment is
332    // determined by the `-C` flags of the crate it is defined in, not the `-C` flags of the crate
333    // it happens to be codegen'd (or const-eval'd) in.
334    codegen_fn_attrs.alignment =
335        Ord::max(codegen_fn_attrs.alignment, tcx.sess.opts.unstable_opts.min_function_alignment);
336
337    // Passed in sanitizer settings are always the default.
338    if !(codegen_fn_attrs.sanitizers == SanitizerFnAttrs::default()) {
    ::core::panicking::panic("assertion failed: codegen_fn_attrs.sanitizers == SanitizerFnAttrs::default()")
};assert!(codegen_fn_attrs.sanitizers == SanitizerFnAttrs::default());
339    // Replace with #[sanitize] value
340    codegen_fn_attrs.sanitizers = tcx.sanitizer_settings_for(did);
341    // On trait methods, inherit the `#[align]` of the trait's method prototype.
342    codegen_fn_attrs.alignment = Ord::max(codegen_fn_attrs.alignment, tcx.inherited_align(did));
343
344    // naked function MUST NOT be inlined! This attribute is required for the rust compiler itself,
345    // but not for the code generation backend because at that point the naked function will just be
346    // a declaration, with a definition provided in global assembly.
347    if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
348        codegen_fn_attrs.inline = InlineAttr::Never;
349    }
350
351    // #73631: closures inherit `#[target_feature]` annotations
352    //
353    // If this closure is marked `#[inline(always)]`, simply skip adding `#[target_feature]`.
354    //
355    // At this point, `unsafe` has already been checked and `#[target_feature]` only affects codegen.
356    // Due to LLVM limitations, emitting both `#[inline(always)]` and `#[target_feature]` is *unsound*:
357    // the function may be inlined into a caller with fewer target features. Also see
358    // <https://github.com/rust-lang/rust/issues/116573>.
359    //
360    // Using `#[inline(always)]` implies that this closure will most likely be inlined into
361    // its parent function, which effectively inherits the features anyway. Boxing this closure
362    // would result in this closure being compiled without the inherited target features, but this
363    // is probably a poor usage of `#[inline(always)]` and easily avoided by not using the attribute.
364    if tcx.is_closure_like(did.to_def_id()) && codegen_fn_attrs.inline != InlineAttr::Always {
365        let owner_id = tcx.parent(did.to_def_id());
366        if tcx.def_kind(owner_id).has_codegen_attrs() {
367            codegen_fn_attrs
368                .target_features
369                .extend(tcx.codegen_fn_attrs(owner_id).target_features.iter().copied());
370        }
371    }
372
373    // Closures inherit `#[optimize]` annotations.
374    if tcx.is_closure_like(did.to_def_id()) {
375        let owner_id = tcx.parent(did.to_def_id());
376        if tcx.def_kind(owner_id).has_codegen_attrs() {
377            let owner_attrs = tcx.codegen_fn_attrs(owner_id);
378            if codegen_fn_attrs.optimize == OptimizeAttr::Default {
379                codegen_fn_attrs.optimize = owner_attrs.optimize;
380            }
381        }
382    }
383
384    // When `no_builtins` is applied at the crate level, we should add the
385    // `no-builtins` attribute to each function to ensure it takes effect in LTO.
386    let no_builtins = {
        'done:
            {
            for i in tcx.hir_krate_attrs() {
                #[allow(unused_imports)]
                use rustc_hir::attrs::AttributeKind::*;
                let i: &rustc_hir::Attribute = i;
                match i {
                    rustc_hir::Attribute::Parsed(NoBuiltins) => {
                        break 'done Some(());
                    }
                    rustc_hir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }.is_some()find_attr!(tcx, crate, NoBuiltins);
387    if no_builtins {
388        codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_BUILTINS;
389    }
390
391    // inherit track-caller properly
392    if tcx.should_inherit_track_caller(did) {
393        codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
394    }
395
396    // Foreign items by default use no mangling for their symbol name.
397    if tcx.is_foreign_item(did) {
398        codegen_fn_attrs.flags |= CodegenFnAttrFlags::FOREIGN_ITEM;
399
400        // There's a few exceptions to this rule though:
401        if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) {
402            // * `#[rustc_std_internal_symbol]` mangles the symbol name in a special way
403            //   both for exports and imports through foreign items. This is handled further,
404            //   during symbol mangling logic.
405        } else if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM)
406        {
407            // * externally implementable items keep their mangled symbol name.
408            //   multiple EIIs can have the same name, so not mangling them would be a bug.
409            //   Implementing an EII does the appropriate name resolution to make sure the implementations
410            //   get the same symbol name as the *mangled* foreign item they refer to so that's all good.
411        } else if codegen_fn_attrs.symbol_name.is_some() {
412            // * This can be overridden with the `#[link_name]` attribute
413        } else {
414            // NOTE: there's one more exception that we cannot apply here. On wasm,
415            // some items cannot be `no_mangle`.
416            // However, we don't have enough information here to determine that.
417            // As such, no_mangle foreign items on wasm that have the same defid as some
418            // import will *still* be mangled despite this.
419            //
420            // if none of the exceptions apply; apply no_mangle
421            codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
422        }
423    }
424}
425
426#[derive(const _: () =
    {
        impl<'_sess, G> rustc_errors::Diagnostic<'_sess, G> for
            SanitizeOnInline where G: rustc_errors::EmissionGuarantee {
            #[track_caller]
            fn into_diag(self, dcx: rustc_errors::DiagCtxtHandle<'_sess>,
                level: rustc_errors::Level) -> rustc_errors::Diag<'_sess, G> {
                match self {
                    SanitizeOnInline { inline_span: __binding_0 } => {
                        let mut diag =
                            rustc_errors::Diag::new(dcx, level,
                                rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("non-default `sanitize` will have no effect after inlining")));
                        ;
                        diag.span_note(__binding_0,
                            rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("inlining requested here")));
                        diag
                    }
                }
            }
        }
    };Diagnostic)]
427#[diag("non-default `sanitize` will have no effect after inlining")]
428struct SanitizeOnInline {
429    #[note("inlining requested here")]
430    inline_span: Span,
431}
432
433#[derive(const _: () =
    {
        impl<'_sess, G> rustc_errors::Diagnostic<'_sess, G> for AsyncBlocking
            where G: rustc_errors::EmissionGuarantee {
            #[track_caller]
            fn into_diag(self, dcx: rustc_errors::DiagCtxtHandle<'_sess>,
                level: rustc_errors::Level) -> rustc_errors::Diag<'_sess, G> {
                match self {
                    AsyncBlocking => {
                        let mut diag =
                            rustc_errors::Diag::new(dcx, level,
                                rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("the async executor can run blocking code, without realtime sanitizer catching it")));
                        ;
                        diag
                    }
                }
            }
        }
    };Diagnostic)]
434#[diag("the async executor can run blocking code, without realtime sanitizer catching it")]
435struct AsyncBlocking;
436
437fn check_result(
438    tcx: TyCtxt<'_>,
439    did: LocalDefId,
440    interesting_spans: InterestingAttributeDiagnosticSpans,
441    codegen_fn_attrs: &CodegenFnAttrs,
442) {
443    // If a function uses `#[target_feature]` it can't be inlined into general
444    // purpose functions as they wouldn't have the right target features
445    // enabled. For that reason we also forbid `#[inline(always)]` as it can't be
446    // respected.
447    //
448    // `#[rustc_force_inline]` doesn't need to be prohibited here, only
449    // `#[inline(always)]`, as forced inlining is implemented entirely within
450    // rustc (and so the MIR inliner can do any necessary checks for compatible target
451    // features).
452    //
453    // This sidesteps the LLVM blockers in enabling `target_features` +
454    // `inline(always)` to be used together (see rust-lang/rust#116573 and
455    // llvm/llvm-project#70563).
456    if !codegen_fn_attrs.target_features.is_empty()
457        && #[allow(non_exhaustive_omitted_patterns)] match codegen_fn_attrs.inline {
    InlineAttr::Always => true,
    _ => false,
}matches!(codegen_fn_attrs.inline, InlineAttr::Always)
458        && let Some(span) = interesting_spans.inline
459    {
460        let mut diag = tcx
461            .dcx()
462            .struct_span_err(span, "cannot use `#[inline(always)]` with `#[target_feature]`");
463        diag.note(
464            "See this issue for full discussion: \
465            https://github.com/rust-lang/rust/issues/145574",
466        );
467        diag.emit();
468    }
469
470    // warn that inline has no effect when no_sanitize is present
471    if codegen_fn_attrs.sanitizers != SanitizerFnAttrs::default()
472        && codegen_fn_attrs.inline.always()
473        && let (Some(sanitize_span), Some(inline_span)) =
474            (interesting_spans.sanitize, interesting_spans.inline)
475    {
476        let hir_id = tcx.local_def_id_to_hir_id(did);
477        tcx.emit_node_span_lint(
478            lint::builtin::INLINE_NO_SANITIZE,
479            hir_id,
480            sanitize_span,
481            SanitizeOnInline { inline_span },
482        )
483    }
484
485    // warn for nonblocking async functions, blocks and closures.
486    // This doesn't behave as expected, because the executor can run blocking code without the sanitizer noticing.
487    if codegen_fn_attrs.sanitizers.rtsan_setting == RtsanSetting::Nonblocking
488        && let Some(sanitize_span) = interesting_spans.sanitize
489        // async fn
490        && (tcx.asyncness(did).is_async()
491            // async block
492            || tcx.is_coroutine(did.into())
493            // async closure
494            || (tcx.is_closure_like(did.into())
495                && tcx.hir_node_by_def_id(did).expect_closure().kind
496                    != rustc_hir::ClosureKind::Closure))
497    {
498        let hir_id = tcx.local_def_id_to_hir_id(did);
499        tcx.emit_node_span_lint(
500            lint::builtin::RTSAN_NONBLOCKING_ASYNC,
501            hir_id,
502            sanitize_span,
503            AsyncBlocking,
504        );
505    }
506
507    // error when specifying link_name together with link_ordinal
508    if let Some(_) = codegen_fn_attrs.symbol_name
509        && let Some(_) = codegen_fn_attrs.link_ordinal
510    {
511        let msg = "cannot use `#[link_name]` with `#[link_ordinal]`";
512        if let Some(span) = interesting_spans.link_ordinal {
513            tcx.dcx().span_err(span, msg);
514        } else {
515            tcx.dcx().err(msg);
516        }
517    }
518
519    if let Some(features) = check_tied_features(
520        tcx.sess,
521        &codegen_fn_attrs
522            .target_features
523            .iter()
524            .map(|features| (features.name.as_str(), true))
525            .collect(),
526    ) {
527        let span = {
    {
        'done:
            {
            for i in ::rustc_hir::attrs::HasAttrs::get_attrs(did, &tcx) {
                #[allow(unused_imports)]
                use rustc_hir::attrs::AttributeKind::*;
                let i: &rustc_hir::Attribute = i;
                match i {
                    rustc_hir::Attribute::Parsed(TargetFeature {
                        attr_span: span, .. }) => {
                        break 'done Some(*span);
                    }
                    rustc_hir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(tcx, did, TargetFeature{attr_span: span, ..} => *span)
528            .unwrap_or_else(|| tcx.def_span(did));
529
530        tcx.dcx()
531            .create_err(diagnostics::TargetFeatureDisableOrEnable {
532                features,
533                span: Some(span),
534                missing_features: Some(diagnostics::MissingFeatures),
535            })
536            .emit();
537    }
538}
539
540fn handle_lang_items(
541    tcx: TyCtxt<'_>,
542    did: LocalDefId,
543    interesting_spans: &InterestingAttributeDiagnosticSpans,
544    attrs: &[Attribute],
545    codegen_fn_attrs: &mut CodegenFnAttrs,
546) {
547    let lang_item = {
    'done:
        {
        for i in attrs {
            #[allow(unused_imports)]
            use rustc_hir::attrs::AttributeKind::*;
            let i: &rustc_hir::Attribute = i;
            match i {
                rustc_hir::Attribute::Parsed(Lang(lang)) => {
                    break 'done Some(lang);
                }
                rustc_hir::Attribute::Unparsed(..) =>
                    {}
                    #[deny(unreachable_patterns)]
                    _ => {}
            }
        }
        None
    }
}find_attr!(attrs, Lang(lang) => lang);
548
549    // Weak lang items have the same semantics as "std internal" symbols in the
550    // sense that they're preserved through all our LTO passes and only
551    // strippable by the linker.
552    //
553    // Additionally weak lang items have predetermined symbol names.
554    if let Some(lang_item) = lang_item
555        && let Some(link_name) = lang_item.link_name()
556    {
557        codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
558        codegen_fn_attrs.symbol_name = Some(link_name);
559    }
560
561    // error when using no_mangle on a lang item item
562    if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL)
563        && codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NO_MANGLE)
564    {
565        let mut err = tcx
566            .dcx()
567            .struct_span_err(
568                interesting_spans.no_mangle.unwrap_or_default(),
569                "`#[no_mangle]` cannot be used on internal language items",
570            )
571            .with_note("Rustc requires this item to have a specific mangled name.")
572            .with_span_label(tcx.def_span(did), "should be the internal language item");
573        if let Some(lang_item) = lang_item
574            && let Some(link_name) = lang_item.link_name()
575        {
576            err = err
577                .with_note("If you are trying to prevent mangling to ease debugging, many")
578                .with_note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("debuggers support a command such as `rbreak {0}` to",
                link_name))
    })format!("debuggers support a command such as `rbreak {link_name}` to"))
579                .with_note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("match `.*{0}.*` instead of `break {0}` on a specific name",
                link_name))
    })format!(
580                    "match `.*{link_name}.*` instead of `break {link_name}` on a specific name"
581                ))
582        }
583        err.emit();
584    }
585}
586
587/// Generate the [`CodegenFnAttrs`] for an item (identified by the [`LocalDefId`]).
588///
589/// This happens in 4 stages:
590/// - apply built-in attributes that directly translate to codegen attributes.
591/// - handle lang items. These have special codegen attrs applied to them.
592/// - apply overrides, like minimum requirements for alignment and other settings that don't rely directly the built-in attrs on the item.
593///   overrides come after applying built-in attributes since they may only apply when certain attributes were already set in the stage before.
594/// - check that the result is valid. There's various ways in which this may not be the case, such as certain combinations of attrs.
595fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
596    if truecfg!(debug_assertions) {
597        let def_kind = tcx.def_kind(did);
598        if !def_kind.has_codegen_attrs() {
    {
        ::core::panicking::panic_fmt(format_args!("unexpected `def_kind` in `codegen_fn_attrs`: {0:?}",
                def_kind));
    }
};assert!(
599            def_kind.has_codegen_attrs(),
600            "unexpected `def_kind` in `codegen_fn_attrs`: {def_kind:?}",
601        );
602    }
603
604    let mut codegen_fn_attrs = CodegenFnAttrs::new();
605    let attrs = tcx.hir_attrs(tcx.local_def_id_to_hir_id(did));
606
607    let interesting_spans = process_builtin_attrs(tcx, did, attrs, &mut codegen_fn_attrs);
608    handle_lang_items(tcx, did, &interesting_spans, attrs, &mut codegen_fn_attrs);
609    apply_overrides(tcx, did, &mut codegen_fn_attrs);
610    check_result(tcx, did, interesting_spans, &codegen_fn_attrs);
611
612    codegen_fn_attrs
613}
614
615fn sanitizer_settings_for(tcx: TyCtxt<'_>, did: LocalDefId) -> SanitizerFnAttrs {
616    // Backtrack to the crate root.
617    let mut settings = match tcx.opt_local_parent(did) {
618        // Check the parent (recursively).
619        Some(parent) => tcx.sanitizer_settings_for(parent),
620        // We reached the crate root without seeing an attribute, so
621        // there is no sanitizers to exclude.
622        None => SanitizerFnAttrs::default(),
623    };
624
625    // Check for a sanitize annotation directly on this def.
626    if let Some((on_set, off_set, rtsan)) =
627        {
    {
        'done:
            {
            for i in ::rustc_hir::attrs::HasAttrs::get_attrs(did, &tcx) {
                #[allow(unused_imports)]
                use rustc_hir::attrs::AttributeKind::*;
                let i: &rustc_hir::Attribute = i;
                match i {
                    rustc_hir::Attribute::Parsed(Sanitize {
                        on_set, off_set, rtsan, .. }) => {
                        break 'done Some((on_set, off_set, rtsan));
                    }
                    rustc_hir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(tcx, did, Sanitize {on_set, off_set, rtsan, ..} => (on_set, off_set, rtsan))
628    {
629        // the on set is the set of sanitizers explicitly enabled.
630        // we mask those out since we want the set of disabled sanitizers here
631        settings.disabled &= !*on_set;
632        // the off set is the set of sanitizers explicitly disabled.
633        // we or those in here.
634        settings.disabled |= *off_set;
635        // the on set and off set are distjoint since there's a third option: unset.
636        // a node may not set the sanitizer setting in which case it inherits from parents.
637        // the code above in this function does this backtracking
638
639        // if rtsan was specified here override the parent
640        if let Some(rtsan) = rtsan {
641            settings.rtsan_setting = *rtsan;
642        }
643    }
644    settings
645}
646
647/// Checks if the provided DefId is a method in a trait impl for a trait which has track_caller
648/// applied to the method prototype.
649fn should_inherit_track_caller(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
650    tcx.trait_item_of(def_id).is_some_and(|id| {
651        tcx.codegen_fn_attrs(id).flags.intersects(CodegenFnAttrFlags::TRACK_CALLER)
652    })
653}
654
655/// If the provided DefId is a method in a trait impl, return the value of the `#[align]`
656/// attribute on the method prototype (if any).
657fn inherited_align<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> Option<Align> {
658    tcx.codegen_fn_attrs(tcx.trait_item_of(def_id)?).alignment
659}
660
661pub(crate) fn provide(providers: &mut Providers) {
662    *providers = Providers {
663        codegen_fn_attrs,
664        should_inherit_track_caller,
665        inherited_align,
666        sanitizer_settings_for,
667        ..*providers
668    };
669}