1use rustc_abi::{Align, ExternAbi};
2use rustc_hir::attrs::{
3AttributeKind, EiiImplResolution, InlineAttr, Linkage, RtsanSetting, UsedBy,
4};
5use rustc_hir::def::DefKind;
6use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId};
7use rustc_hir::{selfas hir, Attribute, find_attr};
8use rustc_middle::middle::codegen_fn_attrs::{
9CodegenFnAttrFlags, CodegenFnAttrs, PatchableFunctionEntry, SanitizerFnAttrs,
10};
11use rustc_middle::mir::mono::Visibility;
12use rustc_middle::query::Providers;
13use rustc_middle::ty::{selfas ty, TyCtxt};
14use rustc_session::lint;
15use rustc_session::parse::feature_err;
16use rustc_span::{Span, sym};
17use rustc_target::spec::Os;
1819use crate::errors;
20use crate::target_features::{
21check_target_feature_trait_unsafe, check_tied_features, from_target_feature_attr,
22};
2324/// 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>>> {
34use DefKind::*;
3536let def_kind = tcx.def_kind(did);
37if let Fn | AssocFn | Variant | Ctor(..) = def_kind {
38Some(tcx.fn_sig(did))
39 } else {
40tcx.dcx().span_delayed_bug(attr_span, "this attribute can only be applied to functions");
41None42 }
43}
4445/// 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}
5455/// 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 {
63let mut interesting_spans = InterestingAttributeDiagnosticSpans::default();
64let rust_target_features = tcx.rust_target_features(LOCAL_CRATE);
6566let parsed_attrs = attrs67 .iter()
68 .filter_map(|attr| if let hir::Attribute::Parsed(attr) = attr { Some(attr) } else { None });
69for attr in parsed_attrs {
70match 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
82if 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);
93if 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 } => {
102let 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");
104continue;
105 };
106let 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;
109if safe_target_features && !was_forced {
110if 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) => {
146let is_closure = tcx.is_closure_like(did.to_def_id());
147148if !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 }
154if 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 => {
172let 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.
178CodegenFnAttrFlags::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) => {
191let linkage = Some(*linkage);
192193if tcx.is_foreign_item(did) {
194 codegen_fn_attrs.import_linkage = linkage;
195196if tcx.is_mutable_static(did.into()) {
197let 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) => {
225for i in impls {
226let foreign_item = match i.resolution {
227 EiiImplResolution::Macro(def_id) => {
228let 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 );
234continue;
235 };
236 extern_item
237 }
238 EiiImplResolution::Known(decl) => decl.foreign_item,
239 EiiImplResolution::Error(_eg) => continue,
240 };
241242// 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.
247if
248// if this is a default impl
249i.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 {
255continue;
256 }
257258 codegen_fn_attrs.foreign_item_symbol_aliases.push((
259 foreign_item,
260if 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 =
292Some(PatchableFunctionEntry::from_prefix_and_entry(*prefix, *entry));
293 }
294_ => {}
295 }
296 }
297298interesting_spans299}
300301/// 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.
307codegen_fn_attrs.alignment =
308 Ord::max(codegen_fn_attrs.alignment, tcx.sess.opts.unstable_opts.min_function_alignment);
309310// Passed in sanitizer settings are always the default.
311if !(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
313codegen_fn_attrs.sanitizers = tcx.sanitizer_settings_for(did);
314// On trait methods, inherit the `#[align]` of the trait's method prototype.
315codegen_fn_attrs.alignment = Ord::max(codegen_fn_attrs.alignment, tcx.inherited_align(did));
316317// 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.
320if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
321codegen_fn_attrs.inline = InlineAttr::Never;
322 }
323324// #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.
337if tcx.is_closure_like(did.to_def_id()) && codegen_fn_attrs.inline != InlineAttr::Always {
338let owner_id = tcx.parent(did.to_def_id());
339if tcx.def_kind(owner_id).has_codegen_attrs() {
340codegen_fn_attrs341 .target_features
342 .extend(tcx.codegen_fn_attrs(owner_id).target_features.iter().copied());
343 }
344 }
345346// 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.
348let 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);
349if no_builtins {
350codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_BUILTINS;
351 }
352353// inherit track-caller properly
354if tcx.should_inherit_track_caller(did) {
355codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
356 }
357358// Foreign items by default use no mangling for their symbol name.
359if tcx.is_foreign_item(did) {
360codegen_fn_attrs.flags |= CodegenFnAttrFlags::FOREIGN_ITEM;
361362// There's a few exceptions to this rule though:
363if 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
383codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_MANGLE;
384 }
385 }
386}
387388fn 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).
407if !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 {
412feature_err(
413tcx.sess,
414 sym::target_feature_inline_always,
415span,
416"cannot use `#[inline(always)]` with `#[target_feature]`",
417 )
418 .emit();
419 }
420421// warn that inline has no effect when no_sanitize is present
422if 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 {
427let hir_id = tcx.local_def_id_to_hir_id(did);
428tcx.node_span_lint(lint::builtin::INLINE_NO_SANITIZE, hir_id, sanitize_span, |lint| {
429lint.primary_message("non-default `sanitize` will have no effect after inlining");
430lint.span_note(inline_span, "inlining requested here");
431 })
432 }
433434// 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.
436if codegen_fn_attrs.sanitizers.rtsan_setting == RtsanSetting::Nonblocking437 && 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 {
447let hir_id = tcx.local_def_id_to_hir_id(did);
448tcx.node_span_lint(
449 lint::builtin::RTSAN_NONBLOCKING_ASYNC,
450hir_id,
451sanitize_span,
452 |lint| {
453lint.primary_message(r#"the async executor can run blocking code, without realtime sanitizer catching it"#);
454 }
455 );
456 }
457458// error when specifying link_name together with link_ordinal
459if let Some(_) = codegen_fn_attrs.symbol_name
460 && let Some(_) = codegen_fn_attrs.link_ordinal
461 {
462let msg = "cannot use `#[link_name]` with `#[link_ordinal]`";
463if let Some(span) = interesting_spans.link_ordinal {
464tcx.dcx().span_err(span, msg);
465 } else {
466tcx.dcx().err(msg);
467 }
468 }
469470if let Some(features) = check_tied_features(
471tcx.sess,
472&codegen_fn_attrs473 .target_features
474 .iter()
475 .map(|features| (features.name.as_str(), true))
476 .collect(),
477 ) {
478let 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));
480481tcx.dcx()
482 .create_err(errors::TargetFeatureDisableOrEnable {
483features,
484 span: Some(span),
485 missing_features: Some(errors::MissingFeatures),
486 })
487 .emit();
488 }
489}
490491fn handle_lang_items(
492 tcx: TyCtxt<'_>,
493 did: LocalDefId,
494 interesting_spans: &InterestingAttributeDiagnosticSpans,
495 attrs: &[Attribute],
496 codegen_fn_attrs: &mut CodegenFnAttrs,
497) {
498let 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);
499500// 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.
505if let Some(lang_item) = lang_item506 && let Some(link_name) = lang_item.link_name()
507 {
508codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
509codegen_fn_attrs.symbol_name = Some(link_name);
510 }
511512// error when using no_mangle on a lang item item
513if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL)
514 && codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NO_MANGLE)
515 {
516let mut err = tcx517 .dcx()
518 .struct_span_err(
519interesting_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");
524if let Some(lang_item) = lang_item525 && let Some(link_name) = lang_item.link_name()
526 {
527err = err528 .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 }
534err.emit();
535 }
536}
537538/// 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 {
547if truecfg!(debug_assertions) {
548let def_kind = tcx.def_kind(did);
549if !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 }
554555let mut codegen_fn_attrs = CodegenFnAttrs::new();
556let attrs = tcx.hir_attrs(tcx.local_def_id_to_hir_id(did));
557558let interesting_spans = process_builtin_attrs(tcx, did, attrs, &mut codegen_fn_attrs);
559handle_lang_items(tcx, did, &interesting_spans, attrs, &mut codegen_fn_attrs);
560apply_overrides(tcx, did, &mut codegen_fn_attrs);
561check_result(tcx, did, interesting_spans, &codegen_fn_attrs);
562563codegen_fn_attrs564}
565566fn sanitizer_settings_for(tcx: TyCtxt<'_>, did: LocalDefId) -> SanitizerFnAttrs {
567// Backtrack to the crate root.
568let mut settings = match tcx.opt_local_parent(did) {
569// Check the parent (recursively).
570Some(parent) => tcx.sanitizer_settings_for(parent),
571// We reached the crate root without seeing an attribute, so
572 // there is no sanitizers to exclude.
573None => SanitizerFnAttrs::default(),
574 };
575576// Check for a sanitize annotation directly on this def.
577if 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
582settings.disabled &= !*on_set;
583// the off set is the set of sanitizers explicitly disabled.
584 // we or those in here.
585settings.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
589590 // if rtsan was specified here override the parent
591if let Some(rtsan) = rtsan {
592settings.rtsan_setting = *rtsan;
593 }
594 }
595settings596}
597598/// 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 {
601tcx.trait_item_of(def_id).is_some_and(|id| {
602tcx.codegen_fn_attrs(id).flags.intersects(CodegenFnAttrFlags::TRACK_CALLER)
603 })
604}
605606/// 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> {
609tcx.codegen_fn_attrs(tcx.trait_item_of(def_id)?).alignment
610}
611612pub(crate) fn provide(providers: &mut Providers) {
613*providers = Providers {
614codegen_fn_attrs,
615should_inherit_track_caller,
616inherited_align,
617sanitizer_settings_for,
618 ..*providers619 };
620}