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::{AttributeKind, InlineAttr, InstructionSetAttr, UsedBy};
7use rustc_hir::def::DefKind;
8use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId};
9use rustc_hir::{self as hir, Attribute, LangItem, find_attr, lang_items};
10use rustc_middle::middle::codegen_fn_attrs::{
11 CodegenFnAttrFlags, CodegenFnAttrs, PatchableFunctionEntry,
12};
13use rustc_middle::query::Providers;
14use rustc_middle::span_bug;
15use rustc_middle::ty::{self as ty, TyCtxt};
16use rustc_session::lint;
17use rustc_session::parse::feature_err;
18use rustc_span::{Ident, Span, sym};
19use rustc_target::spec::SanitizerSet;
20
21use crate::errors;
22use crate::errors::NoMangleNameless;
23use crate::target_features::{
24 check_target_feature_trait_unsafe, check_tied_features, from_target_feature_attr,
25};
26
27fn try_fn_sig<'tcx>(
33 tcx: TyCtxt<'tcx>,
34 did: LocalDefId,
35 attr_span: Span,
36) -> Option<ty::EarlyBinder<'tcx, ty::PolyFnSig<'tcx>>> {
37 use DefKind::*;
38
39 let def_kind = tcx.def_kind(did);
40 if let Fn | AssocFn | Variant | Ctor(..) = def_kind {
41 Some(tcx.fn_sig(did))
42 } else {
43 tcx.dcx().span_delayed_bug(attr_span, "this attribute can only be applied to functions");
44 None
45 }
46}
47
48fn parse_instruction_set_attr(tcx: TyCtxt<'_>, attr: &Attribute) -> Option<InstructionSetAttr> {
50 let list = attr.meta_item_list()?;
51
52 match &list[..] {
53 [MetaItemInner::MetaItem(set)] => {
54 let segments = set.path.segments.iter().map(|x| x.ident.name).collect::<Vec<_>>();
55 match segments.as_slice() {
56 [sym::arm, sym::a32 | sym::t32] if !tcx.sess.target.has_thumb_interworking => {
57 tcx.dcx().emit_err(errors::UnsupportedInstructionSet { span: attr.span() });
58 None
59 }
60 [sym::arm, sym::a32] => Some(InstructionSetAttr::ArmA32),
61 [sym::arm, sym::t32] => Some(InstructionSetAttr::ArmT32),
62 _ => {
63 tcx.dcx().emit_err(errors::InvalidInstructionSet { span: attr.span() });
64 None
65 }
66 }
67 }
68 [] => {
69 tcx.dcx().emit_err(errors::BareInstructionSet { span: attr.span() });
70 None
71 }
72 _ => {
73 tcx.dcx().emit_err(errors::MultipleInstructionSet { span: attr.span() });
74 None
75 }
76 }
77}
78
79fn parse_patchable_function_entry(
81 tcx: TyCtxt<'_>,
82 attr: &Attribute,
83) -> Option<PatchableFunctionEntry> {
84 attr.meta_item_list().and_then(|l| {
85 let mut prefix = None;
86 let mut entry = None;
87 for item in l {
88 let Some(meta_item) = item.meta_item() else {
89 tcx.dcx().emit_err(errors::ExpectedNameValuePair { span: item.span() });
90 continue;
91 };
92
93 let Some(name_value_lit) = meta_item.name_value_literal() else {
94 tcx.dcx().emit_err(errors::ExpectedNameValuePair { span: item.span() });
95 continue;
96 };
97
98 let attrib_to_write = match meta_item.name() {
99 Some(sym::prefix_nops) => &mut prefix,
100 Some(sym::entry_nops) => &mut entry,
101 _ => {
102 tcx.dcx().emit_err(errors::UnexpectedParameterName {
103 span: item.span(),
104 prefix_nops: sym::prefix_nops,
105 entry_nops: sym::entry_nops,
106 });
107 continue;
108 }
109 };
110
111 let rustc_ast::LitKind::Int(val, _) = name_value_lit.kind else {
112 tcx.dcx().emit_err(errors::InvalidLiteralValue { span: name_value_lit.span });
113 continue;
114 };
115
116 let Ok(val) = val.get().try_into() else {
117 tcx.dcx().emit_err(errors::OutOfRangeInteger { span: name_value_lit.span });
118 continue;
119 };
120
121 *attrib_to_write = Some(val);
122 }
123
124 if let (None, None) = (prefix, entry) {
125 tcx.dcx().span_err(attr.span(), "must specify at least one parameter");
126 }
127
128 Some(PatchableFunctionEntry::from_prefix_and_entry(prefix.unwrap_or(0), entry.unwrap_or(0)))
129 })
130}
131
132#[derive(Default)]
135struct InterestingAttributeDiagnosticSpans {
136 link_ordinal: Option<Span>,
137 sanitize: Option<Span>,
138 inline: Option<Span>,
139 no_mangle: Option<Span>,
140}
141
142fn process_builtin_attrs(
145 tcx: TyCtxt<'_>,
146 did: LocalDefId,
147 attrs: &[Attribute],
148 codegen_fn_attrs: &mut CodegenFnAttrs,
149) -> InterestingAttributeDiagnosticSpans {
150 let mut interesting_spans = InterestingAttributeDiagnosticSpans::default();
151 let rust_target_features = tcx.rust_target_features(LOCAL_CRATE);
152
153 for attr in attrs.iter() {
154 if let hir::Attribute::Parsed(p) = attr {
155 match p {
156 AttributeKind::Cold(_) => codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD,
157 AttributeKind::ExportName { name, .. } => {
158 codegen_fn_attrs.symbol_name = Some(*name)
159 }
160 AttributeKind::Inline(inline, span) => {
161 codegen_fn_attrs.inline = *inline;
162 interesting_spans.inline = Some(*span);
163 }
164 AttributeKind::Naked(_) => codegen_fn_attrs.flags |= CodegenFnAttrFlags::NAKED,
165 AttributeKind::Align { align, .. } => codegen_fn_attrs.alignment = Some(*align),
166 AttributeKind::LinkName { name, .. } => {
167 if tcx.is_foreign_item(did) {
170 codegen_fn_attrs.symbol_name = Some(*name);
171 }
172 }
173 AttributeKind::LinkOrdinal { ordinal, span } => {
174 codegen_fn_attrs.link_ordinal = Some(*ordinal);
175 interesting_spans.link_ordinal = Some(*span);
176 }
177 AttributeKind::LinkSection { name, .. } => {
178 codegen_fn_attrs.link_section = Some(*name)
179 }
180 AttributeKind::NoMangle(attr_span) => {
181 interesting_spans.no_mangle = Some(*attr_span);
182 if tcx.opt_item_name(did.to_def_id()).is_some() {
183 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
184 } else {
185 tcx.dcx().emit_err(NoMangleNameless {
186 span: *attr_span,
187 definition: format!(
188 "{} {}",
189 tcx.def_descr_article(did.to_def_id()),
190 tcx.def_descr(did.to_def_id())
191 ),
192 });
193 }
194 }
195 AttributeKind::Optimize(optimize, _) => codegen_fn_attrs.optimize = *optimize,
196 AttributeKind::TargetFeature { features, attr_span, was_forced } => {
197 let Some(sig) = tcx.hir_node_by_def_id(did).fn_sig() else {
198 tcx.dcx().span_delayed_bug(*attr_span, "target_feature applied to non-fn");
199 continue;
200 };
201 let safe_target_features =
202 matches!(sig.header.safety, hir::HeaderSafety::SafeTargetFeatures);
203 codegen_fn_attrs.safe_target_features = safe_target_features;
204 if safe_target_features && !was_forced {
205 if tcx.sess.target.is_like_wasm || tcx.sess.opts.actually_rustdoc {
206 } else {
228 check_target_feature_trait_unsafe(tcx, did, *attr_span);
229 }
230 }
231 from_target_feature_attr(
232 tcx,
233 did,
234 features,
235 *was_forced,
236 rust_target_features,
237 &mut codegen_fn_attrs.target_features,
238 );
239 }
240 AttributeKind::TrackCaller(attr_span) => {
241 let is_closure = tcx.is_closure_like(did.to_def_id());
242
243 if !is_closure
244 && let Some(fn_sig) = try_fn_sig(tcx, did, *attr_span)
245 && fn_sig.skip_binder().abi() != ExternAbi::Rust
246 {
247 tcx.dcx().emit_err(errors::RequiresRustAbi { span: *attr_span });
248 }
249 if is_closure
250 && !tcx.features().closure_track_caller()
251 && !attr_span.allows_unstable(sym::closure_track_caller)
252 {
253 feature_err(
254 &tcx.sess,
255 sym::closure_track_caller,
256 *attr_span,
257 "`#[track_caller]` on closures is currently unstable",
258 )
259 .emit();
260 }
261 codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER
262 }
263 AttributeKind::Used { used_by, .. } => match used_by {
264 UsedBy::Compiler => codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED_COMPILER,
265 UsedBy::Linker => codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED_LINKER,
266 },
267 AttributeKind::FfiConst(_) => {
268 codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_CONST
269 }
270 AttributeKind::FfiPure(_) => codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_PURE,
271 AttributeKind::StdInternalSymbol(_) => {
272 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL
273 }
274 AttributeKind::Linkage(linkage, _) => {
275 let linkage = Some(*linkage);
276
277 if tcx.is_foreign_item(did) {
278 codegen_fn_attrs.import_linkage = linkage;
279
280 if tcx.is_mutable_static(did.into()) {
281 let mut diag = tcx.dcx().struct_span_err(
282 attr.span(),
283 "extern mutable statics are not allowed with `#[linkage]`",
284 );
285 diag.note(
286 "marking the extern static mutable would allow changing which \
287 symbol the static references rather than make the target of the \
288 symbol mutable",
289 );
290 diag.emit();
291 }
292 } else {
293 codegen_fn_attrs.linkage = linkage;
294 }
295 }
296 _ => {}
297 }
298 }
299
300 let Some(Ident { name, .. }) = attr.ident() else {
301 continue;
302 };
303
304 match name {
305 sym::rustc_allocator => codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR,
306 sym::rustc_nounwind => codegen_fn_attrs.flags |= CodegenFnAttrFlags::NEVER_UNWIND,
307 sym::rustc_reallocator => codegen_fn_attrs.flags |= CodegenFnAttrFlags::REALLOCATOR,
308 sym::rustc_deallocator => codegen_fn_attrs.flags |= CodegenFnAttrFlags::DEALLOCATOR,
309 sym::rustc_allocator_zeroed => {
310 codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR_ZEROED
311 }
312 sym::thread_local => codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL,
313 sym::sanitize => interesting_spans.sanitize = Some(attr.span()),
314 sym::instruction_set => {
315 codegen_fn_attrs.instruction_set = parse_instruction_set_attr(tcx, attr)
316 }
317 sym::patchable_function_entry => {
318 codegen_fn_attrs.patchable_function_entry =
319 parse_patchable_function_entry(tcx, attr);
320 }
321 _ => {}
322 }
323 }
324
325 interesting_spans
326}
327
328fn apply_overrides(tcx: TyCtxt<'_>, did: LocalDefId, codegen_fn_attrs: &mut CodegenFnAttrs) {
331 codegen_fn_attrs.alignment =
335 Ord::max(codegen_fn_attrs.alignment, tcx.sess.opts.unstable_opts.min_function_alignment);
336
337 codegen_fn_attrs.no_sanitize |= tcx.disabled_sanitizers_for(did);
339 codegen_fn_attrs.alignment = Ord::max(codegen_fn_attrs.alignment, tcx.inherited_align(did));
341
342 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
346 codegen_fn_attrs.inline = InlineAttr::Never;
347 }
348
349 if tcx.is_closure_like(did.to_def_id()) && codegen_fn_attrs.inline != InlineAttr::Always {
363 let owner_id = tcx.parent(did.to_def_id());
364 if tcx.def_kind(owner_id).has_codegen_attrs() {
365 codegen_fn_attrs
366 .target_features
367 .extend(tcx.codegen_fn_attrs(owner_id).target_features.iter().copied());
368 }
369 }
370
371 let crate_attrs = tcx.hir_attrs(rustc_hir::CRATE_HIR_ID);
374 let no_builtins = attr::contains_name(crate_attrs, sym::no_builtins);
375 if no_builtins {
376 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_BUILTINS;
377 }
378
379 if tcx.should_inherit_track_caller(did) {
381 codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
382 }
383
384 if tcx.is_foreign_item(did) {
386 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) {
388 } else if codegen_fn_attrs.symbol_name.is_some() {
392 } else {
394 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
402 }
403 }
404}
405
406fn check_result(
407 tcx: TyCtxt<'_>,
408 did: LocalDefId,
409 interesting_spans: InterestingAttributeDiagnosticSpans,
410 codegen_fn_attrs: &CodegenFnAttrs,
411) {
412 if !codegen_fn_attrs.target_features.is_empty()
426 && matches!(codegen_fn_attrs.inline, InlineAttr::Always)
427 && let Some(span) = interesting_spans.inline
428 {
429 tcx.dcx().span_err(span, "cannot use `#[inline(always)]` with `#[target_feature]`");
430 }
431
432 if !codegen_fn_attrs.no_sanitize.is_empty()
434 && codegen_fn_attrs.inline.always()
435 && let (Some(no_sanitize_span), Some(inline_span)) =
436 (interesting_spans.sanitize, interesting_spans.inline)
437 {
438 let hir_id = tcx.local_def_id_to_hir_id(did);
439 tcx.node_span_lint(lint::builtin::INLINE_NO_SANITIZE, hir_id, no_sanitize_span, |lint| {
440 lint.primary_message("setting `sanitize` off will have no effect after inlining");
441 lint.span_note(inline_span, "inlining requested here");
442 })
443 }
444
445 if let Some(_) = codegen_fn_attrs.symbol_name
447 && let Some(_) = codegen_fn_attrs.link_ordinal
448 {
449 let msg = "cannot use `#[link_name]` with `#[link_ordinal]`";
450 if let Some(span) = interesting_spans.link_ordinal {
451 tcx.dcx().span_err(span, msg);
452 } else {
453 tcx.dcx().err(msg);
454 }
455 }
456
457 if let Some(features) = check_tied_features(
458 tcx.sess,
459 &codegen_fn_attrs
460 .target_features
461 .iter()
462 .map(|features| (features.name.as_str(), true))
463 .collect(),
464 ) {
465 let span =
466 find_attr!(tcx.get_all_attrs(did), AttributeKind::TargetFeature{attr_span: span, ..} => *span)
467 .unwrap_or_else(|| tcx.def_span(did));
468
469 tcx.dcx()
470 .create_err(errors::TargetFeatureDisableOrEnable {
471 features,
472 span: Some(span),
473 missing_features: Some(errors::MissingFeatures),
474 })
475 .emit();
476 }
477}
478
479fn handle_lang_items(
480 tcx: TyCtxt<'_>,
481 did: LocalDefId,
482 interesting_spans: &InterestingAttributeDiagnosticSpans,
483 attrs: &[Attribute],
484 codegen_fn_attrs: &mut CodegenFnAttrs,
485) {
486 let lang_item = lang_items::extract(attrs).and_then(|(name, _)| LangItem::from_name(name));
487
488 if let Some(lang_item) = lang_item
494 && let Some(link_name) = lang_item.link_name()
495 {
496 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
497 codegen_fn_attrs.symbol_name = Some(link_name);
498 }
499
500 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL)
502 && codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NO_MANGLE)
503 {
504 let mut err = tcx
505 .dcx()
506 .struct_span_err(
507 interesting_spans.no_mangle.unwrap_or_default(),
508 "`#[no_mangle]` cannot be used on internal language items",
509 )
510 .with_note("Rustc requires this item to have a specific mangled name.")
511 .with_span_label(tcx.def_span(did), "should be the internal language item");
512 if let Some(lang_item) = lang_item
513 && let Some(link_name) = lang_item.link_name()
514 {
515 err = err
516 .with_note("If you are trying to prevent mangling to ease debugging, many")
517 .with_note(format!("debuggers support a command such as `rbreak {link_name}` to"))
518 .with_note(format!(
519 "match `.*{link_name}.*` instead of `break {link_name}` on a specific name"
520 ))
521 }
522 err.emit();
523 }
524}
525
526fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
535 if cfg!(debug_assertions) {
536 let def_kind = tcx.def_kind(did);
537 assert!(
538 def_kind.has_codegen_attrs(),
539 "unexpected `def_kind` in `codegen_fn_attrs`: {def_kind:?}",
540 );
541 }
542
543 let mut codegen_fn_attrs = CodegenFnAttrs::new();
544 let attrs = tcx.hir_attrs(tcx.local_def_id_to_hir_id(did));
545
546 let interesting_spans = process_builtin_attrs(tcx, did, attrs, &mut codegen_fn_attrs);
547 handle_lang_items(tcx, did, &interesting_spans, attrs, &mut codegen_fn_attrs);
548 apply_overrides(tcx, did, &mut codegen_fn_attrs);
549 check_result(tcx, did, interesting_spans, &codegen_fn_attrs);
550
551 codegen_fn_attrs
552}
553
554fn opt_trait_item(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
556 let impl_item = tcx.opt_associated_item(def_id)?;
557 match impl_item.container {
558 ty::AssocItemContainer::Impl => impl_item.trait_item_def_id,
559 _ => None,
560 }
561}
562
563fn parse_sanitize_attr(
567 tcx: TyCtxt<'_>,
568 attr: &Attribute,
569 current_attr: SanitizerSet,
570) -> SanitizerSet {
571 let mut result = current_attr;
572 if let Some(list) = attr.meta_item_list() {
573 for item in list.iter() {
574 let MetaItemInner::MetaItem(set) = item else {
575 tcx.dcx().emit_err(errors::InvalidSanitize { span: attr.span() });
576 break;
577 };
578 let segments = set.path.segments.iter().map(|x| x.ident.name).collect::<Vec<_>>();
579 match segments.as_slice() {
580 [sym::address] | [sym::kernel_address] if set.value_str() == Some(sym::off) => {
584 result |= SanitizerSet::ADDRESS | SanitizerSet::KERNELADDRESS
585 }
586 [sym::address] | [sym::kernel_address] if set.value_str() == Some(sym::on) => {
587 result &= !SanitizerSet::ADDRESS;
588 result &= !SanitizerSet::KERNELADDRESS;
589 }
590 [sym::cfi] if set.value_str() == Some(sym::off) => result |= SanitizerSet::CFI,
591 [sym::cfi] if set.value_str() == Some(sym::on) => result &= !SanitizerSet::CFI,
592 [sym::kcfi] if set.value_str() == Some(sym::off) => result |= SanitizerSet::KCFI,
593 [sym::kcfi] if set.value_str() == Some(sym::on) => result &= !SanitizerSet::KCFI,
594 [sym::memory] if set.value_str() == Some(sym::off) => {
595 result |= SanitizerSet::MEMORY
596 }
597 [sym::memory] if set.value_str() == Some(sym::on) => {
598 result &= !SanitizerSet::MEMORY
599 }
600 [sym::memtag] if set.value_str() == Some(sym::off) => {
601 result |= SanitizerSet::MEMTAG
602 }
603 [sym::memtag] if set.value_str() == Some(sym::on) => {
604 result &= !SanitizerSet::MEMTAG
605 }
606 [sym::shadow_call_stack] if set.value_str() == Some(sym::off) => {
607 result |= SanitizerSet::SHADOWCALLSTACK
608 }
609 [sym::shadow_call_stack] if set.value_str() == Some(sym::on) => {
610 result &= !SanitizerSet::SHADOWCALLSTACK
611 }
612 [sym::thread] if set.value_str() == Some(sym::off) => {
613 result |= SanitizerSet::THREAD
614 }
615 [sym::thread] if set.value_str() == Some(sym::on) => {
616 result &= !SanitizerSet::THREAD
617 }
618 [sym::hwaddress] if set.value_str() == Some(sym::off) => {
619 result |= SanitizerSet::HWADDRESS
620 }
621 [sym::hwaddress] if set.value_str() == Some(sym::on) => {
622 result &= !SanitizerSet::HWADDRESS
623 }
624 _ => {
625 tcx.dcx().emit_err(errors::InvalidSanitize { span: attr.span() });
626 }
627 }
628 }
629 }
630 result
631}
632
633fn disabled_sanitizers_for(tcx: TyCtxt<'_>, did: LocalDefId) -> SanitizerSet {
634 let disabled = match tcx.opt_local_parent(did) {
636 Some(parent) => tcx.disabled_sanitizers_for(parent),
638 None => SanitizerSet::empty(),
641 };
642
643 if let Some(attr) = tcx.get_attr(did, sym::sanitize) {
645 return parse_sanitize_attr(tcx, attr, disabled);
646 }
647 disabled
648}
649
650fn should_inherit_track_caller(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
653 let Some(trait_item) = opt_trait_item(tcx, def_id) else { return false };
654 tcx.codegen_fn_attrs(trait_item).flags.intersects(CodegenFnAttrFlags::TRACK_CALLER)
655}
656
657fn inherited_align<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> Option<Align> {
660 tcx.codegen_fn_attrs(opt_trait_item(tcx, def_id)?).alignment
661}
662
663pub fn autodiff_attrs(tcx: TyCtxt<'_>, id: DefId) -> Option<AutoDiffAttrs> {
670 let attrs = tcx.get_attrs(id, sym::rustc_autodiff);
671
672 let attrs = attrs.filter(|attr| attr.has_name(sym::rustc_autodiff)).collect::<Vec<_>>();
673
674 let attr = match &attrs[..] {
677 [] => return None,
678 [attr] => attr,
679 _ => {
680 span_bug!(attrs[1].span(), "cg_ssa: rustc_autodiff should only exist once per source");
681 }
682 };
683
684 let list = attr.meta_item_list().unwrap_or_default();
685
686 if list.is_empty() {
688 return Some(AutoDiffAttrs::source());
689 }
690
691 let [mode, width_meta, input_activities @ .., ret_activity] = &list[..] else {
692 span_bug!(attr.span(), "rustc_autodiff attribute must contain mode, width and activities");
693 };
694 let mode = if let MetaItemInner::MetaItem(MetaItem { path: p1, .. }) = mode {
695 p1.segments.first().unwrap().ident
696 } else {
697 span_bug!(attr.span(), "rustc_autodiff attribute must contain mode");
698 };
699
700 let mode = match mode.as_str() {
702 "Forward" => DiffMode::Forward,
703 "Reverse" => DiffMode::Reverse,
704 _ => {
705 span_bug!(mode.span, "rustc_autodiff attribute contains invalid mode");
706 }
707 };
708
709 let width: u32 = match width_meta {
710 MetaItemInner::MetaItem(MetaItem { path: p1, .. }) => {
711 let w = p1.segments.first().unwrap().ident;
712 match w.as_str().parse() {
713 Ok(val) => val,
714 Err(_) => {
715 span_bug!(w.span, "rustc_autodiff width should fit u32");
716 }
717 }
718 }
719 MetaItemInner::Lit(lit) => {
720 if let LitKind::Int(val, _) = lit.kind {
721 match val.get().try_into() {
722 Ok(val) => val,
723 Err(_) => {
724 span_bug!(lit.span, "rustc_autodiff width should fit u32");
725 }
726 }
727 } else {
728 span_bug!(lit.span, "rustc_autodiff width should be an integer");
729 }
730 }
731 };
732
733 let ret_symbol = if let MetaItemInner::MetaItem(MetaItem { path: p1, .. }) = ret_activity {
735 p1.segments.first().unwrap().ident
736 } else {
737 span_bug!(attr.span(), "rustc_autodiff attribute must contain the return activity");
738 };
739
740 let Ok(ret_activity) = DiffActivity::from_str(ret_symbol.as_str()) else {
742 span_bug!(ret_symbol.span, "invalid return activity");
743 };
744
745 let mut arg_activities: Vec<DiffActivity> = vec![];
747 for arg in input_activities {
748 let arg_symbol = if let MetaItemInner::MetaItem(MetaItem { path: p2, .. }) = arg {
749 match p2.segments.first() {
750 Some(x) => x.ident,
751 None => {
752 span_bug!(
753 arg.span(),
754 "rustc_autodiff attribute must contain the input activity"
755 );
756 }
757 }
758 } else {
759 span_bug!(arg.span(), "rustc_autodiff attribute must contain the input activity");
760 };
761
762 match DiffActivity::from_str(arg_symbol.as_str()) {
763 Ok(arg_activity) => arg_activities.push(arg_activity),
764 Err(_) => {
765 span_bug!(arg_symbol.span, "invalid input activity");
766 }
767 }
768 }
769
770 Some(AutoDiffAttrs { mode, width, ret_activity, input_activity: arg_activities })
771}
772
773pub(crate) fn provide(providers: &mut Providers) {
774 *providers = Providers {
775 codegen_fn_attrs,
776 should_inherit_track_caller,
777 inherited_align,
778 disabled_sanitizers_for,
779 ..*providers
780 };
781}