rustc_codegen_ssa/
codegen_attrs.rs

1use std::str::FromStr;
2
3use rustc_abi::{Align, ExternAbi};
4use rustc_ast::expand::autodiff_attrs::{AutoDiffAttrs, DiffActivity, DiffMode};
5use rustc_ast::{LitKind, MetaItem, MetaItemInner, attr};
6use rustc_hir::attrs::{
7    AttributeKind, InlineAttr, InstructionSetAttr, Linkage, RtsanSetting, UsedBy,
8};
9use rustc_hir::def::DefKind;
10use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId};
11use rustc_hir::{self as hir, Attribute, LangItem, find_attr, lang_items};
12use rustc_middle::middle::codegen_fn_attrs::{
13    CodegenFnAttrFlags, CodegenFnAttrs, PatchableFunctionEntry, SanitizerFnAttrs,
14};
15use rustc_middle::mir::mono::Visibility;
16use rustc_middle::query::Providers;
17use rustc_middle::span_bug;
18use rustc_middle::ty::{self as ty, Instance, TyCtxt};
19use rustc_session::lint;
20use rustc_session::parse::feature_err;
21use rustc_span::{Ident, Span, Symbol, sym};
22use rustc_target::spec::Os;
23
24use crate::errors;
25use crate::target_features::{
26    check_target_feature_trait_unsafe, check_tied_features, from_target_feature_attr,
27};
28
29/// In some cases, attributes are only valid on functions, but it's the `check_attr`
30/// pass that checks that they aren't used anywhere else, rather than this module.
31/// In these cases, we bail from performing further checks that are only meaningful for
32/// functions (such as calling `fn_sig`, which ICEs if given a non-function). We also
33/// report a delayed bug, just in case `check_attr` isn't doing its job.
34fn try_fn_sig<'tcx>(
35    tcx: TyCtxt<'tcx>,
36    did: LocalDefId,
37    attr_span: Span,
38) -> Option<ty::EarlyBinder<'tcx, ty::PolyFnSig<'tcx>>> {
39    use DefKind::*;
40
41    let def_kind = tcx.def_kind(did);
42    if let Fn | AssocFn | Variant | Ctor(..) = def_kind {
43        Some(tcx.fn_sig(did))
44    } else {
45        tcx.dcx().span_delayed_bug(attr_span, "this attribute can only be applied to functions");
46        None
47    }
48}
49
50// FIXME(jdonszelmann): remove when instruction_set becomes a parsed attr
51fn parse_instruction_set_attr(tcx: TyCtxt<'_>, attr: &Attribute) -> Option<InstructionSetAttr> {
52    let list = attr.meta_item_list()?;
53
54    match &list[..] {
55        [MetaItemInner::MetaItem(set)] => {
56            let segments = set.path.segments.iter().map(|x| x.ident.name).collect::<Vec<_>>();
57            match segments.as_slice() {
58                [sym::arm, sym::a32 | sym::t32] if !tcx.sess.target.has_thumb_interworking => {
59                    tcx.dcx().emit_err(errors::UnsupportedInstructionSet { span: attr.span() });
60                    None
61                }
62                [sym::arm, sym::a32] => Some(InstructionSetAttr::ArmA32),
63                [sym::arm, sym::t32] => Some(InstructionSetAttr::ArmT32),
64                _ => {
65                    tcx.dcx().emit_err(errors::InvalidInstructionSet { span: attr.span() });
66                    None
67                }
68            }
69        }
70        [] => {
71            tcx.dcx().emit_err(errors::BareInstructionSet { span: attr.span() });
72            None
73        }
74        _ => {
75            tcx.dcx().emit_err(errors::MultipleInstructionSet { span: attr.span() });
76            None
77        }
78    }
79}
80
81// FIXME(jdonszelmann): remove when patchable_function_entry becomes a parsed attr
82fn parse_patchable_function_entry(
83    tcx: TyCtxt<'_>,
84    attr: &Attribute,
85) -> Option<PatchableFunctionEntry> {
86    attr.meta_item_list().and_then(|l| {
87        let mut prefix = None;
88        let mut entry = None;
89        for item in l {
90            let Some(meta_item) = item.meta_item() else {
91                tcx.dcx().emit_err(errors::ExpectedNameValuePair { span: item.span() });
92                continue;
93            };
94
95            let Some(name_value_lit) = meta_item.name_value_literal() else {
96                tcx.dcx().emit_err(errors::ExpectedNameValuePair { span: item.span() });
97                continue;
98            };
99
100            let attrib_to_write = match meta_item.name() {
101                Some(sym::prefix_nops) => &mut prefix,
102                Some(sym::entry_nops) => &mut entry,
103                _ => {
104                    tcx.dcx().emit_err(errors::UnexpectedParameterName {
105                        span: item.span(),
106                        prefix_nops: sym::prefix_nops,
107                        entry_nops: sym::entry_nops,
108                    });
109                    continue;
110                }
111            };
112
113            let rustc_ast::LitKind::Int(val, _) = name_value_lit.kind else {
114                tcx.dcx().emit_err(errors::InvalidLiteralValue { span: name_value_lit.span });
115                continue;
116            };
117
118            let Ok(val) = val.get().try_into() else {
119                tcx.dcx().emit_err(errors::OutOfRangeInteger { span: name_value_lit.span });
120                continue;
121            };
122
123            *attrib_to_write = Some(val);
124        }
125
126        if let (None, None) = (prefix, entry) {
127            tcx.dcx().span_err(attr.span(), "must specify at least one parameter");
128        }
129
130        Some(PatchableFunctionEntry::from_prefix_and_entry(prefix.unwrap_or(0), entry.unwrap_or(0)))
131    })
132}
133
134/// Spans that are collected when processing built-in attributes,
135/// that are useful for emitting diagnostics later.
136#[derive(Default)]
137struct InterestingAttributeDiagnosticSpans {
138    link_ordinal: Option<Span>,
139    sanitize: Option<Span>,
140    inline: Option<Span>,
141    no_mangle: Option<Span>,
142}
143
144/// Process the builtin attrs ([`hir::Attribute`]) on the item.
145/// Many of them directly translate to codegen attrs.
146fn process_builtin_attrs(
147    tcx: TyCtxt<'_>,
148    did: LocalDefId,
149    attrs: &[Attribute],
150    codegen_fn_attrs: &mut CodegenFnAttrs,
151) -> InterestingAttributeDiagnosticSpans {
152    let mut interesting_spans = InterestingAttributeDiagnosticSpans::default();
153    let rust_target_features = tcx.rust_target_features(LOCAL_CRATE);
154
155    for attr in attrs.iter() {
156        if let hir::Attribute::Parsed(p) = attr {
157            match p {
158                AttributeKind::Cold(_) => codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD,
159                AttributeKind::ExportName { name, .. } => {
160                    codegen_fn_attrs.symbol_name = Some(*name)
161                }
162                AttributeKind::Inline(inline, span) => {
163                    codegen_fn_attrs.inline = *inline;
164                    interesting_spans.inline = Some(*span);
165                }
166                AttributeKind::Naked(_) => codegen_fn_attrs.flags |= CodegenFnAttrFlags::NAKED,
167                AttributeKind::Align { align, .. } => codegen_fn_attrs.alignment = Some(*align),
168                AttributeKind::LinkName { name, .. } => {
169                    // FIXME Remove check for foreign functions once #[link_name] on non-foreign
170                    // functions is a hard error
171                    if tcx.is_foreign_item(did) {
172                        codegen_fn_attrs.symbol_name = Some(*name);
173                    }
174                }
175                AttributeKind::LinkOrdinal { ordinal, span } => {
176                    codegen_fn_attrs.link_ordinal = Some(*ordinal);
177                    interesting_spans.link_ordinal = Some(*span);
178                }
179                AttributeKind::LinkSection { name, .. } => {
180                    codegen_fn_attrs.link_section = Some(*name)
181                }
182                AttributeKind::NoMangle(attr_span) => {
183                    interesting_spans.no_mangle = Some(*attr_span);
184                    if tcx.opt_item_name(did.to_def_id()).is_some() {
185                        codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
186                    } else {
187                        tcx.dcx().span_delayed_bug(
188                            *attr_span,
189                            "no_mangle should be on a named function",
190                        );
191                    }
192                }
193                AttributeKind::Optimize(optimize, _) => codegen_fn_attrs.optimize = *optimize,
194                AttributeKind::TargetFeature { features, attr_span, was_forced } => {
195                    let Some(sig) = tcx.hir_node_by_def_id(did).fn_sig() else {
196                        tcx.dcx().span_delayed_bug(*attr_span, "target_feature applied to non-fn");
197                        continue;
198                    };
199                    let safe_target_features =
200                        matches!(sig.header.safety, hir::HeaderSafety::SafeTargetFeatures);
201                    codegen_fn_attrs.safe_target_features = safe_target_features;
202                    if safe_target_features && !was_forced {
203                        if tcx.sess.target.is_like_wasm || tcx.sess.opts.actually_rustdoc {
204                            // The `#[target_feature]` attribute is allowed on
205                            // WebAssembly targets on all functions. Prior to stabilizing
206                            // the `target_feature_11` feature, `#[target_feature]` was
207                            // only permitted on unsafe functions because on most targets
208                            // execution of instructions that are not supported is
209                            // considered undefined behavior. For WebAssembly which is a
210                            // 100% safe target at execution time it's not possible to
211                            // execute undefined instructions, and even if a future
212                            // feature was added in some form for this it would be a
213                            // deterministic trap. There is no undefined behavior when
214                            // executing WebAssembly so `#[target_feature]` is allowed
215                            // on safe functions (but again, only for WebAssembly)
216                            //
217                            // Note that this is also allowed if `actually_rustdoc` so
218                            // if a target is documenting some wasm-specific code then
219                            // it's not spuriously denied.
220                            //
221                            // Now that `#[target_feature]` is permitted on safe functions,
222                            // this exception must still exist for allowing the attribute on
223                            // `main`, `start`, and other functions that are not usually
224                            // allowed.
225                        } else {
226                            check_target_feature_trait_unsafe(tcx, did, *attr_span);
227                        }
228                    }
229                    from_target_feature_attr(
230                        tcx,
231                        did,
232                        features,
233                        *was_forced,
234                        rust_target_features,
235                        &mut codegen_fn_attrs.target_features,
236                    );
237                }
238                AttributeKind::TrackCaller(attr_span) => {
239                    let is_closure = tcx.is_closure_like(did.to_def_id());
240
241                    if !is_closure
242                        && let Some(fn_sig) = try_fn_sig(tcx, did, *attr_span)
243                        && fn_sig.skip_binder().abi() != ExternAbi::Rust
244                    {
245                        tcx.dcx().emit_err(errors::RequiresRustAbi { span: *attr_span });
246                    }
247                    if is_closure
248                        && !tcx.features().closure_track_caller()
249                        && !attr_span.allows_unstable(sym::closure_track_caller)
250                    {
251                        feature_err(
252                            &tcx.sess,
253                            sym::closure_track_caller,
254                            *attr_span,
255                            "`#[track_caller]` on closures is currently unstable",
256                        )
257                        .emit();
258                    }
259                    codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER
260                }
261                AttributeKind::Used { used_by, .. } => match used_by {
262                    UsedBy::Compiler => codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED_COMPILER,
263                    UsedBy::Linker => codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED_LINKER,
264                    UsedBy::Default => {
265                        let used_form = if tcx.sess.target.os == Os::Illumos {
266                            // illumos' `ld` doesn't support a section header that would represent
267                            // `#[used(linker)]`, see
268                            // https://github.com/rust-lang/rust/issues/146169. For that target,
269                            // downgrade as if `#[used(compiler)]` was requested and hope for the
270                            // best.
271                            CodegenFnAttrFlags::USED_COMPILER
272                        } else {
273                            CodegenFnAttrFlags::USED_LINKER
274                        };
275                        codegen_fn_attrs.flags |= used_form;
276                    }
277                },
278                AttributeKind::FfiConst(_) => {
279                    codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_CONST
280                }
281                AttributeKind::FfiPure(_) => codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_PURE,
282                AttributeKind::StdInternalSymbol(_) => {
283                    codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL
284                }
285                AttributeKind::Linkage(linkage, span) => {
286                    let linkage = Some(*linkage);
287
288                    if tcx.is_foreign_item(did) {
289                        codegen_fn_attrs.import_linkage = linkage;
290
291                        if tcx.is_mutable_static(did.into()) {
292                            let mut diag = tcx.dcx().struct_span_err(
293                                *span,
294                                "extern mutable statics are not allowed with `#[linkage]`",
295                            );
296                            diag.note(
297                                "marking the extern static mutable would allow changing which \
298                                symbol the static references rather than make the target of the \
299                                symbol mutable",
300                            );
301                            diag.emit();
302                        }
303                    } else {
304                        codegen_fn_attrs.linkage = linkage;
305                    }
306                }
307                AttributeKind::Sanitize { span, .. } => {
308                    interesting_spans.sanitize = Some(*span);
309                }
310                AttributeKind::ObjcClass { classname, .. } => {
311                    codegen_fn_attrs.objc_class = Some(*classname);
312                }
313                AttributeKind::ObjcSelector { methname, .. } => {
314                    codegen_fn_attrs.objc_selector = Some(*methname);
315                }
316                AttributeKind::EiiExternItem => {
317                    codegen_fn_attrs.flags |= CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM;
318                }
319                AttributeKind::EiiImpls(impls) => {
320                    for i in impls {
321                        let extern_item = find_attr!(
322                            tcx.get_all_attrs(i.eii_macro),
323                            AttributeKind::EiiExternTarget(target) => target.eii_extern_target
324                        )
325                        .expect("eii should have declaration macro with extern target attribute");
326
327                        let symbol_name = tcx.symbol_name(Instance::mono(tcx, extern_item));
328
329                        // this is to prevent a bug where a single crate defines both the default and explicit implementation
330                        // for an EII. In that case, both of them may be part of the same final object file. I'm not 100% sure
331                        // what happens, either rustc deduplicates the symbol or llvm, or it's random/order-dependent.
332                        // However, the fact that the default one of has weak linkage isn't considered and you sometimes get that
333                        // the default implementation is used while an explicit implementation is given.
334                        if
335                        // if this is a default impl
336                        i.is_default
337                            // iterate over all implementations *in the current crate*
338                            // (this is ok since we generate codegen fn attrs in the local crate)
339                            // if any of them is *not default* then don't emit the alias.
340                            && tcx.externally_implementable_items(LOCAL_CRATE).get(&i.eii_macro).expect("at least one").1.iter().any(|(_, imp)| !imp.is_default)
341                        {
342                            continue;
343                        }
344
345                        codegen_fn_attrs.foreign_item_symbol_aliases.push((
346                            Symbol::intern(symbol_name.name),
347                            if i.is_default { Linkage::LinkOnceAny } else { Linkage::External },
348                            Visibility::Default,
349                        ));
350                        codegen_fn_attrs.flags |= CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM;
351                    }
352                }
353                _ => {}
354            }
355        }
356
357        let Some(Ident { name, .. }) = attr.ident() else {
358            continue;
359        };
360
361        match name {
362            sym::rustc_allocator => codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR,
363            sym::rustc_nounwind => codegen_fn_attrs.flags |= CodegenFnAttrFlags::NEVER_UNWIND,
364            sym::rustc_reallocator => codegen_fn_attrs.flags |= CodegenFnAttrFlags::REALLOCATOR,
365            sym::rustc_deallocator => codegen_fn_attrs.flags |= CodegenFnAttrFlags::DEALLOCATOR,
366            sym::rustc_allocator_zeroed => {
367                codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR_ZEROED
368            }
369            sym::thread_local => codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL,
370            sym::instruction_set => {
371                codegen_fn_attrs.instruction_set = parse_instruction_set_attr(tcx, attr)
372            }
373            sym::patchable_function_entry => {
374                codegen_fn_attrs.patchable_function_entry =
375                    parse_patchable_function_entry(tcx, attr);
376            }
377            sym::rustc_offload_kernel => {
378                codegen_fn_attrs.flags |= CodegenFnAttrFlags::OFFLOAD_KERNEL
379            }
380            _ => {}
381        }
382    }
383
384    interesting_spans
385}
386
387/// Applies overrides for codegen fn attrs. These often have a specific reason why they're necessary.
388/// Please comment why when adding a new one!
389fn apply_overrides(tcx: TyCtxt<'_>, did: LocalDefId, codegen_fn_attrs: &mut CodegenFnAttrs) {
390    // Apply the minimum function alignment here. This ensures that a function's alignment is
391    // determined by the `-C` flags of the crate it is defined in, not the `-C` flags of the crate
392    // it happens to be codegen'd (or const-eval'd) in.
393    codegen_fn_attrs.alignment =
394        Ord::max(codegen_fn_attrs.alignment, tcx.sess.opts.unstable_opts.min_function_alignment);
395
396    // Passed in sanitizer settings are always the default.
397    assert!(codegen_fn_attrs.sanitizers == SanitizerFnAttrs::default());
398    // Replace with #[sanitize] value
399    codegen_fn_attrs.sanitizers = tcx.sanitizer_settings_for(did);
400    // On trait methods, inherit the `#[align]` of the trait's method prototype.
401    codegen_fn_attrs.alignment = Ord::max(codegen_fn_attrs.alignment, tcx.inherited_align(did));
402
403    // naked function MUST NOT be inlined! This attribute is required for the rust compiler itself,
404    // but not for the code generation backend because at that point the naked function will just be
405    // a declaration, with a definition provided in global assembly.
406    if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
407        codegen_fn_attrs.inline = InlineAttr::Never;
408    }
409
410    // #73631: closures inherit `#[target_feature]` annotations
411    //
412    // If this closure is marked `#[inline(always)]`, simply skip adding `#[target_feature]`.
413    //
414    // At this point, `unsafe` has already been checked and `#[target_feature]` only affects codegen.
415    // Due to LLVM limitations, emitting both `#[inline(always)]` and `#[target_feature]` is *unsound*:
416    // the function may be inlined into a caller with fewer target features. Also see
417    // <https://github.com/rust-lang/rust/issues/116573>.
418    //
419    // Using `#[inline(always)]` implies that this closure will most likely be inlined into
420    // its parent function, which effectively inherits the features anyway. Boxing this closure
421    // would result in this closure being compiled without the inherited target features, but this
422    // is probably a poor usage of `#[inline(always)]` and easily avoided by not using the attribute.
423    if tcx.is_closure_like(did.to_def_id()) && codegen_fn_attrs.inline != InlineAttr::Always {
424        let owner_id = tcx.parent(did.to_def_id());
425        if tcx.def_kind(owner_id).has_codegen_attrs() {
426            codegen_fn_attrs
427                .target_features
428                .extend(tcx.codegen_fn_attrs(owner_id).target_features.iter().copied());
429        }
430    }
431
432    // When `no_builtins` is applied at the crate level, we should add the
433    // `no-builtins` attribute to each function to ensure it takes effect in LTO.
434    let crate_attrs = tcx.hir_attrs(rustc_hir::CRATE_HIR_ID);
435    let no_builtins = attr::contains_name(crate_attrs, sym::no_builtins);
436    if no_builtins {
437        codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_BUILTINS;
438    }
439
440    // inherit track-caller properly
441    if tcx.should_inherit_track_caller(did) {
442        codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
443    }
444
445    // Foreign items by default use no mangling for their symbol name.
446    if tcx.is_foreign_item(did) {
447        codegen_fn_attrs.flags |= CodegenFnAttrFlags::FOREIGN_ITEM;
448
449        // There's a few exceptions to this rule though:
450        if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) {
451            // * `#[rustc_std_internal_symbol]` mangles the symbol name in a special way
452            //   both for exports and imports through foreign items. This is handled further,
453            //   during symbol mangling logic.
454        } else if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM)
455        {
456            // * externally implementable items keep their mangled symbol name.
457            //   multiple EIIs can have the same name, so not mangling them would be a bug.
458            //   Implementing an EII does the appropriate name resolution to make sure the implementations
459            //   get the same symbol name as the *mangled* foreign item they refer to so that's all good.
460        } else if codegen_fn_attrs.symbol_name.is_some() {
461            // * This can be overridden with the `#[link_name]` attribute
462        } else {
463            // NOTE: there's one more exception that we cannot apply here. On wasm,
464            // some items cannot be `no_mangle`.
465            // However, we don't have enough information here to determine that.
466            // As such, no_mangle foreign items on wasm that have the same defid as some
467            // import will *still* be mangled despite this.
468            //
469            // if none of the exceptions apply; apply no_mangle
470            codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
471        }
472    }
473}
474
475fn check_result(
476    tcx: TyCtxt<'_>,
477    did: LocalDefId,
478    interesting_spans: InterestingAttributeDiagnosticSpans,
479    codegen_fn_attrs: &CodegenFnAttrs,
480) {
481    // If a function uses `#[target_feature]` it can't be inlined into general
482    // purpose functions as they wouldn't have the right target features
483    // enabled. For that reason we also forbid `#[inline(always)]` as it can't be
484    // respected.
485    //
486    // `#[rustc_force_inline]` doesn't need to be prohibited here, only
487    // `#[inline(always)]`, as forced inlining is implemented entirely within
488    // rustc (and so the MIR inliner can do any necessary checks for compatible target
489    // features).
490    //
491    // This sidesteps the LLVM blockers in enabling `target_features` +
492    // `inline(always)` to be used together (see rust-lang/rust#116573 and
493    // llvm/llvm-project#70563).
494    if !codegen_fn_attrs.target_features.is_empty()
495        && matches!(codegen_fn_attrs.inline, InlineAttr::Always)
496        && !tcx.features().target_feature_inline_always()
497        && let Some(span) = interesting_spans.inline
498    {
499        feature_err(
500            tcx.sess,
501            sym::target_feature_inline_always,
502            span,
503            "cannot use `#[inline(always)]` with `#[target_feature]`",
504        )
505        .emit();
506    }
507
508    // warn that inline has no effect when no_sanitize is present
509    if codegen_fn_attrs.sanitizers != SanitizerFnAttrs::default()
510        && codegen_fn_attrs.inline.always()
511        && let (Some(sanitize_span), Some(inline_span)) =
512            (interesting_spans.sanitize, interesting_spans.inline)
513    {
514        let hir_id = tcx.local_def_id_to_hir_id(did);
515        tcx.node_span_lint(lint::builtin::INLINE_NO_SANITIZE, hir_id, sanitize_span, |lint| {
516            lint.primary_message("non-default `sanitize` will have no effect after inlining");
517            lint.span_note(inline_span, "inlining requested here");
518        })
519    }
520
521    // warn for nonblocking async functions, blocks and closures.
522    // This doesn't behave as expected, because the executor can run blocking code without the sanitizer noticing.
523    if codegen_fn_attrs.sanitizers.rtsan_setting == RtsanSetting::Nonblocking
524        && let Some(sanitize_span) = interesting_spans.sanitize
525        // async fn
526        && (tcx.asyncness(did).is_async()
527            // async block
528            || tcx.is_coroutine(did.into())
529            // async closure
530            || (tcx.is_closure_like(did.into())
531                && tcx.hir_node_by_def_id(did).expect_closure().kind
532                    != rustc_hir::ClosureKind::Closure))
533    {
534        let hir_id = tcx.local_def_id_to_hir_id(did);
535        tcx.node_span_lint(
536            lint::builtin::RTSAN_NONBLOCKING_ASYNC,
537            hir_id,
538            sanitize_span,
539            |lint| {
540                lint.primary_message(r#"the async executor can run blocking code, without realtime sanitizer catching it"#);
541            }
542        );
543    }
544
545    // error when specifying link_name together with link_ordinal
546    if let Some(_) = codegen_fn_attrs.symbol_name
547        && let Some(_) = codegen_fn_attrs.link_ordinal
548    {
549        let msg = "cannot use `#[link_name]` with `#[link_ordinal]`";
550        if let Some(span) = interesting_spans.link_ordinal {
551            tcx.dcx().span_err(span, msg);
552        } else {
553            tcx.dcx().err(msg);
554        }
555    }
556
557    if let Some(features) = check_tied_features(
558        tcx.sess,
559        &codegen_fn_attrs
560            .target_features
561            .iter()
562            .map(|features| (features.name.as_str(), true))
563            .collect(),
564    ) {
565        let span =
566            find_attr!(tcx.get_all_attrs(did), AttributeKind::TargetFeature{attr_span: span, ..} => *span)
567                .unwrap_or_else(|| tcx.def_span(did));
568
569        tcx.dcx()
570            .create_err(errors::TargetFeatureDisableOrEnable {
571                features,
572                span: Some(span),
573                missing_features: Some(errors::MissingFeatures),
574            })
575            .emit();
576    }
577}
578
579fn handle_lang_items(
580    tcx: TyCtxt<'_>,
581    did: LocalDefId,
582    interesting_spans: &InterestingAttributeDiagnosticSpans,
583    attrs: &[Attribute],
584    codegen_fn_attrs: &mut CodegenFnAttrs,
585) {
586    let lang_item = lang_items::extract(attrs).and_then(|(name, _)| LangItem::from_name(name));
587
588    // Weak lang items have the same semantics as "std internal" symbols in the
589    // sense that they're preserved through all our LTO passes and only
590    // strippable by the linker.
591    //
592    // Additionally weak lang items have predetermined symbol names.
593    if let Some(lang_item) = lang_item
594        && let Some(link_name) = lang_item.link_name()
595    {
596        codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
597        codegen_fn_attrs.symbol_name = Some(link_name);
598    }
599
600    // error when using no_mangle on a lang item item
601    if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL)
602        && codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NO_MANGLE)
603    {
604        let mut err = tcx
605            .dcx()
606            .struct_span_err(
607                interesting_spans.no_mangle.unwrap_or_default(),
608                "`#[no_mangle]` cannot be used on internal language items",
609            )
610            .with_note("Rustc requires this item to have a specific mangled name.")
611            .with_span_label(tcx.def_span(did), "should be the internal language item");
612        if let Some(lang_item) = lang_item
613            && let Some(link_name) = lang_item.link_name()
614        {
615            err = err
616                .with_note("If you are trying to prevent mangling to ease debugging, many")
617                .with_note(format!("debuggers support a command such as `rbreak {link_name}` to"))
618                .with_note(format!(
619                    "match `.*{link_name}.*` instead of `break {link_name}` on a specific name"
620                ))
621        }
622        err.emit();
623    }
624}
625
626/// Generate the [`CodegenFnAttrs`] for an item (identified by the [`LocalDefId`]).
627///
628/// This happens in 4 stages:
629/// - apply built-in attributes that directly translate to codegen attributes.
630/// - handle lang items. These have special codegen attrs applied to them.
631/// - apply overrides, like minimum requirements for alignment and other settings that don't rely directly the built-in attrs on the item.
632///   overrides come after applying built-in attributes since they may only apply when certain attributes were already set in the stage before.
633/// - check that the result is valid. There's various ways in which this may not be the case, such as certain combinations of attrs.
634fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
635    if cfg!(debug_assertions) {
636        let def_kind = tcx.def_kind(did);
637        assert!(
638            def_kind.has_codegen_attrs(),
639            "unexpected `def_kind` in `codegen_fn_attrs`: {def_kind:?}",
640        );
641    }
642
643    let mut codegen_fn_attrs = CodegenFnAttrs::new();
644    let attrs = tcx.hir_attrs(tcx.local_def_id_to_hir_id(did));
645
646    let interesting_spans = process_builtin_attrs(tcx, did, attrs, &mut codegen_fn_attrs);
647    handle_lang_items(tcx, did, &interesting_spans, attrs, &mut codegen_fn_attrs);
648    apply_overrides(tcx, did, &mut codegen_fn_attrs);
649    check_result(tcx, did, interesting_spans, &codegen_fn_attrs);
650
651    codegen_fn_attrs
652}
653
654fn sanitizer_settings_for(tcx: TyCtxt<'_>, did: LocalDefId) -> SanitizerFnAttrs {
655    // Backtrack to the crate root.
656    let mut settings = match tcx.opt_local_parent(did) {
657        // Check the parent (recursively).
658        Some(parent) => tcx.sanitizer_settings_for(parent),
659        // We reached the crate root without seeing an attribute, so
660        // there is no sanitizers to exclude.
661        None => SanitizerFnAttrs::default(),
662    };
663
664    // Check for a sanitize annotation directly on this def.
665    if let Some((on_set, off_set, rtsan)) = find_attr!(tcx.get_all_attrs(did), AttributeKind::Sanitize {on_set, off_set, rtsan, ..} => (on_set, off_set, rtsan))
666    {
667        // the on set is the set of sanitizers explicitly enabled.
668        // we mask those out since we want the set of disabled sanitizers here
669        settings.disabled &= !*on_set;
670        // the off set is the set of sanitizers explicitly disabled.
671        // we or those in here.
672        settings.disabled |= *off_set;
673        // the on set and off set are distjoint since there's a third option: unset.
674        // a node may not set the sanitizer setting in which case it inherits from parents.
675        // the code above in this function does this backtracking
676
677        // if rtsan was specified here override the parent
678        if let Some(rtsan) = rtsan {
679            settings.rtsan_setting = *rtsan;
680        }
681    }
682    settings
683}
684
685/// Checks if the provided DefId is a method in a trait impl for a trait which has track_caller
686/// applied to the method prototype.
687fn should_inherit_track_caller(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
688    tcx.trait_item_of(def_id).is_some_and(|id| {
689        tcx.codegen_fn_attrs(id).flags.intersects(CodegenFnAttrFlags::TRACK_CALLER)
690    })
691}
692
693/// If the provided DefId is a method in a trait impl, return the value of the `#[align]`
694/// attribute on the method prototype (if any).
695fn inherited_align<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> Option<Align> {
696    tcx.codegen_fn_attrs(tcx.trait_item_of(def_id)?).alignment
697}
698
699/// We now check the #\[rustc_autodiff\] attributes which we generated from the #[autodiff(...)]
700/// macros. There are two forms. The pure one without args to mark primal functions (the functions
701/// being differentiated). The other form is #[rustc_autodiff(Mode, ActivityList)] on top of the
702/// placeholder functions. We wrote the rustc_autodiff attributes ourself, so this should never
703/// panic, unless we introduced a bug when parsing the autodiff macro.
704//FIXME(jdonszelmann): put in the main loop. No need to have two..... :/ Let's do that when we make autodiff parsed.
705pub fn autodiff_attrs(tcx: TyCtxt<'_>, id: DefId) -> Option<AutoDiffAttrs> {
706    let attrs = tcx.get_attrs(id, sym::rustc_autodiff);
707
708    let attrs = attrs.filter(|attr| attr.has_name(sym::rustc_autodiff)).collect::<Vec<_>>();
709
710    // check for exactly one autodiff attribute on placeholder functions.
711    // There should only be one, since we generate a new placeholder per ad macro.
712    let attr = match &attrs[..] {
713        [] => return None,
714        [attr] => attr,
715        _ => {
716            span_bug!(attrs[1].span(), "cg_ssa: rustc_autodiff should only exist once per source");
717        }
718    };
719
720    let list = attr.meta_item_list().unwrap_or_default();
721
722    // empty autodiff attribute macros (i.e. `#[autodiff]`) are used to mark source functions
723    if list.is_empty() {
724        return Some(AutoDiffAttrs::source());
725    }
726
727    let [mode, width_meta, input_activities @ .., ret_activity] = &list[..] else {
728        span_bug!(attr.span(), "rustc_autodiff attribute must contain mode, width and activities");
729    };
730    let mode = if let MetaItemInner::MetaItem(MetaItem { path: p1, .. }) = mode {
731        p1.segments.first().unwrap().ident
732    } else {
733        span_bug!(attr.span(), "rustc_autodiff attribute must contain mode");
734    };
735
736    // parse mode
737    let mode = match mode.as_str() {
738        "Forward" => DiffMode::Forward,
739        "Reverse" => DiffMode::Reverse,
740        _ => {
741            span_bug!(mode.span, "rustc_autodiff attribute contains invalid mode");
742        }
743    };
744
745    let width: u32 = match width_meta {
746        MetaItemInner::MetaItem(MetaItem { path: p1, .. }) => {
747            let w = p1.segments.first().unwrap().ident;
748            match w.as_str().parse() {
749                Ok(val) => val,
750                Err(_) => {
751                    span_bug!(w.span, "rustc_autodiff width should fit u32");
752                }
753            }
754        }
755        MetaItemInner::Lit(lit) => {
756            if let LitKind::Int(val, _) = lit.kind {
757                match val.get().try_into() {
758                    Ok(val) => val,
759                    Err(_) => {
760                        span_bug!(lit.span, "rustc_autodiff width should fit u32");
761                    }
762                }
763            } else {
764                span_bug!(lit.span, "rustc_autodiff width should be an integer");
765            }
766        }
767    };
768
769    // First read the ret symbol from the attribute
770    let MetaItemInner::MetaItem(MetaItem { path: p1, .. }) = ret_activity else {
771        span_bug!(attr.span(), "rustc_autodiff attribute must contain the return activity");
772    };
773    let ret_symbol = p1.segments.first().unwrap().ident;
774
775    // Then parse it into an actual DiffActivity
776    let Ok(ret_activity) = DiffActivity::from_str(ret_symbol.as_str()) else {
777        span_bug!(ret_symbol.span, "invalid return activity");
778    };
779
780    // Now parse all the intermediate (input) activities
781    let mut arg_activities: Vec<DiffActivity> = vec![];
782    for arg in input_activities {
783        let arg_symbol = if let MetaItemInner::MetaItem(MetaItem { path: p2, .. }) = arg {
784            match p2.segments.first() {
785                Some(x) => x.ident,
786                None => {
787                    span_bug!(
788                        arg.span(),
789                        "rustc_autodiff attribute must contain the input activity"
790                    );
791                }
792            }
793        } else {
794            span_bug!(arg.span(), "rustc_autodiff attribute must contain the input activity");
795        };
796
797        match DiffActivity::from_str(arg_symbol.as_str()) {
798            Ok(arg_activity) => arg_activities.push(arg_activity),
799            Err(_) => {
800                span_bug!(arg_symbol.span, "invalid input activity");
801            }
802        }
803    }
804
805    Some(AutoDiffAttrs { mode, width, ret_activity, input_activity: arg_activities })
806}
807
808pub(crate) fn provide(providers: &mut Providers) {
809    *providers = Providers {
810        codegen_fn_attrs,
811        should_inherit_track_caller,
812        inherited_align,
813        sanitizer_settings_for,
814        ..*providers
815    };
816}