1 //! Set and unset common attributes on LLVM values.
6 use rustc_codegen_ssa::traits::*;
7 use rustc_data_structures::small_c_str::SmallCStr;
8 use rustc_hir::def_id::DefId;
9 use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
10 use rustc_middle::ty::layout::HasTyCtxt;
11 use rustc_middle::ty::{self, TyCtxt};
12 use rustc_session::config::OptLevel;
13 use rustc_session::Session;
14 use rustc_target::spec::abi::Abi;
15 use rustc_target::spec::{FramePointer, SanitizerSet, StackProbeType};
17 use crate::attributes;
18 use crate::llvm::AttributePlace::Function;
19 use crate::llvm::{self, Attribute};
21 pub use rustc_attr::{InlineAttr, InstructionSetAttr, OptimizeAttr};
23 use crate::context::CodegenCx;
24 use crate::value::Value;
26 /// Mark LLVM function to use provided inline heuristic.
28 fn inline(cx: &CodegenCx<'ll, '_>, val: &'ll Value, inline: InlineAttr) {
29 use self::InlineAttr::*;
31 Hint => Attribute::InlineHint.apply_llfn(Function, val),
32 Always => Attribute::AlwaysInline.apply_llfn(Function, val),
34 if cx.tcx().sess.target.arch != "amdgpu" {
35 Attribute::NoInline.apply_llfn(Function, val);
42 /// Apply LLVM sanitize attributes.
44 pub fn sanitize(cx: &CodegenCx<'ll, '_>, no_sanitize: SanitizerSet, llfn: &'ll Value) {
45 let enabled = cx.tcx.sess.opts.debugging_opts.sanitizer - no_sanitize;
46 if enabled.contains(SanitizerSet::ADDRESS) {
47 llvm::Attribute::SanitizeAddress.apply_llfn(Function, llfn);
49 if enabled.contains(SanitizerSet::MEMORY) {
50 llvm::Attribute::SanitizeMemory.apply_llfn(Function, llfn);
52 if enabled.contains(SanitizerSet::THREAD) {
53 llvm::Attribute::SanitizeThread.apply_llfn(Function, llfn);
55 if enabled.contains(SanitizerSet::HWADDRESS) {
56 llvm::Attribute::SanitizeHWAddress.apply_llfn(Function, llfn);
60 /// Tell LLVM to emit or not emit the information necessary to unwind the stack for the function.
62 pub fn emit_uwtable(val: &'ll Value, emit: bool) {
63 Attribute::UWTable.toggle_llfn(Function, val, emit);
66 /// Tell LLVM if this function should be 'naked', i.e., skip the epilogue and prologue.
68 fn naked(val: &'ll Value, is_naked: bool) {
69 Attribute::Naked.toggle_llfn(Function, val, is_naked);
72 pub fn set_frame_pointer_type(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
73 let mut fp = cx.sess().target.frame_pointer;
74 // "mcount" function relies on stack pointer.
75 // See <https://sourceware.org/binutils/docs/gprof/Implementation.html>.
76 if cx.sess().instrument_mcount() || matches!(cx.sess().opts.cg.force_frame_pointers, Some(true))
78 fp = FramePointer::Always;
80 let attr_value = match fp {
81 FramePointer::Always => cstr!("all"),
82 FramePointer::NonLeaf => cstr!("non-leaf"),
83 FramePointer::MayOmit => return,
85 llvm::AddFunctionAttrStringValue(
87 llvm::AttributePlace::Function,
88 cstr!("frame-pointer"),
93 /// Tell LLVM what instrument function to insert.
95 fn set_instrument_function(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
96 if cx.sess().instrument_mcount() {
97 // Similar to `clang -pg` behavior. Handled by the
98 // `post-inline-ee-instrument` LLVM pass.
100 // The function name varies on platforms.
101 // See test/CodeGen/mcount.c in clang.
102 let mcount_name = CString::new(cx.sess().target.mcount.as_str().as_bytes()).unwrap();
104 llvm::AddFunctionAttrStringValue(
106 llvm::AttributePlace::Function,
107 cstr!("instrument-function-entry-inlined"),
113 fn set_probestack(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
114 // Currently stack probes seem somewhat incompatible with the address
115 // sanitizer and thread sanitizer. With asan we're already protected from
116 // stack overflow anyway so we don't really need stack probes regardless.
122 .intersects(SanitizerSet::ADDRESS | SanitizerSet::THREAD)
127 // probestack doesn't play nice either with `-C profile-generate`.
128 if cx.sess().opts.cg.profile_generate.enabled() {
132 // probestack doesn't play nice either with gcov profiling.
133 if cx.sess().opts.debugging_opts.profile {
137 let attr_value = match cx.sess().target.stack_probes {
138 StackProbeType::None => None,
139 // Request LLVM to generate the probes inline. If the given LLVM version does not support
140 // this, no probe is generated at all (even if the attribute is specified).
141 StackProbeType::Inline => Some(cstr!("inline-asm")),
142 // Flag our internal `__rust_probestack` function as the stack probe symbol.
143 // This is defined in the `compiler-builtins` crate for each architecture.
144 StackProbeType::Call => Some(cstr!("__rust_probestack")),
145 // Pick from the two above based on the LLVM version.
146 StackProbeType::InlineOrCall { min_llvm_version_for_inline } => {
147 if llvm_util::get_version() < min_llvm_version_for_inline {
148 Some(cstr!("__rust_probestack"))
150 Some(cstr!("inline-asm"))
154 if let Some(attr_value) = attr_value {
155 llvm::AddFunctionAttrStringValue(
157 llvm::AttributePlace::Function,
158 cstr!("probe-stack"),
164 pub fn apply_target_cpu_attr(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
165 let target_cpu = SmallCStr::new(llvm_util::target_cpu(cx.tcx.sess));
166 llvm::AddFunctionAttrStringValue(
168 llvm::AttributePlace::Function,
170 target_cpu.as_c_str(),
174 pub fn apply_tune_cpu_attr(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
175 if let Some(tune) = llvm_util::tune_cpu(cx.tcx.sess) {
176 let tune_cpu = SmallCStr::new(tune);
177 llvm::AddFunctionAttrStringValue(
179 llvm::AttributePlace::Function,
186 /// Sets the `NonLazyBind` LLVM attribute on a given function,
187 /// assuming the codegen options allow skipping the PLT.
188 pub fn non_lazy_bind(sess: &Session, llfn: &'ll Value) {
189 // Don't generate calls through PLT if it's not necessary
190 if !sess.needs_plt() {
191 Attribute::NonLazyBind.apply_llfn(Function, llfn);
195 pub(crate) fn default_optimisation_attrs(sess: &Session, llfn: &'ll Value) {
196 match sess.opts.optimize {
198 llvm::Attribute::MinSize.unapply_llfn(Function, llfn);
199 llvm::Attribute::OptimizeForSize.apply_llfn(Function, llfn);
200 llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
202 OptLevel::SizeMin => {
203 llvm::Attribute::MinSize.apply_llfn(Function, llfn);
204 llvm::Attribute::OptimizeForSize.apply_llfn(Function, llfn);
205 llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
208 llvm::Attribute::MinSize.unapply_llfn(Function, llfn);
209 llvm::Attribute::OptimizeForSize.unapply_llfn(Function, llfn);
210 llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
216 /// Composite function which sets LLVM attributes for function depending on its AST (`#[attribute]`)
218 pub fn from_fn_attrs(cx: &CodegenCx<'ll, 'tcx>, llfn: &'ll Value, instance: ty::Instance<'tcx>) {
219 let codegen_fn_attrs = cx.tcx.codegen_fn_attrs(instance.def_id());
221 match codegen_fn_attrs.optimize {
222 OptimizeAttr::None => {
223 default_optimisation_attrs(cx.tcx.sess, llfn);
225 OptimizeAttr::Speed => {
226 llvm::Attribute::MinSize.unapply_llfn(Function, llfn);
227 llvm::Attribute::OptimizeForSize.unapply_llfn(Function, llfn);
228 llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
230 OptimizeAttr::Size => {
231 llvm::Attribute::MinSize.apply_llfn(Function, llfn);
232 llvm::Attribute::OptimizeForSize.apply_llfn(Function, llfn);
233 llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
237 let inline_attr = if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
239 } else if codegen_fn_attrs.inline == InlineAttr::None && instance.def.requires_inline(cx.tcx) {
242 codegen_fn_attrs.inline
244 inline(cx, llfn, inline_attr);
246 // The `uwtable` attribute according to LLVM is:
248 // This attribute indicates that the ABI being targeted requires that an
249 // unwind table entry be produced for this function even if we can show
250 // that no exceptions passes by it. This is normally the case for the
251 // ELF x86-64 abi, but it can be disabled for some compilation units.
253 // Typically when we're compiling with `-C panic=abort` (which implies this
254 // `no_landing_pads` check) we don't need `uwtable` because we can't
255 // generate any exceptions! On Windows, however, exceptions include other
256 // events such as illegal instructions, segfaults, etc. This means that on
257 // Windows we end up still needing the `uwtable` attribute even if the `-C
258 // panic=abort` flag is passed.
260 // You can also find more info on why Windows always requires uwtables here:
261 // https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
262 if cx.sess().must_emit_unwind_tables() {
263 attributes::emit_uwtable(llfn, true);
266 // FIXME: none of these three functions interact with source level attributes.
267 set_frame_pointer_type(cx, llfn);
268 set_instrument_function(cx, llfn);
269 set_probestack(cx, llfn);
271 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
272 Attribute::Cold.apply_llfn(Function, llfn);
274 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::FFI_RETURNS_TWICE) {
275 Attribute::ReturnsTwice.apply_llfn(Function, llfn);
277 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::FFI_PURE) {
278 Attribute::ReadOnly.apply_llfn(Function, llfn);
280 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::FFI_CONST) {
281 Attribute::ReadNone.apply_llfn(Function, llfn);
283 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
286 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::ALLOCATOR) {
287 Attribute::NoAlias.apply_llfn(llvm::AttributePlace::ReturnValue, llfn);
289 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::CMSE_NONSECURE_ENTRY) {
290 llvm::AddFunctionAttrString(llfn, Function, cstr!("cmse_nonsecure_entry"));
292 if let Some(align) = codegen_fn_attrs.alignment {
293 llvm::set_alignment(llfn, align as usize);
295 sanitize(cx, codegen_fn_attrs.no_sanitize, llfn);
297 // Always annotate functions with the target-cpu they are compiled for.
298 // Without this, ThinLTO won't inline Rust functions into Clang generated
299 // functions (because Clang annotates functions this way too).
300 apply_target_cpu_attr(cx, llfn);
301 // tune-cpu is only conveyed through the attribute for our purpose.
302 // The target doesn't care; the subtarget reads our attribute.
303 apply_tune_cpu_attr(cx, llfn);
305 let mut function_features = codegen_fn_attrs
309 let feature = &f.as_str();
310 llvm_util::to_llvm_feature(cx.tcx.sess, feature)
312 .map(|f| format!("+{}", f))
313 .collect::<Vec<String>>()
315 .chain(codegen_fn_attrs.instruction_set.iter().map(|x| match x {
316 InstructionSetAttr::ArmA32 => "-thumb-mode".to_string(),
317 InstructionSetAttr::ArmT32 => "+thumb-mode".to_string(),
319 .collect::<Vec<String>>();
321 if cx.tcx.sess.target.is_like_wasm {
322 // If this function is an import from the environment but the wasm
323 // import has a specific module/name, apply them here.
324 if let Some(module) = wasm_import_module(cx.tcx, instance.def_id()) {
325 llvm::AddFunctionAttrStringValue(
327 llvm::AttributePlace::Function,
328 cstr!("wasm-import-module"),
333 codegen_fn_attrs.link_name.unwrap_or_else(|| cx.tcx.item_name(instance.def_id()));
334 let name = CString::new(&name.as_str()[..]).unwrap();
335 llvm::AddFunctionAttrStringValue(
337 llvm::AttributePlace::Function,
338 cstr!("wasm-import-name"),
343 // The `"wasm"` abi on wasm targets automatically enables the
344 // `+multivalue` feature because the purpose of the wasm abi is to match
345 // the WebAssembly specification, which has this feature. This won't be
346 // needed when LLVM enables this `multivalue` feature by default.
347 if !cx.tcx.is_closure(instance.def_id()) {
348 let abi = cx.tcx.fn_sig(instance.def_id()).abi();
349 if abi == Abi::Wasm {
350 function_features.push("+multivalue".to_string());
355 if !function_features.is_empty() {
356 let mut global_features = llvm_util::llvm_global_features(cx.tcx.sess);
357 global_features.extend(function_features.into_iter());
358 let features = global_features.join(",");
359 let val = CString::new(features).unwrap();
360 llvm::AddFunctionAttrStringValue(
362 llvm::AttributePlace::Function,
363 cstr!("target-features"),
369 fn wasm_import_module(tcx: TyCtxt<'_>, id: DefId) -> Option<CString> {
370 tcx.wasm_import_module_map(id.krate).get(&id).map(|s| CString::new(&s[..]).unwrap())