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