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