rustc_middle/middle/
codegen_fn_attrs.rs

1use std::borrow::Cow;
2
3use rustc_abi::Align;
4use rustc_hir::attrs::{InlineAttr, InstructionSetAttr, Linkage, OptimizeAttr};
5use rustc_hir::def_id::DefId;
6use rustc_macros::{HashStable, TyDecodable, TyEncodable};
7use rustc_span::Symbol;
8use rustc_target::spec::SanitizerSet;
9
10use crate::ty::{InstanceKind, TyCtxt};
11
12impl<'tcx> TyCtxt<'tcx> {
13    pub fn codegen_instance_attrs(
14        self,
15        instance_kind: InstanceKind<'_>,
16    ) -> Cow<'tcx, CodegenFnAttrs> {
17        let mut attrs = Cow::Borrowed(self.codegen_fn_attrs(instance_kind.def_id()));
18
19        // Drop the `#[naked]` attribute on non-item `InstanceKind`s, like the shims that
20        // are generated for indirect function calls.
21        if !matches!(instance_kind, InstanceKind::Item(_)) {
22            if attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
23                attrs.to_mut().flags.remove(CodegenFnAttrFlags::NAKED);
24            }
25        }
26
27        attrs
28    }
29}
30
31#[derive(Clone, TyEncodable, TyDecodable, HashStable, Debug)]
32pub struct CodegenFnAttrs {
33    pub flags: CodegenFnAttrFlags,
34    /// Parsed representation of the `#[inline]` attribute
35    pub inline: InlineAttr,
36    /// Parsed representation of the `#[optimize]` attribute
37    pub optimize: OptimizeAttr,
38    /// The `#[export_name = "..."]` attribute, indicating a custom symbol a
39    /// function should be exported under
40    pub export_name: Option<Symbol>,
41    /// The `#[link_name = "..."]` attribute, indicating a custom symbol an
42    /// imported function should be imported as. Note that `export_name`
43    /// probably isn't set when this is set, this is for foreign items while
44    /// `#[export_name]` is for Rust-defined functions.
45    pub link_name: Option<Symbol>,
46    /// The `#[link_ordinal = "..."]` attribute, indicating an ordinal an
47    /// imported function has in the dynamic library. Note that this must not
48    /// be set when `link_name` is set. This is for foreign items with the
49    /// "raw-dylib" kind.
50    pub link_ordinal: Option<u16>,
51    /// The `#[target_feature(enable = "...")]` attribute and the enabled
52    /// features (only enabled features are supported right now).
53    /// Implied target features have already been applied.
54    pub target_features: Vec<TargetFeature>,
55    /// Whether the function was declared safe, but has target features
56    pub safe_target_features: bool,
57    /// The `#[linkage = "..."]` attribute on Rust-defined items and the value we found.
58    pub linkage: Option<Linkage>,
59    /// The `#[linkage = "..."]` attribute on foreign items and the value we found.
60    pub import_linkage: Option<Linkage>,
61    /// The `#[link_section = "..."]` attribute, or what executable section this
62    /// should be placed in.
63    pub link_section: Option<Symbol>,
64    /// The `#[no_sanitize(...)]` attribute. Indicates sanitizers for which
65    /// instrumentation should be disabled inside the annotated function.
66    pub no_sanitize: SanitizerSet,
67    /// The `#[instruction_set(set)]` attribute. Indicates if the generated code should
68    /// be generated against a specific instruction set. Only usable on architectures which allow
69    /// switching between multiple instruction sets.
70    pub instruction_set: Option<InstructionSetAttr>,
71    /// The `#[align(...)]` attribute. Determines the alignment of the function body.
72    // FIXME(#82232, #143834): temporarily renamed to mitigate `#[align]` nameres ambiguity
73    pub alignment: Option<Align>,
74    /// The `#[patchable_function_entry(...)]` attribute. Indicates how many nops should be around
75    /// the function entry.
76    pub patchable_function_entry: Option<PatchableFunctionEntry>,
77}
78
79#[derive(Copy, Clone, Debug, TyEncodable, TyDecodable, HashStable)]
80pub struct TargetFeature {
81    /// The name of the target feature (e.g. "avx")
82    pub name: Symbol,
83    /// The feature is implied by another feature, rather than explicitly added by the
84    /// `#[target_feature]` attribute
85    pub implied: bool,
86}
87
88#[derive(Copy, Clone, Debug, TyEncodable, TyDecodable, HashStable)]
89pub struct PatchableFunctionEntry {
90    /// Nops to prepend to the function
91    prefix: u8,
92    /// Nops after entry, but before body
93    entry: u8,
94}
95
96impl PatchableFunctionEntry {
97    pub fn from_config(config: rustc_session::config::PatchableFunctionEntry) -> Self {
98        Self { prefix: config.prefix(), entry: config.entry() }
99    }
100    pub fn from_prefix_and_entry(prefix: u8, entry: u8) -> Self {
101        Self { prefix, entry }
102    }
103    pub fn prefix(&self) -> u8 {
104        self.prefix
105    }
106    pub fn entry(&self) -> u8 {
107        self.entry
108    }
109}
110
111#[derive(Clone, Copy, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
112pub struct CodegenFnAttrFlags(u32);
113bitflags::bitflags! {
114    impl CodegenFnAttrFlags: u32 {
115        /// `#[cold]`: a hint to LLVM that this function, when called, is never on
116        /// the hot path.
117        const COLD                      = 1 << 0;
118        /// `#[rustc_nounwind]`: An indicator that function will never unwind.
119        const NEVER_UNWIND              = 1 << 1;
120        /// `#[naked]`: an indicator to LLVM that no function prologue/epilogue
121        /// should be generated.
122        const NAKED                     = 1 << 2;
123        /// `#[no_mangle]`: an indicator that the function's name should be the same
124        /// as its symbol.
125        const NO_MANGLE                 = 1 << 3;
126        /// `#[rustc_std_internal_symbol]`: an indicator that this symbol is a
127        /// "weird symbol" for the standard library in that it has slightly
128        /// different linkage, visibility, and reachability rules.
129        const RUSTC_STD_INTERNAL_SYMBOL = 1 << 4;
130        /// `#[thread_local]`: indicates a static is actually a thread local
131        /// piece of memory
132        const THREAD_LOCAL              = 1 << 5;
133        /// `#[used(compiler)]`: indicates that LLVM can't eliminate this function (but the
134        /// linker can!).
135        const USED_COMPILER             = 1 << 6;
136        /// `#[used(linker)]`:
137        /// indicates that neither LLVM nor the linker will eliminate this function.
138        const USED_LINKER               = 1 << 7;
139        /// `#[track_caller]`: allow access to the caller location
140        const TRACK_CALLER              = 1 << 8;
141        /// #[ffi_pure]: applies clang's `pure` attribute to a foreign function
142        /// declaration.
143        const FFI_PURE                  = 1 << 9;
144        /// #[ffi_const]: applies clang's `const` attribute to a foreign function
145        /// declaration.
146        const FFI_CONST                 = 1 << 10;
147        /// `#[rustc_allocator]`: a hint to LLVM that the pointer returned from this
148        /// function is never null and the function has no side effects other than allocating.
149        const ALLOCATOR                 = 1 << 11;
150        /// `#[rustc_deallocator]`: a hint to LLVM that the function only deallocates memory.
151        const DEALLOCATOR               = 1 << 12;
152        /// `#[rustc_reallocator]`: a hint to LLVM that the function only reallocates memory.
153        const REALLOCATOR               = 1 << 13;
154        /// `#[rustc_allocator_zeroed]`: a hint to LLVM that the function only allocates zeroed memory.
155        const ALLOCATOR_ZEROED          = 1 << 14;
156        /// `#[no_builtins]`: indicates that disable implicit builtin knowledge of functions for the function.
157        const NO_BUILTINS               = 1 << 15;
158    }
159}
160rustc_data_structures::external_bitflags_debug! { CodegenFnAttrFlags }
161
162impl CodegenFnAttrs {
163    pub const EMPTY: &'static Self = &Self::new();
164
165    pub const fn new() -> CodegenFnAttrs {
166        CodegenFnAttrs {
167            flags: CodegenFnAttrFlags::empty(),
168            inline: InlineAttr::None,
169            optimize: OptimizeAttr::Default,
170            export_name: None,
171            link_name: None,
172            link_ordinal: None,
173            target_features: vec![],
174            safe_target_features: false,
175            linkage: None,
176            import_linkage: None,
177            link_section: None,
178            no_sanitize: SanitizerSet::empty(),
179            instruction_set: None,
180            alignment: None,
181            patchable_function_entry: None,
182        }
183    }
184
185    /// Returns `true` if it looks like this symbol needs to be exported, for example:
186    ///
187    /// * `#[no_mangle]` is present
188    /// * `#[export_name(...)]` is present
189    /// * `#[linkage]` is present
190    ///
191    /// Keep this in sync with the logic for the unused_attributes for `#[inline]` lint.
192    pub fn contains_extern_indicator(&self, tcx: TyCtxt<'_>, did: DefId) -> bool {
193        if tcx.is_foreign_item(did) {
194            return false;
195        }
196
197        self.flags.contains(CodegenFnAttrFlags::NO_MANGLE)
198            || self.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL)
199            || self.export_name.is_some()
200            || match self.linkage {
201                // These are private, so make sure we don't try to consider
202                // them external.
203                None | Some(Linkage::Internal) => false,
204                Some(_) => true,
205            }
206    }
207}