Skip to main content

rustc_codegen_ssa/
codegen_attrs.rs

1use rustc_abi::{Align, ExternAbi};
2use rustc_hir::attrs::{
3    AttributeKind, EiiImplResolution, InlineAttr, Linkage, RtsanSetting, UsedBy,
4};
5use rustc_hir::def::DefKind;
6use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId};
7use rustc_hir::{self as hir, Attribute, find_attr};
8use rustc_middle::middle::codegen_fn_attrs::{
9    CodegenFnAttrFlags, CodegenFnAttrs, PatchableFunctionEntry, SanitizerFnAttrs,
10};
11use rustc_middle::mir::mono::Visibility;
12use rustc_middle::query::Providers;
13use rustc_middle::ty::{self as ty, TyCtxt};
14use rustc_session::lint;
15use rustc_session::parse::feature_err;
16use rustc_span::{Span, sym};
17use rustc_target::spec::Os;
18
19use crate::errors;
20use crate::target_features::{
21    check_target_feature_trait_unsafe, check_tied_features, from_target_feature_attr,
22};
23
24/// In some cases, attributes are only valid on functions, but it's the `check_attr`
25/// pass that checks that they aren't used anywhere else, rather than this module.
26/// In these cases, we bail from performing further checks that are only meaningful for
27/// functions (such as calling `fn_sig`, which ICEs if given a non-function). We also
28/// report a delayed bug, just in case `check_attr` isn't doing its job.
29fn try_fn_sig<'tcx>(
30    tcx: TyCtxt<'tcx>,
31    did: LocalDefId,
32    attr_span: Span,
33) -> Option<ty::EarlyBinder<'tcx, ty::PolyFnSig<'tcx>>> {
34    use DefKind::*;
35
36    let def_kind = tcx.def_kind(did);
37    if let Fn | AssocFn | Variant | Ctor(..) = def_kind {
38        Some(tcx.fn_sig(did))
39    } else {
40        tcx.dcx().span_delayed_bug(attr_span, "this attribute can only be applied to functions");
41        None
42    }
43}
44
45/// Spans that are collected when processing built-in attributes,
46/// that are useful for emitting diagnostics later.
47#[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)]
48struct InterestingAttributeDiagnosticSpans {
49    link_ordinal: Option<Span>,
50    sanitize: Option<Span>,
51    inline: Option<Span>,
52    no_mangle: Option<Span>,
53}
54
55/// Process the builtin attrs ([`hir::Attribute`]) on the item.
56/// Many of them directly translate to codegen attrs.
57fn process_builtin_attrs(
58    tcx: TyCtxt<'_>,
59    did: LocalDefId,
60    attrs: &[Attribute],
61    codegen_fn_attrs: &mut CodegenFnAttrs,
62) -> InterestingAttributeDiagnosticSpans {
63    let mut interesting_spans = InterestingAttributeDiagnosticSpans::default();
64    let rust_target_features = tcx.rust_target_features(LOCAL_CRATE);
65
66    let parsed_attrs = attrs
67        .iter()
68        .filter_map(|attr| if let hir::Attribute::Parsed(attr) = attr { Some(attr) } else { None });
69    for attr in parsed_attrs {
70        match attr {
71            AttributeKind::Cold(_) => codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD,
72            AttributeKind::ExportName { name, .. } => codegen_fn_attrs.symbol_name = Some(*name),
73            AttributeKind::Inline(inline, span) => {
74                codegen_fn_attrs.inline = *inline;
75                interesting_spans.inline = Some(*span);
76            }
77            AttributeKind::Naked(_) => codegen_fn_attrs.flags |= CodegenFnAttrFlags::NAKED,
78            AttributeKind::RustcAlign { align, .. } => codegen_fn_attrs.alignment = Some(*align),
79            AttributeKind::LinkName { name, .. } => {
80                // FIXME Remove check for foreign functions once #[link_name] on non-foreign
81                // functions is a hard error
82                if tcx.is_foreign_item(did) {
83                    codegen_fn_attrs.symbol_name = Some(*name);
84                }
85            }
86            AttributeKind::LinkOrdinal { ordinal, span } => {
87                codegen_fn_attrs.link_ordinal = Some(*ordinal);
88                interesting_spans.link_ordinal = Some(*span);
89            }
90            AttributeKind::LinkSection { name, .. } => codegen_fn_attrs.link_section = Some(*name),
91            AttributeKind::NoMangle(attr_span) => {
92                interesting_spans.no_mangle = Some(*attr_span);
93                if tcx.opt_item_name(did.to_def_id()).is_some() {
94                    codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
95                } else {
96                    tcx.dcx()
97                        .span_delayed_bug(*attr_span, "no_mangle should be on a named function");
98                }
99            }
100            AttributeKind::Optimize(optimize, _) => codegen_fn_attrs.optimize = *optimize,
101            AttributeKind::TargetFeature { features, attr_span, was_forced } => {
102                let Some(sig) = tcx.hir_node_by_def_id(did).fn_sig() else {
103                    tcx.dcx().span_delayed_bug(*attr_span, "target_feature applied to non-fn");
104                    continue;
105                };
106                let safe_target_features =
107                    #[allow(non_exhaustive_omitted_patterns)] match sig.header.safety {
    hir::HeaderSafety::SafeTargetFeatures => true,
    _ => false,
}matches!(sig.header.safety, hir::HeaderSafety::SafeTargetFeatures);
108                codegen_fn_attrs.safe_target_features = safe_target_features;
109                if safe_target_features && !was_forced {
110                    if tcx.sess.target.is_like_wasm || tcx.sess.opts.actually_rustdoc {
111                        // The `#[target_feature]` attribute is allowed on
112                        // WebAssembly targets on all functions. Prior to stabilizing
113                        // the `target_feature_11` feature, `#[target_feature]` was
114                        // only permitted on unsafe functions because on most targets
115                        // execution of instructions that are not supported is
116                        // considered undefined behavior. For WebAssembly which is a
117                        // 100% safe target at execution time it's not possible to
118                        // execute undefined instructions, and even if a future
119                        // feature was added in some form for this it would be a
120                        // deterministic trap. There is no undefined behavior when
121                        // executing WebAssembly so `#[target_feature]` is allowed
122                        // on safe functions (but again, only for WebAssembly)
123                        //
124                        // Note that this is also allowed if `actually_rustdoc` so
125                        // if a target is documenting some wasm-specific code then
126                        // it's not spuriously denied.
127                        //
128                        // Now that `#[target_feature]` is permitted on safe functions,
129                        // this exception must still exist for allowing the attribute on
130                        // `main`, `start`, and other functions that are not usually
131                        // allowed.
132                    } else {
133                        check_target_feature_trait_unsafe(tcx, did, *attr_span);
134                    }
135                }
136                from_target_feature_attr(
137                    tcx,
138                    did,
139                    features,
140                    *was_forced,
141                    rust_target_features,
142                    &mut codegen_fn_attrs.target_features,
143                );
144            }
145            AttributeKind::TrackCaller(attr_span) => {
146                let is_closure = tcx.is_closure_like(did.to_def_id());
147
148                if !is_closure
149                    && let Some(fn_sig) = try_fn_sig(tcx, did, *attr_span)
150                    && fn_sig.skip_binder().abi() != ExternAbi::Rust
151                {
152                    tcx.dcx().emit_err(errors::RequiresRustAbi { span: *attr_span });
153                }
154                if is_closure
155                    && !tcx.features().closure_track_caller()
156                    && !attr_span.allows_unstable(sym::closure_track_caller)
157                {
158                    feature_err(
159                        &tcx.sess,
160                        sym::closure_track_caller,
161                        *attr_span,
162                        "`#[track_caller]` on closures is currently unstable",
163                    )
164                    .emit();
165                }
166                codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER
167            }
168            AttributeKind::Used { used_by, .. } => match used_by {
169                UsedBy::Compiler => codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED_COMPILER,
170                UsedBy::Linker => codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED_LINKER,
171                UsedBy::Default => {
172                    let used_form = if tcx.sess.target.os == Os::Illumos {
173                        // illumos' `ld` doesn't support a section header that would represent
174                        // `#[used(linker)]`, see
175                        // https://github.com/rust-lang/rust/issues/146169. For that target,
176                        // downgrade as if `#[used(compiler)]` was requested and hope for the
177                        // best.
178                        CodegenFnAttrFlags::USED_COMPILER
179                    } else {
180                        CodegenFnAttrFlags::USED_LINKER
181                    };
182                    codegen_fn_attrs.flags |= used_form;
183                }
184            },
185            AttributeKind::FfiConst(_) => codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_CONST,
186            AttributeKind::FfiPure(_) => codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_PURE,
187            AttributeKind::RustcStdInternalSymbol(_) => {
188                codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL
189            }
190            AttributeKind::Linkage(linkage, span) => {
191                let linkage = Some(*linkage);
192
193                if tcx.is_foreign_item(did) {
194                    codegen_fn_attrs.import_linkage = linkage;
195
196                    if tcx.is_mutable_static(did.into()) {
197                        let mut diag = tcx.dcx().struct_span_err(
198                            *span,
199                            "extern mutable statics are not allowed with `#[linkage]`",
200                        );
201                        diag.note(
202                            "marking the extern static mutable would allow changing which \
203                            symbol the static references rather than make the target of the \
204                            symbol mutable",
205                        );
206                        diag.emit();
207                    }
208                } else {
209                    codegen_fn_attrs.linkage = linkage;
210                }
211            }
212            AttributeKind::Sanitize { span, .. } => {
213                interesting_spans.sanitize = Some(*span);
214            }
215            AttributeKind::RustcObjcClass { classname, .. } => {
216                codegen_fn_attrs.objc_class = Some(*classname);
217            }
218            AttributeKind::RustcObjcSelector { methname, .. } => {
219                codegen_fn_attrs.objc_selector = Some(*methname);
220            }
221            AttributeKind::RustcEiiForeignItem => {
222                codegen_fn_attrs.flags |= CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM;
223            }
224            AttributeKind::EiiImpls(impls) => {
225                for i in impls {
226                    let foreign_item = match i.resolution {
227                        EiiImplResolution::Macro(def_id) => {
228                            let Some(extern_item) = {

    #[allow(deprecated)]
    {
        {
            'done:
                {
                for i in tcx.get_all_attrs(def_id) {
                    #[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
229                            ) else {
230                                tcx.dcx().span_delayed_bug(
231                                    i.span,
232                                    "resolved to something that's not an EII",
233                                );
234                                continue;
235                            };
236                            extern_item
237                        }
238                        EiiImplResolution::Known(decl) => decl.foreign_item,
239                        EiiImplResolution::Error(_eg) => continue,
240                    };
241
242                    // this is to prevent a bug where a single crate defines both the default and explicit implementation
243                    // for an EII. In that case, both of them may be part of the same final object file. I'm not 100% sure
244                    // what happens, either rustc deduplicates the symbol or llvm, or it's random/order-dependent.
245                    // However, the fact that the default one of has weak linkage isn't considered and you sometimes get that
246                    // the default implementation is used while an explicit implementation is given.
247                    if
248                    // if this is a default impl
249                    i.is_default
250                        // iterate over all implementations *in the current crate*
251                        // (this is ok since we generate codegen fn attrs in the local crate)
252                        // if any of them is *not default* then don't emit the alias.
253                        && tcx.externally_implementable_items(LOCAL_CRATE).get(&foreign_item).expect("at least one").1.iter().any(|(_, imp)| !imp.is_default)
254                    {
255                        continue;
256                    }
257
258                    codegen_fn_attrs.foreign_item_symbol_aliases.push((
259                        foreign_item,
260                        if i.is_default { Linkage::LinkOnceAny } else { Linkage::External },
261                        Visibility::Default,
262                    ));
263                    codegen_fn_attrs.flags |= CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM;
264                }
265            }
266            AttributeKind::ThreadLocal => {
267                codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL
268            }
269            AttributeKind::InstructionSet(instruction_set) => {
270                codegen_fn_attrs.instruction_set = Some(*instruction_set)
271            }
272            AttributeKind::RustcAllocator => {
273                codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR
274            }
275            AttributeKind::RustcDeallocator => {
276                codegen_fn_attrs.flags |= CodegenFnAttrFlags::DEALLOCATOR
277            }
278            AttributeKind::RustcReallocator => {
279                codegen_fn_attrs.flags |= CodegenFnAttrFlags::REALLOCATOR
280            }
281            AttributeKind::RustcAllocatorZeroed => {
282                codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR_ZEROED
283            }
284            AttributeKind::RustcNounwind => {
285                codegen_fn_attrs.flags |= CodegenFnAttrFlags::NEVER_UNWIND
286            }
287            AttributeKind::RustcOffloadKernel => {
288                codegen_fn_attrs.flags |= CodegenFnAttrFlags::OFFLOAD_KERNEL
289            }
290            AttributeKind::PatchableFunctionEntry { prefix, entry } => {
291                codegen_fn_attrs.patchable_function_entry =
292                    Some(PatchableFunctionEntry::from_prefix_and_entry(*prefix, *entry));
293            }
294            _ => {}
295        }
296    }
297
298    interesting_spans
299}
300
301/// Applies overrides for codegen fn attrs. These often have a specific reason why they're necessary.
302/// Please comment why when adding a new one!
303fn apply_overrides(tcx: TyCtxt<'_>, did: LocalDefId, codegen_fn_attrs: &mut CodegenFnAttrs) {
304    // Apply the minimum function alignment here. This ensures that a function's alignment is
305    // determined by the `-C` flags of the crate it is defined in, not the `-C` flags of the crate
306    // it happens to be codegen'd (or const-eval'd) in.
307    codegen_fn_attrs.alignment =
308        Ord::max(codegen_fn_attrs.alignment, tcx.sess.opts.unstable_opts.min_function_alignment);
309
310    // Passed in sanitizer settings are always the default.
311    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());
312    // Replace with #[sanitize] value
313    codegen_fn_attrs.sanitizers = tcx.sanitizer_settings_for(did);
314    // On trait methods, inherit the `#[align]` of the trait's method prototype.
315    codegen_fn_attrs.alignment = Ord::max(codegen_fn_attrs.alignment, tcx.inherited_align(did));
316
317    // naked function MUST NOT be inlined! This attribute is required for the rust compiler itself,
318    // but not for the code generation backend because at that point the naked function will just be
319    // a declaration, with a definition provided in global assembly.
320    if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
321        codegen_fn_attrs.inline = InlineAttr::Never;
322    }
323
324    // #73631: closures inherit `#[target_feature]` annotations
325    //
326    // If this closure is marked `#[inline(always)]`, simply skip adding `#[target_feature]`.
327    //
328    // At this point, `unsafe` has already been checked and `#[target_feature]` only affects codegen.
329    // Due to LLVM limitations, emitting both `#[inline(always)]` and `#[target_feature]` is *unsound*:
330    // the function may be inlined into a caller with fewer target features. Also see
331    // <https://github.com/rust-lang/rust/issues/116573>.
332    //
333    // Using `#[inline(always)]` implies that this closure will most likely be inlined into
334    // its parent function, which effectively inherits the features anyway. Boxing this closure
335    // would result in this closure being compiled without the inherited target features, but this
336    // is probably a poor usage of `#[inline(always)]` and easily avoided by not using the attribute.
337    if tcx.is_closure_like(did.to_def_id()) && codegen_fn_attrs.inline != InlineAttr::Always {
338        let owner_id = tcx.parent(did.to_def_id());
339        if tcx.def_kind(owner_id).has_codegen_attrs() {
340            codegen_fn_attrs
341                .target_features
342                .extend(tcx.codegen_fn_attrs(owner_id).target_features.iter().copied());
343        }
344    }
345
346    // When `no_builtins` is applied at the crate level, we should add the
347    // `no-builtins` attribute to each function to ensure it takes effect in LTO.
348    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);
349    if no_builtins {
350        codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_BUILTINS;
351    }
352
353    // inherit track-caller properly
354    if tcx.should_inherit_track_caller(did) {
355        codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
356    }
357
358    // Foreign items by default use no mangling for their symbol name.
359    if tcx.is_foreign_item(did) {
360        codegen_fn_attrs.flags |= CodegenFnAttrFlags::FOREIGN_ITEM;
361
362        // There's a few exceptions to this rule though:
363        if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) {
364            // * `#[rustc_std_internal_symbol]` mangles the symbol name in a special way
365            //   both for exports and imports through foreign items. This is handled further,
366            //   during symbol mangling logic.
367        } else if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM)
368        {
369            // * externally implementable items keep their mangled symbol name.
370            //   multiple EIIs can have the same name, so not mangling them would be a bug.
371            //   Implementing an EII does the appropriate name resolution to make sure the implementations
372            //   get the same symbol name as the *mangled* foreign item they refer to so that's all good.
373        } else if codegen_fn_attrs.symbol_name.is_some() {
374            // * This can be overridden with the `#[link_name]` attribute
375        } else {
376            // NOTE: there's one more exception that we cannot apply here. On wasm,
377            // some items cannot be `no_mangle`.
378            // However, we don't have enough information here to determine that.
379            // As such, no_mangle foreign items on wasm that have the same defid as some
380            // import will *still* be mangled despite this.
381            //
382            // if none of the exceptions apply; apply no_mangle
383            codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
384        }
385    }
386}
387
388fn check_result(
389    tcx: TyCtxt<'_>,
390    did: LocalDefId,
391    interesting_spans: InterestingAttributeDiagnosticSpans,
392    codegen_fn_attrs: &CodegenFnAttrs,
393) {
394    // If a function uses `#[target_feature]` it can't be inlined into general
395    // purpose functions as they wouldn't have the right target features
396    // enabled. For that reason we also forbid `#[inline(always)]` as it can't be
397    // respected.
398    //
399    // `#[rustc_force_inline]` doesn't need to be prohibited here, only
400    // `#[inline(always)]`, as forced inlining is implemented entirely within
401    // rustc (and so the MIR inliner can do any necessary checks for compatible target
402    // features).
403    //
404    // This sidesteps the LLVM blockers in enabling `target_features` +
405    // `inline(always)` to be used together (see rust-lang/rust#116573 and
406    // llvm/llvm-project#70563).
407    if !codegen_fn_attrs.target_features.is_empty()
408        && #[allow(non_exhaustive_omitted_patterns)] match codegen_fn_attrs.inline {
    InlineAttr::Always => true,
    _ => false,
}matches!(codegen_fn_attrs.inline, InlineAttr::Always)
409        && !tcx.features().target_feature_inline_always()
410        && let Some(span) = interesting_spans.inline
411    {
412        feature_err(
413            tcx.sess,
414            sym::target_feature_inline_always,
415            span,
416            "cannot use `#[inline(always)]` with `#[target_feature]`",
417        )
418        .emit();
419    }
420
421    // warn that inline has no effect when no_sanitize is present
422    if codegen_fn_attrs.sanitizers != SanitizerFnAttrs::default()
423        && codegen_fn_attrs.inline.always()
424        && let (Some(sanitize_span), Some(inline_span)) =
425            (interesting_spans.sanitize, interesting_spans.inline)
426    {
427        let hir_id = tcx.local_def_id_to_hir_id(did);
428        tcx.node_span_lint(lint::builtin::INLINE_NO_SANITIZE, hir_id, sanitize_span, |lint| {
429            lint.primary_message("non-default `sanitize` will have no effect after inlining");
430            lint.span_note(inline_span, "inlining requested here");
431        })
432    }
433
434    // warn for nonblocking async functions, blocks and closures.
435    // This doesn't behave as expected, because the executor can run blocking code without the sanitizer noticing.
436    if codegen_fn_attrs.sanitizers.rtsan_setting == RtsanSetting::Nonblocking
437        && let Some(sanitize_span) = interesting_spans.sanitize
438        // async fn
439        && (tcx.asyncness(did).is_async()
440            // async block
441            || tcx.is_coroutine(did.into())
442            // async closure
443            || (tcx.is_closure_like(did.into())
444                && tcx.hir_node_by_def_id(did).expect_closure().kind
445                    != rustc_hir::ClosureKind::Closure))
446    {
447        let hir_id = tcx.local_def_id_to_hir_id(did);
448        tcx.node_span_lint(
449            lint::builtin::RTSAN_NONBLOCKING_ASYNC,
450            hir_id,
451            sanitize_span,
452            |lint| {
453                lint.primary_message(r#"the async executor can run blocking code, without realtime sanitizer catching it"#);
454            }
455        );
456    }
457
458    // error when specifying link_name together with link_ordinal
459    if let Some(_) = codegen_fn_attrs.symbol_name
460        && let Some(_) = codegen_fn_attrs.link_ordinal
461    {
462        let msg = "cannot use `#[link_name]` with `#[link_ordinal]`";
463        if let Some(span) = interesting_spans.link_ordinal {
464            tcx.dcx().span_err(span, msg);
465        } else {
466            tcx.dcx().err(msg);
467        }
468    }
469
470    if let Some(features) = check_tied_features(
471        tcx.sess,
472        &codegen_fn_attrs
473            .target_features
474            .iter()
475            .map(|features| (features.name.as_str(), true))
476            .collect(),
477    ) {
478        let span = {

    #[allow(deprecated)]
    {
        {
            'done:
                {
                for i in tcx.get_all_attrs(did) {
                    #[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)
479            .unwrap_or_else(|| tcx.def_span(did));
480
481        tcx.dcx()
482            .create_err(errors::TargetFeatureDisableOrEnable {
483                features,
484                span: Some(span),
485                missing_features: Some(errors::MissingFeatures),
486            })
487            .emit();
488    }
489}
490
491fn handle_lang_items(
492    tcx: TyCtxt<'_>,
493    did: LocalDefId,
494    interesting_spans: &InterestingAttributeDiagnosticSpans,
495    attrs: &[Attribute],
496    codegen_fn_attrs: &mut CodegenFnAttrs,
497) {
498    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);
499
500    // Weak lang items have the same semantics as "std internal" symbols in the
501    // sense that they're preserved through all our LTO passes and only
502    // strippable by the linker.
503    //
504    // Additionally weak lang items have predetermined symbol names.
505    if let Some(lang_item) = lang_item
506        && let Some(link_name) = lang_item.link_name()
507    {
508        codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
509        codegen_fn_attrs.symbol_name = Some(link_name);
510    }
511
512    // error when using no_mangle on a lang item item
513    if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL)
514        && codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NO_MANGLE)
515    {
516        let mut err = tcx
517            .dcx()
518            .struct_span_err(
519                interesting_spans.no_mangle.unwrap_or_default(),
520                "`#[no_mangle]` cannot be used on internal language items",
521            )
522            .with_note("Rustc requires this item to have a specific mangled name.")
523            .with_span_label(tcx.def_span(did), "should be the internal language item");
524        if let Some(lang_item) = lang_item
525            && let Some(link_name) = lang_item.link_name()
526        {
527            err = err
528                .with_note("If you are trying to prevent mangling to ease debugging, many")
529                .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"))
530                .with_note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("match `.*{0}.*` instead of `break {0}` on a specific name",
                link_name))
    })format!(
531                    "match `.*{link_name}.*` instead of `break {link_name}` on a specific name"
532                ))
533        }
534        err.emit();
535    }
536}
537
538/// Generate the [`CodegenFnAttrs`] for an item (identified by the [`LocalDefId`]).
539///
540/// This happens in 4 stages:
541/// - apply built-in attributes that directly translate to codegen attributes.
542/// - handle lang items. These have special codegen attrs applied to them.
543/// - apply overrides, like minimum requirements for alignment and other settings that don't rely directly the built-in attrs on the item.
544///   overrides come after applying built-in attributes since they may only apply when certain attributes were already set in the stage before.
545/// - check that the result is valid. There's various ways in which this may not be the case, such as certain combinations of attrs.
546fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
547    if truecfg!(debug_assertions) {
548        let def_kind = tcx.def_kind(did);
549        if !def_kind.has_codegen_attrs() {
    {
        ::core::panicking::panic_fmt(format_args!("unexpected `def_kind` in `codegen_fn_attrs`: {0:?}",
                def_kind));
    }
};assert!(
550            def_kind.has_codegen_attrs(),
551            "unexpected `def_kind` in `codegen_fn_attrs`: {def_kind:?}",
552        );
553    }
554
555    let mut codegen_fn_attrs = CodegenFnAttrs::new();
556    let attrs = tcx.hir_attrs(tcx.local_def_id_to_hir_id(did));
557
558    let interesting_spans = process_builtin_attrs(tcx, did, attrs, &mut codegen_fn_attrs);
559    handle_lang_items(tcx, did, &interesting_spans, attrs, &mut codegen_fn_attrs);
560    apply_overrides(tcx, did, &mut codegen_fn_attrs);
561    check_result(tcx, did, interesting_spans, &codegen_fn_attrs);
562
563    codegen_fn_attrs
564}
565
566fn sanitizer_settings_for(tcx: TyCtxt<'_>, did: LocalDefId) -> SanitizerFnAttrs {
567    // Backtrack to the crate root.
568    let mut settings = match tcx.opt_local_parent(did) {
569        // Check the parent (recursively).
570        Some(parent) => tcx.sanitizer_settings_for(parent),
571        // We reached the crate root without seeing an attribute, so
572        // there is no sanitizers to exclude.
573        None => SanitizerFnAttrs::default(),
574    };
575
576    // Check for a sanitize annotation directly on this def.
577    if let Some((on_set, off_set, rtsan)) =
578        {

    #[allow(deprecated)]
    {
        {
            'done:
                {
                for i in tcx.get_all_attrs(did) {
                    #[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))
579    {
580        // the on set is the set of sanitizers explicitly enabled.
581        // we mask those out since we want the set of disabled sanitizers here
582        settings.disabled &= !*on_set;
583        // the off set is the set of sanitizers explicitly disabled.
584        // we or those in here.
585        settings.disabled |= *off_set;
586        // the on set and off set are distjoint since there's a third option: unset.
587        // a node may not set the sanitizer setting in which case it inherits from parents.
588        // the code above in this function does this backtracking
589
590        // if rtsan was specified here override the parent
591        if let Some(rtsan) = rtsan {
592            settings.rtsan_setting = *rtsan;
593        }
594    }
595    settings
596}
597
598/// Checks if the provided DefId is a method in a trait impl for a trait which has track_caller
599/// applied to the method prototype.
600fn should_inherit_track_caller(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
601    tcx.trait_item_of(def_id).is_some_and(|id| {
602        tcx.codegen_fn_attrs(id).flags.intersects(CodegenFnAttrFlags::TRACK_CALLER)
603    })
604}
605
606/// If the provided DefId is a method in a trait impl, return the value of the `#[align]`
607/// attribute on the method prototype (if any).
608fn inherited_align<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> Option<Align> {
609    tcx.codegen_fn_attrs(tcx.trait_item_of(def_id)?).alignment
610}
611
612pub(crate) fn provide(providers: &mut Providers) {
613    *providers = Providers {
614        codegen_fn_attrs,
615        should_inherit_track_caller,
616        inherited_align,
617        sanitizer_settings_for,
618        ..*providers
619    };
620}