1use rustc_abi::{Align, ExternAbi};
2use rustc_attr_ir::{
3Attribute, AttributeKind, EiiImplResolution, InlineAttr, Linkage, OptimizeAttr, RtsanSetting,
4UsedBy, find_attr,
5};
6use rustc_hiras hir;
7use rustc_hir::def::DefKind;
8use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId};
9use rustc_lint_defs::builtin::{INLINE_NO_SANITIZE, RTSAN_NONBLOCKING_ASYNC};
10use rustc_macros::Diagnostic;
11use rustc_middle::middle::codegen_fn_attrs::{
12CodegenFnAttrFlags, CodegenFnAttrs, PatchableFunctionEntry, SanitizerFnAttrs,
13};
14use rustc_middle::mono::Visibility;
15use rustc_middle::query::Providers;
16use rustc_middle::ty::{selfas ty, TyCtxt};
17use rustc_span::{Span, bug};
18use rustc_target::spec::Os;
1920use crate::diagnostics;
21use crate::target_features::{
22check_target_feature_trait_unsafe, check_tied_features, from_target_feature_attr,
23};
2425/// In some cases, attributes are only valid on functions, but it's the `check_attr`
26/// pass that checks that they aren't used anywhere else, rather than this module.
27/// In these cases, we bail from performing further checks that are only meaningful for
28/// functions (such as calling `fn_sig`, which ICEs if given a non-function). We also
29/// report a delayed bug, just in case `check_attr` isn't doing its job.
30fn try_fn_sig<'tcx>(
31 tcx: TyCtxt<'tcx>,
32 did: LocalDefId,
33 attr_span: Span,
34) -> Option<ty::EarlyBinder<'tcx, ty::PolyFnSig<'tcx>>> {
35use DefKind::*;
3637let def_kind = tcx.def_kind(did);
38if let Fn | AssocFn | Variant | Ctor(..) = def_kind {
39Some(tcx.fn_sig(did))
40 } else {
41tcx.dcx().span_delayed_bug(attr_span, "this attribute can only be applied to functions");
42None43 }
44}
4546/// Spans that are collected when processing built-in attributes,
47/// that are useful for emitting diagnostics later.
48#[derive(#[automatically_derived]impl ::core::default::Default for
InterestingAttributeDiagnosticSpans {
#[inline]
fn default() -> Self {
InterestingAttributeDiagnosticSpans {
link_ordinal: ::core::default::Default::default(),
sanitize: ::core::default::Default::default(),
inline: ::core::default::Default::default(),
no_mangle: ::core::default::Default::default(),
}
}
}Default)]
49struct InterestingAttributeDiagnosticSpans {
50 link_ordinal: Option<Span>,
51 sanitize: Option<Span>,
52 inline: Option<Span>,
53 no_mangle: Option<Span>,
54}
5556/// Process the builtin attrs ([`rustc_attr_ir::Attribute`]) on the item.
57/// Many of them directly translate to codegen attrs.
58fn process_builtin_attrs(
59 tcx: TyCtxt<'_>,
60 did: LocalDefId,
61 attrs: &[Attribute],
62 codegen_fn_attrs: &mut CodegenFnAttrs,
63) -> InterestingAttributeDiagnosticSpans {
64let mut interesting_spans = InterestingAttributeDiagnosticSpans::default();
65let rust_target_features = tcx.all_rust_target_features(LOCAL_CRATE);
6667let parsed_attrs = attrs68 .iter()
69 .filter_map(|attr| if let Attribute::Parsed(attr) = attr { Some(attr) } else { None });
70for attr in parsed_attrs {
71match attr {
72 AttributeKind::Cold => codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD,
73 AttributeKind::ExportName { name, .. } => codegen_fn_attrs.symbol_name = Some(*name),
74 AttributeKind::Inline(inline, span) => {
75// On an `async fn` (or similar), inlining hints are meant for the code the user
76 // wrote, which lives in the body coroutine. The constructor is trivial and left to
77 // the usual heuristics.
78if !constructs_desugared_body_coroutine(tcx, did) {
79 codegen_fn_attrs.inline = *inline;
80 interesting_spans.inline = Some(*span);
81 }
82 }
83 AttributeKind::Naked(_) => codegen_fn_attrs.flags |= CodegenFnAttrFlags::NAKED,
84 AttributeKind::RustcAlign { align, .. } => codegen_fn_attrs.alignment = Some(*align),
85 AttributeKind::LinkName { name, .. } => {
86// FIXME Remove check for foreign functions once #[link_name] on non-foreign
87 // functions is a hard error
88if tcx.is_foreign_item(did) {
89 codegen_fn_attrs.symbol_name = Some(*name);
90 }
91 }
92 AttributeKind::LinkOrdinal { ordinal, span } => {
93 codegen_fn_attrs.link_ordinal = Some(*ordinal);
94 interesting_spans.link_ordinal = Some(*span);
95 }
96 AttributeKind::LinkSection { name } => codegen_fn_attrs.link_section = Some(*name),
97 AttributeKind::NoMangle(attr_span) => {
98 interesting_spans.no_mangle = Some(*attr_span);
99if let Some(name) = tcx.opt_item_name(did.to_def_id()) {
100// Don't override #[export_name].
101102 // Also don't override #[link_name]. All places where #[link_name] is allowed
103 // shouldn't allow #[no_mangle], so #[link_name] shouldn't be a concern here,
104 // however currently #[no_mangle] is currently merely a warning on foreign
105 // items rather than a hard error, so we still need to take #[no_mangle] +
106 // #[link_name] into account.
107 // FIXME remove this comment once #[no_mangle] on foreign items is a hard error.
108109if codegen_fn_attrs.symbol_name.is_none() {
110 codegen_fn_attrs.symbol_name = Some(name);
111 }
112 } else {
113 tcx.dcx()
114 .span_delayed_bug(*attr_span, "no_mangle should be on a named function");
115 }
116 }
117 AttributeKind::Optimize(optimize, _) => codegen_fn_attrs.optimize = *optimize,
118 AttributeKind::TargetFeature { features, attr_span, was_forced } => {
119let Some(sig) = tcx.hir_node_by_def_id(did).fn_sig() else {
120 tcx.dcx().span_delayed_bug(*attr_span, "target_feature applied to non-fn");
121continue;
122 };
123let safe_target_features =
124#[allow(non_exhaustive_omitted_patterns)] match sig.header.safety {
hir::HeaderSafety::SafeTargetFeatures => true,
_ => false,
}matches!(sig.header.safety, hir::HeaderSafety::SafeTargetFeatures);
125 codegen_fn_attrs.safe_target_features = safe_target_features;
126if safe_target_features && !was_forced {
127if tcx.sess.target.is_like_wasm || tcx.sess.opts.actually_rustdoc {
128// The `#[target_feature]` attribute is allowed on
129 // WebAssembly targets on all functions. Prior to stabilizing
130 // the `target_feature_11` feature, `#[target_feature]` was
131 // only permitted on unsafe functions because on most targets
132 // execution of instructions that are not supported is
133 // considered undefined behavior. For WebAssembly which is a
134 // 100% safe target at execution time it's not possible to
135 // execute undefined instructions, and even if a future
136 // feature was added in some form for this it would be a
137 // deterministic trap. There is no undefined behavior when
138 // executing WebAssembly so `#[target_feature]` is allowed
139 // on safe functions (but again, only for WebAssembly)
140 //
141 // Note that this is also allowed if `actually_rustdoc` so
142 // if a target is documenting some wasm-specific code then
143 // it's not spuriously denied.
144 //
145 // Now that `#[target_feature]` is permitted on safe functions,
146 // this exception must still exist for allowing the attribute on
147 // `main`, `start`, and other functions that are not usually
148 // allowed.
149} else {
150 check_target_feature_trait_unsafe(tcx, did, *attr_span);
151 }
152 }
153 from_target_feature_attr(
154 tcx,
155 did,
156 features,
157*was_forced,
158 rust_target_features,
159&mut codegen_fn_attrs.target_features,
160 );
161 }
162 AttributeKind::TrackCaller(attr_span) => {
163let is_closure = tcx.is_closure_like(did.to_def_id());
164165if !is_closure
166 && let Some(fn_sig) = try_fn_sig(tcx, did, *attr_span)
167 && fn_sig.skip_binder().abi() != ExternAbi::Rust
168 {
169// This error is already reported in `rustc_ast_passes/src/ast_validation.rs`.
170tcx.dcx().delayed_bug("`#[track_caller]` requires the Rust ABI");
171 }
172 codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER
173 }
174 AttributeKind::Used { used_by } => match used_by {
175 UsedBy::Compiler => codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED_COMPILER,
176 UsedBy::Linker => codegen_fn_attrs.flags |= CodegenFnAttrFlags::USED_LINKER,
177 UsedBy::Default => {
178let used_form = if tcx.sess.target.os == Os::Illumos {
179// illumos' `ld` doesn't support a section header that would represent
180 // `#[used(linker)]`, see
181 // https://github.com/rust-lang/rust/issues/146169. For that target,
182 // downgrade as if `#[used(compiler)]` was requested and hope for the
183 // best.
184CodegenFnAttrFlags::USED_COMPILER
185 } else {
186 CodegenFnAttrFlags::USED_LINKER
187 };
188 codegen_fn_attrs.flags |= used_form;
189 }
190 },
191 AttributeKind::FfiConst => codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_CONST,
192 AttributeKind::FfiPure(_) => codegen_fn_attrs.flags |= CodegenFnAttrFlags::FFI_PURE,
193 AttributeKind::RustcStdInternalSymbol => {
194 codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL
195 }
196 AttributeKind::Linkage(linkage, span) => {
197let linkage = Some(*linkage);
198199if tcx.is_foreign_item(did) {
200 codegen_fn_attrs.import_linkage = linkage;
201202if tcx.is_mutable_static(did.into()) {
203 tcx.dcx().span_delayed_bug(
204*span,
205"`extern { #[linkage] static mut ...` is checked in check_attr}",
206 );
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::EiiImpl(i) => {
225let foreign_item = match i.resolution {
226 EiiImplResolution::Macro(def_id) => {
227let Some(extern_item) = {
{
'done:
{
for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(EiiDeclaration(target))
=> {
break 'done Some(target.foreign_item);
}
::rustc_attr_ir::Attribute::Tool { .. } |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(tcx, def_id, EiiDeclaration(target) => target.foreign_item
228 )else {
229 tcx.dcx().span_delayed_bug(
230 i.span,
231"resolved to something that's not an EII",
232 );
233continue;
234 };
235 extern_item
236 }
237 EiiImplResolution::Known(def_id) => def_id,
238 EiiImplResolution::Error(_eg) => continue,
239 };
240241// this is to prevent a bug where a single crate defines both the default and explicit implementation
242 // for an EII. In that case, both of them may be part of the same final object file. I'm not 100% sure
243 // what happens, either rustc deduplicates the symbol or llvm, or it's random/order-dependent.
244 // However, the fact that the default one of has weak linkage isn't considered and you sometimes get that
245 // the default implementation is used while an explicit implementation is given.
246if
247// if this is a default impl
248i.is_default
249// iterate over all implementations *in the current crate*
250 // (this is ok since we generate codegen fn attrs in the local crate)
251 // if any of them is *not default* then don't emit the alias.
252&& {
253let (_, impls) = tcx.externally_implementable_items(LOCAL_CRATE).get(&foreign_item).unwrap_or_else(|| ::rustc_span::macros::bug_impl(None,
format_args!("EII impl should have an entry"), Location::caller())bug!("EII impl should have an entry"));
254 impls.iter().any(|(_, imp)| !imp.is_default)
255 }
256 {
257continue;
258 }
259260 codegen_fn_attrs.foreign_item_symbol_aliases.push((
261 foreign_item,
262if i.is_default { Linkage::WeakAny } else { Linkage::External },
263 Visibility::Default,
264 ));
265 codegen_fn_attrs.flags |= CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM;
266267// If the declaration is `#[track_caller]`, derive it onto the implementation
268 // too. The shim that forwards to this impl (see `add_function_aliases`) takes
269 // its ABI from the impl's `fn_abi`, so every impl must agree on whether the
270 // caller-location argument is present, otherwise it would be silently dropped.
271if tcx
272 .codegen_fn_attrs(foreign_item)
273 .flags
274 .contains(CodegenFnAttrFlags::TRACK_CALLER)
275 {
276 codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
277 }
278 }
279 AttributeKind::ThreadLocal => {
280 codegen_fn_attrs.flags |= CodegenFnAttrFlags::THREAD_LOCAL
281 }
282 AttributeKind::InstructionSet(instruction_set) => {
283 codegen_fn_attrs.instruction_set = Some(*instruction_set)
284 }
285 AttributeKind::RustcAllocator => {
286 codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR
287 }
288 AttributeKind::RustcDeallocator => {
289 codegen_fn_attrs.flags |= CodegenFnAttrFlags::DEALLOCATOR
290 }
291 AttributeKind::RustcReallocator => {
292 codegen_fn_attrs.flags |= CodegenFnAttrFlags::REALLOCATOR
293 }
294 AttributeKind::RustcAllocatorZeroed => {
295 codegen_fn_attrs.flags |= CodegenFnAttrFlags::ALLOCATOR_ZEROED
296 }
297 AttributeKind::RustcNounwind => {
298 codegen_fn_attrs.flags |= CodegenFnAttrFlags::NEVER_UNWIND
299 }
300 AttributeKind::RustcOffloadKernel => {
301 codegen_fn_attrs.flags |= CodegenFnAttrFlags::OFFLOAD_KERNEL
302 }
303 AttributeKind::PatchableFunctionEntry { prefix, entry, section } => {
304 codegen_fn_attrs.patchable_function_entry =
305Some(PatchableFunctionEntry::from_prefix_entry_and_section(
306*prefix, *entry, *section,
307 ));
308 }
309 AttributeKind::InstrumentFn(instrument_fn) => {
310 codegen_fn_attrs.instrument_fn = Some(*instrument_fn);
311 }
312_ => {}
313 }
314 }
315316// The body coroutine can't carry attributes of its own, so it takes the ones describing the
317 // code the user wrote from the `async fn` (or similar) it was desugared from. This makes e.g.
318 // `#[inline(never)] async fn` affect `Future::poll`. See #129347.
319if is_desugared_body_coroutine(tcx, did) {
320let parent = tcx.local_parent(did);
321// `#[rustc_force_inline]` is already rejected on the parent. Propagating it would only
322 // cause `CheckForceInline` to report the same attribute again for the coroutine.
323if let Some((inline, span)) = {
{
'done:
{
for i in ::rustc_attr_ir::HasAttrs::get_attrs(parent, &tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(Inline(inline, span)) if
!#[allow(non_exhaustive_omitted_patterns)] match inline {
InlineAttr::Force { .. } => true,
_ => false,
} => {
break 'done Some((*inline, *span));
}
::rustc_attr_ir::Attribute::Tool { .. } |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(
324 tcx,
325 parent,
326 Inline(inline, span) if !matches!(inline, InlineAttr::Force { .. }) => (*inline, *span)
327 ) {
328codegen_fn_attrs.inline = inline;
329interesting_spans.inline = Some(span);
330 }
331// Unlike inlining hints, `#[cold]` stays on the constructor as well: calling it is just as
332 // unlikely, and its call sites are only recognized as cold through that.
333if {
{
'done:
{
for i in ::rustc_attr_ir::HasAttrs::get_attrs(parent, &tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(Cold) => {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Tool { .. } |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}.is_some()find_attr!(tcx, parent, Cold) {
334codegen_fn_attrs.flags |= CodegenFnAttrFlags::COLD;
335 }
336 }
337338interesting_spans339}
340341/// Whether `did` is the coroutine holding the body of an `async fn`, `gen fn`, `async gen fn`, or
342/// `async` closure, as opposed to one written as an `async {}` block.
343fn is_desugared_body_coroutine(tcx: TyCtxt<'_>, did: LocalDefId) -> bool {
344#[allow(non_exhaustive_omitted_patterns)] match tcx.coroutine_kind(did) {
Some(hir::CoroutineKind::Desugared(_,
hir::CoroutineSource::Fn | hir::CoroutineSource::Closure)) => true,
_ => false,
}matches!(
345 tcx.coroutine_kind(did),
346Some(hir::CoroutineKind::Desugared(
347_,
348 hir::CoroutineSource::Fn | hir::CoroutineSource::Closure
349 ))
350 )351}
352353/// Whether `did` is an `async fn`, `gen fn`, `async gen fn`, or `async` closure, i.e. its body
354/// does nothing but construct a [desugared body coroutine](is_desugared_body_coroutine).
355fn constructs_desugared_body_coroutine(tcx: TyCtxt<'_>, did: LocalDefId) -> bool {
356tcx.hir_maybe_body_owned_by(did).is_some_and(|body| {
357#[allow(non_exhaustive_omitted_patterns)] match body.value.kind {
hir::ExprKind::Closure(closure) if
is_desugared_body_coroutine(tcx, closure.def_id) => true,
_ => false,
}matches!(
358 body.value.kind,
359 hir::ExprKind::Closure(closure) if is_desugared_body_coroutine(tcx, closure.def_id)
360 )361 })
362}
363364/// Applies overrides for codegen fn attrs. These often have a specific reason why they're necessary.
365/// Please comment why when adding a new one!
366fn apply_overrides(tcx: TyCtxt<'_>, did: LocalDefId, codegen_fn_attrs: &mut CodegenFnAttrs) {
367// Apply the minimum function alignment here. This ensures that a function's alignment is
368 // determined by the `-C` flags of the crate it is defined in, not the `-C` flags of the crate
369 // it happens to be codegen'd (or const-eval'd) in.
370codegen_fn_attrs.alignment =
371 Ord::max(codegen_fn_attrs.alignment, tcx.sess.opts.unstable_opts.min_function_alignment);
372373// Passed in sanitizer settings are always the default.
374if !(codegen_fn_attrs.sanitizers == SanitizerFnAttrs::default()) {
::core::panicking::panic("assertion failed: codegen_fn_attrs.sanitizers == SanitizerFnAttrs::default()")
};assert!(codegen_fn_attrs.sanitizers == SanitizerFnAttrs::default());
375// Replace with #[sanitize] value
376codegen_fn_attrs.sanitizers = tcx.sanitizer_settings_for(did);
377// On trait methods, inherit the `#[align]` of the trait's method prototype.
378codegen_fn_attrs.alignment = Ord::max(codegen_fn_attrs.alignment, tcx.inherited_align(did));
379380// naked function MUST NOT be inlined! This attribute is required for the rust compiler itself,
381 // but not for the code generation backend because at that point the naked function will just be
382 // a declaration, with a definition provided in global assembly.
383if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
384codegen_fn_attrs.inline = InlineAttr::Never;
385 }
386387// #73631: closures inherit `#[target_feature]` annotations
388 //
389 // If this closure is marked `#[inline(always)]`, simply skip adding `#[target_feature]`.
390 //
391 // At this point, `unsafe` has already been checked and `#[target_feature]` only affects codegen.
392 // Due to LLVM limitations, emitting both `#[inline(always)]` and `#[target_feature]` is *unsound*:
393 // the function may be inlined into a caller with fewer target features. Also see
394 // <https://github.com/rust-lang/rust/issues/116573>.
395 //
396 // Using `#[inline(always)]` implies that this closure will most likely be inlined into
397 // its parent function, which effectively inherits the features anyway. Boxing this closure
398 // would result in this closure being compiled without the inherited target features, but this
399 // is probably a poor usage of `#[inline(always)]` and easily avoided by not using the attribute.
400 //
401 // That reasoning doesn't hold for the body coroutine of an `async fn` or `gen fn`: it is never
402 // inlined into the function constructing it, yet its body was checked as part of that function.
403 // It always inherits, so it is compiled with the same features as the function itself.
404if tcx.is_closure_like(did.to_def_id())
405 && (codegen_fn_attrs.inline != InlineAttr::Always406 || #[allow(non_exhaustive_omitted_patterns)] match tcx.coroutine_kind(did) {
Some(hir::CoroutineKind::Desugared(_, hir::CoroutineSource::Fn)) => true,
_ => false,
}matches!(
407 tcx.coroutine_kind(did),
408Some(hir::CoroutineKind::Desugared(_, hir::CoroutineSource::Fn))
409 ))
410 {
411let owner_id = tcx.parent(did.to_def_id());
412if tcx.def_kind(owner_id).has_codegen_attrs() {
413codegen_fn_attrs414 .target_features
415 .extend(tcx.codegen_fn_attrs(owner_id).target_features.iter().copied());
416 }
417 }
418419// Closures inherit `#[optimize]` annotations.
420if tcx.is_closure_like(did.to_def_id()) {
421let owner_id = tcx.parent(did.to_def_id());
422if tcx.def_kind(owner_id).has_codegen_attrs() {
423let owner_attrs = tcx.codegen_fn_attrs(owner_id);
424if codegen_fn_attrs.optimize == OptimizeAttr::Default {
425codegen_fn_attrs.optimize = owner_attrs.optimize;
426 }
427 }
428 }
429430// When `no_builtins` is applied at the crate level, we should add the
431 // `no-builtins` attribute to each function to ensure it takes effect in LTO.
432let no_builtins = {
'done:
{
for i in tcx.hir_krate_attrs() {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(NoBuiltins) => {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Tool { .. } |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}.is_some()find_attr!(tcx, crate, NoBuiltins);
433if no_builtins {
434codegen_fn_attrs.flags |= CodegenFnAttrFlags::NO_BUILTINS;
435 }
436437// inherit track-caller properly
438if tcx.should_inherit_track_caller(did) {
439codegen_fn_attrs.flags |= CodegenFnAttrFlags::TRACK_CALLER;
440 }
441442// Foreign items by default use no mangling for their symbol name.
443 // Usually, `symbol_name` is controlled by `#[link_name]`/`#[export_name]`. Here we additionally
444 // set `symbol_name` on most foreign items so that their their symbol name does not get mangled.
445if tcx.is_foreign_item(did) {
446codegen_fn_attrs.flags |= CodegenFnAttrFlags::FOREIGN_ITEM;
447448// There's a few exceptions to this rule though:
449if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) {
450// * `#[rustc_std_internal_symbol]` mangles the symbol name in a special way
451 // both for exports and imports through foreign items. This is handled further,
452 // during symbol mangling logic.
453} else if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM)
454 {
455// * externally implementable items keep their mangled symbol name.
456 // multiple EIIs can have the same name, so not mangling them would be a bug.
457 // Implementing an EII does the appropriate name resolution to make sure the implementations
458 // get the same symbol name as the *mangled* foreign item they refer to so that's all good.
459} else if codegen_fn_attrs.symbol_name.is_some() {
460// * If the name is already set by `#[link_name]`, we don't overwrite it.
461} else if codegen_fn_attrs.link_ordinal.is_some() {
462// * `#[link_ordinal]` and `#[link_name]` are incompatible with each other, so
463 // disable the implicit `#[link_name]` for foreign items below to avoid an
464 // error.
465} else {
466// This effectively adds an implicit `#[link_name = "<item name>"]`.
467 // NOTE: there's one more exception that we cannot apply here. On wasm,
468 // some items cannot be `no_mangle`.
469 // However, we don't have enough information here to determine that.
470 // As such, no_mangle foreign items on wasm that have the same defid as some
471 // import will *still* be mangled despite this.
472 //
473 // if none of the exceptions apply; do not mangle the symbol name
474codegen_fn_attrs.symbol_name = Some(tcx.item_name(did));
475 }
476 }
477}
478479#[derive(const _: () =
{
impl<'_sess> rustc_errors::Diagnostic<'_sess> for SanitizeOnInline {
#[track_caller]
fn into_diag(self, dcx: rustc_errors::DiagCtxtHandle<'_sess>,
level: rustc_errors::Level) -> rustc_errors::Diag<'_sess> {
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)]
480#[diag("non-default `sanitize` will have no effect after inlining")]
481struct SanitizeOnInline {
482#[note("inlining requested here")]
483inline_span: Span,
484}
485486#[derive(const _: () =
{
impl<'_sess> rustc_errors::Diagnostic<'_sess> for AsyncBlocking {
#[track_caller]
fn into_diag(self, dcx: rustc_errors::DiagCtxtHandle<'_sess>,
level: rustc_errors::Level) -> rustc_errors::Diag<'_sess> {
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)]
487#[diag("the async executor can run blocking code, without realtime sanitizer catching it")]
488struct AsyncBlocking;
489490fn check_result(
491 tcx: TyCtxt<'_>,
492 did: LocalDefId,
493 interesting_spans: InterestingAttributeDiagnosticSpans,
494 codegen_fn_attrs: &CodegenFnAttrs,
495) {
496// warn that inline has no effect when no_sanitize is present
497if codegen_fn_attrs.sanitizers != SanitizerFnAttrs::default()
498 && codegen_fn_attrs.inline.always()
499 && let (Some(sanitize_span), Some(inline_span)) =
500 (interesting_spans.sanitize, interesting_spans.inline)
501 {
502let hir_id = tcx.local_def_id_to_hir_id(did);
503tcx.emit_node_span_lint(
504INLINE_NO_SANITIZE,
505hir_id,
506sanitize_span,
507SanitizeOnInline { inline_span },
508 )
509 }
510511// warn for nonblocking async functions, blocks and closures.
512 // This doesn't behave as expected, because the executor can run blocking code without the sanitizer noticing.
513if codegen_fn_attrs.sanitizers.rtsan_setting == RtsanSetting::Nonblocking514 && let Some(sanitize_span) = interesting_spans.sanitize
515// async fn
516&& (tcx.asyncness(did).is_async()
517// async block
518|| tcx.is_coroutine(did.into())
519// async closure
520|| (tcx.is_closure_like(did.into())
521 && tcx.hir_node_by_def_id(did).expect_closure().kind
522 != rustc_hir::ClosureKind::Closure))
523 {
524let hir_id = tcx.local_def_id_to_hir_id(did);
525tcx.emit_node_span_lint(RTSAN_NONBLOCKING_ASYNC, hir_id, sanitize_span, AsyncBlocking);
526 }
527528// error when specifying link_name together with link_ordinal
529if let Some(_) = codegen_fn_attrs.symbol_name
530 && let Some(_) = codegen_fn_attrs.link_ordinal
531 {
532let msg = "cannot use `#[link_name]` with `#[link_ordinal]`";
533if let Some(span) = interesting_spans.link_ordinal {
534tcx.dcx().span_err(span, msg);
535 } else {
536tcx.dcx().err(msg);
537 }
538 }
539540if let Some(features) = check_tied_features(
541&tcx.sess.target,
542&codegen_fn_attrs543 .target_features
544 .iter()
545 .map(|features| (features.name.as_str(), true))
546 .collect(),
547 ) {
548let span = {
{
'done:
{
for i in ::rustc_attr_ir::HasAttrs::get_attrs(did, &tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(TargetFeature {
attr_span: span, .. }) => {
break 'done Some(*span);
}
::rustc_attr_ir::Attribute::Tool { .. } |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(tcx, did, TargetFeature{attr_span: span, ..} => *span)549 .unwrap_or_else(|| tcx.def_span(did));
550551tcx.dcx().emit_err(diagnostics::TargetFeatureDisableOrEnable {
552features,
553 span: Some(span),
554 missing_features: Some(diagnostics::MissingFeatures),
555 });
556 }
557}
558559fn handle_lang_items(
560 tcx: TyCtxt<'_>,
561 did: LocalDefId,
562 interesting_spans: &InterestingAttributeDiagnosticSpans,
563 attrs: &[Attribute],
564 codegen_fn_attrs: &mut CodegenFnAttrs,
565) {
566let lang_item = {
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(Lang(lang, _)) => {
break 'done Some(lang);
}
::rustc_attr_ir::Attribute::Tool { .. } |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}find_attr!(attrs, Lang(lang, _) => lang);
567568// Weak lang items have the same semantics as "std internal" symbols in the
569 // sense that they're preserved through all our LTO passes and only
570 // strippable by the linker.
571 //
572 // Additionally weak lang items have predetermined symbol names.
573let link_name_override = if let Some(lang_item) = lang_item574 && let Some(link_name) = lang_item.link_name()
575 {
576codegen_fn_attrs.flags |= CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL;
577Some(link_name)
578 } else {
579None580 };
581582// error when using no_mangle, or export_name on a lang item item
583if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL)
584 && codegen_fn_attrs.symbol_name.is_some()
585 {
586let mut err = tcx587 .dcx()
588 .struct_span_err(
589interesting_spans.no_mangle.unwrap_or_default(),
590"`#[no_mangle]` and `#[export_name]` cannot be used on internal language items",
591 )
592 .with_note("Rustc requires this item to have a specific mangled name.")
593 .with_span_label(tcx.def_span(did), "should be the internal language item");
594if let Some(lang_item) = lang_item595 && let Some(link_name) = lang_item.link_name()
596 {
597err = err598 .with_note("If you are trying to prevent mangling to ease debugging, many")
599 .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"))
600 .with_note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("match `.*{0}.*` instead of `break {0}` on a specific name",
link_name))
})format!(
601"match `.*{link_name}.*` instead of `break {link_name}` on a specific name"
602))
603 }
604err.emit();
605 }
606607if let Some(link_name_override) = link_name_override {
608codegen_fn_attrs.symbol_name = Some(link_name_override);
609 }
610}
611612/// Generate the [`CodegenFnAttrs`] for an item (identified by the [`LocalDefId`]).
613///
614/// This happens in 4 stages:
615/// - apply built-in attributes that directly translate to codegen attributes.
616/// - handle lang items. These have special codegen attrs applied to them.
617/// - apply overrides, like minimum requirements for alignment and other settings that don't rely directly the built-in attrs on the item.
618/// overrides come after applying built-in attributes since they may only apply when certain attributes were already set in the stage before.
619/// - check that the result is valid. There's various ways in which this may not be the case, such as certain combinations of attrs.
620fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
621if truecfg!(debug_assertions) {
622let def_kind = tcx.def_kind(did);
623if !def_kind.has_codegen_attrs() {
{
::core::panicking::panic_fmt(format_args!("unexpected `def_kind` in `codegen_fn_attrs`: {0:?}",
def_kind));
}
};assert!(
624 def_kind.has_codegen_attrs(),
625"unexpected `def_kind` in `codegen_fn_attrs`: {def_kind:?}",
626 );
627 }
628629let mut codegen_fn_attrs = CodegenFnAttrs::new();
630let attrs = tcx.hir_attrs(tcx.local_def_id_to_hir_id(did));
631632let interesting_spans = process_builtin_attrs(tcx, did, attrs, &mut codegen_fn_attrs);
633handle_lang_items(tcx, did, &interesting_spans, attrs, &mut codegen_fn_attrs);
634apply_overrides(tcx, did, &mut codegen_fn_attrs);
635check_result(tcx, did, interesting_spans, &codegen_fn_attrs);
636637codegen_fn_attrs638}
639640fn sanitizer_settings_for(tcx: TyCtxt<'_>, did: LocalDefId) -> SanitizerFnAttrs {
641// Backtrack to the crate root.
642let mut settings = match tcx.opt_local_parent(did) {
643// Check the parent (recursively).
644Some(parent) => tcx.sanitizer_settings_for(parent),
645// We reached the crate root without seeing an attribute, so
646 // there is no sanitizers to exclude.
647None => SanitizerFnAttrs::default(),
648 };
649650// Check for a sanitize annotation directly on this def.
651if let Some((on_set, off_set, rtsan)) =
652{
{
'done:
{
for i in ::rustc_attr_ir::HasAttrs::get_attrs(did, &tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(Sanitize {
on_set, off_set, rtsan, .. }) => {
break 'done Some((on_set, off_set, rtsan));
}
::rustc_attr_ir::Attribute::Tool { .. } |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(tcx, did, Sanitize {on_set, off_set, rtsan, ..} => (on_set, off_set, rtsan))653 {
654// the on set is the set of sanitizers explicitly enabled.
655 // we mask those out since we want the set of disabled sanitizers here
656settings.disabled &= !*on_set;
657// the off set is the set of sanitizers explicitly disabled.
658 // we or those in here.
659settings.disabled |= *off_set;
660// the on set and off set are distjoint since there's a third option: unset.
661 // a node may not set the sanitizer setting in which case it inherits from parents.
662 // the code above in this function does this backtracking
663664 // if rtsan was specified here override the parent
665if let Some(rtsan) = rtsan {
666settings.rtsan_setting = *rtsan;
667 }
668 }
669settings670}
671672/// Checks if the provided DefId is a method in a trait impl for a trait which has track_caller
673/// applied to the method prototype.
674fn should_inherit_track_caller(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
675tcx.trait_item_of(def_id).is_some_and(|id| {
676tcx.codegen_fn_attrs(id).flags.intersects(CodegenFnAttrFlags::TRACK_CALLER)
677 })
678}
679680/// If the provided DefId is a method in a trait impl, return the value of the `#[align]`
681/// attribute on the method prototype (if any).
682fn inherited_align<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> Option<Align> {
683tcx.codegen_fn_attrs(tcx.trait_item_of(def_id)?).alignment
684}
685686pub(crate) fn provide(providers: &mut Providers) {
687*providers = Providers {
688codegen_fn_attrs,
689should_inherit_track_caller,
690inherited_align,
691sanitizer_settings_for,
692 ..*providers693 };
694}