1 //! Set and unset common attributes on LLVM values.
5 use rustc::hir::{CodegenFnAttrFlags, CodegenFnAttrs};
6 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
7 use rustc::session::Session;
8 use rustc::session::config::{Sanitizer, OptLevel};
9 use rustc::ty::{self, TyCtxt, PolyFnSig};
10 use rustc::ty::layout::HasTyCtxt;
11 use rustc::ty::query::Providers;
12 use rustc_data_structures::small_c_str::SmallCStr;
13 use rustc_data_structures::fx::FxHashMap;
14 use rustc_target::spec::PanicStrategy;
15 use rustc_codegen_ssa::traits::*;
18 use crate::attributes;
19 use crate::llvm::{self, Attribute};
20 use crate::llvm::AttributePlace::Function;
22 pub use syntax::attr::{self, InlineAttr, OptimizeAttr};
24 use crate::context::CodegenCx;
25 use crate::value::Value;
27 /// Mark LLVM function to use provided inline heuristic.
29 pub fn inline(cx: &CodegenCx<'ll, '_>, val: &'ll Value, inline: InlineAttr) {
30 use self::InlineAttr::*;
32 Hint => Attribute::InlineHint.apply_llfn(Function, val),
33 Always => Attribute::AlwaysInline.apply_llfn(Function, val),
35 if cx.tcx().sess.target.target.arch != "amdgpu" {
36 Attribute::NoInline.apply_llfn(Function, val);
40 Attribute::InlineHint.unapply_llfn(Function, val);
41 Attribute::AlwaysInline.unapply_llfn(Function, val);
42 Attribute::NoInline.unapply_llfn(Function, val);
47 /// Tell LLVM to emit or not emit the information necessary to unwind the stack for the function.
49 pub fn emit_uwtable(val: &'ll Value, emit: bool) {
50 Attribute::UWTable.toggle_llfn(Function, val, emit);
53 /// Tell LLVM whether the function can or cannot unwind.
55 fn unwind(val: &'ll Value, can_unwind: bool) {
56 Attribute::NoUnwind.toggle_llfn(Function, val, !can_unwind);
59 /// Tell LLVM if this function should be 'naked', i.e., skip the epilogue and prologue.
61 pub fn naked(val: &'ll Value, is_naked: bool) {
62 Attribute::Naked.toggle_llfn(Function, val, is_naked);
65 pub fn set_frame_pointer_elimination(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
66 if cx.sess().must_not_eliminate_frame_pointers() {
67 llvm::AddFunctionAttrStringValue(
68 llfn, llvm::AttributePlace::Function,
69 const_cstr!("no-frame-pointer-elim"), const_cstr!("true"));
73 /// Tell LLVM what instrument function to insert.
75 pub fn set_instrument_function(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
76 if cx.sess().instrument_mcount() {
77 // Similar to `clang -pg` behavior. Handled by the
78 // `post-inline-ee-instrument` LLVM pass.
80 // The function name varies on platforms.
81 // See test/CodeGen/mcount.c in clang.
82 let mcount_name = CString::new(
83 cx.sess().target.target.options.target_mcount.as_str().as_bytes()).unwrap();
85 llvm::AddFunctionAttrStringValue(
86 llfn, llvm::AttributePlace::Function,
87 const_cstr!("instrument-function-entry-inlined"), &mcount_name);
91 pub fn set_probestack(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
92 // Only use stack probes if the target specification indicates that we
93 // should be using stack probes
94 if !cx.sess().target.target.options.stack_probes {
98 // Currently stack probes seem somewhat incompatible with the address
99 // sanitizer. With asan we're already protected from stack overflow anyway
100 // so we don't really need stack probes regardless.
101 if let Some(Sanitizer::Address) = cx.sess().opts.debugging_opts.sanitizer {
105 // probestack doesn't play nice either with pgo-gen.
106 if cx.sess().opts.debugging_opts.pgo_gen.enabled() {
110 // probestack doesn't play nice either with gcov profiling.
111 if cx.sess().opts.debugging_opts.profile {
115 // Flag our internal `__rust_probestack` function as the stack probe symbol.
116 // This is defined in the `compiler-builtins` crate for each architecture.
117 llvm::AddFunctionAttrStringValue(
118 llfn, llvm::AttributePlace::Function,
119 const_cstr!("probe-stack"), const_cstr!("__rust_probestack"));
122 pub fn llvm_target_features(sess: &Session) -> impl Iterator<Item = &str> {
123 const RUSTC_SPECIFIC_FEATURES: &[&str] = &[
127 let cmdline = sess.opts.cg.target_feature.split(',')
128 .filter(|f| !RUSTC_SPECIFIC_FEATURES.iter().any(|s| f.contains(s)));
129 sess.target.target.options.features.split(',')
131 .filter(|l| !l.is_empty())
134 pub fn apply_target_cpu_attr(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
135 let target_cpu = SmallCStr::new(llvm_util::target_cpu(cx.tcx.sess));
136 llvm::AddFunctionAttrStringValue(
138 llvm::AttributePlace::Function,
139 const_cstr!("target-cpu"),
140 target_cpu.as_c_str());
143 /// Sets the `NonLazyBind` LLVM attribute on a given function,
144 /// assuming the codegen options allow skipping the PLT.
145 pub fn non_lazy_bind(sess: &Session, llfn: &'ll Value) {
146 // Don't generate calls through PLT if it's not necessary
147 if !sess.needs_plt() {
148 Attribute::NonLazyBind.apply_llfn(Function, llfn);
152 pub(crate) fn default_optimisation_attrs(sess: &Session, llfn: &'ll Value) {
153 match sess.opts.optimize {
155 llvm::Attribute::MinSize.unapply_llfn(Function, llfn);
156 llvm::Attribute::OptimizeForSize.apply_llfn(Function, llfn);
157 llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
159 OptLevel::SizeMin => {
160 llvm::Attribute::MinSize.apply_llfn(Function, llfn);
161 llvm::Attribute::OptimizeForSize.apply_llfn(Function, llfn);
162 llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
165 llvm::Attribute::MinSize.unapply_llfn(Function, llfn);
166 llvm::Attribute::OptimizeForSize.unapply_llfn(Function, llfn);
167 llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
174 /// Composite function which sets LLVM attributes for function depending on its AST (`#[attribute]`)
176 pub fn from_fn_attrs(
177 cx: &CodegenCx<'ll, 'tcx>,
180 sig: PolyFnSig<'tcx>,
182 let codegen_fn_attrs = id.map(|id| cx.tcx.codegen_fn_attrs(id))
183 .unwrap_or_else(|| CodegenFnAttrs::new());
185 match codegen_fn_attrs.optimize {
186 OptimizeAttr::None => {
187 default_optimisation_attrs(cx.tcx.sess, llfn);
189 OptimizeAttr::Speed => {
190 llvm::Attribute::MinSize.unapply_llfn(Function, llfn);
191 llvm::Attribute::OptimizeForSize.unapply_llfn(Function, llfn);
192 llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
194 OptimizeAttr::Size => {
195 llvm::Attribute::MinSize.apply_llfn(Function, llfn);
196 llvm::Attribute::OptimizeForSize.apply_llfn(Function, llfn);
197 llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
201 inline(cx, llfn, codegen_fn_attrs.inline);
203 // The `uwtable` attribute according to LLVM is:
205 // This attribute indicates that the ABI being targeted requires that an
206 // unwind table entry be produced for this function even if we can show
207 // that no exceptions passes by it. This is normally the case for the
208 // ELF x86-64 abi, but it can be disabled for some compilation units.
210 // Typically when we're compiling with `-C panic=abort` (which implies this
211 // `no_landing_pads` check) we don't need `uwtable` because we can't
212 // generate any exceptions! On Windows, however, exceptions include other
213 // events such as illegal instructions, segfaults, etc. This means that on
214 // Windows we end up still needing the `uwtable` attribute even if the `-C
215 // panic=abort` flag is passed.
217 // You can also find more info on why Windows is whitelisted here in:
218 // https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
219 if !cx.sess().no_landing_pads() ||
220 cx.sess().target.target.options.requires_uwtable {
221 attributes::emit_uwtable(llfn, true);
224 set_frame_pointer_elimination(cx, llfn);
225 set_instrument_function(cx, llfn);
226 set_probestack(cx, llfn);
228 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
229 Attribute::Cold.apply_llfn(Function, llfn);
231 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::FFI_RETURNS_TWICE) {
232 Attribute::ReturnsTwice.apply_llfn(Function, llfn);
234 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
237 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::ALLOCATOR) {
238 Attribute::NoAlias.apply_llfn(
239 llvm::AttributePlace::ReturnValue, llfn);
242 unwind(llfn, if cx.tcx.sess.panic_strategy() != PanicStrategy::Unwind {
243 // In panic=abort mode we assume nothing can unwind anywhere, so
244 // optimize based on this!
246 } else if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::UNWIND) {
247 // If a specific #[unwind] attribute is present, use that
249 } else if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_ALLOCATOR_NOUNWIND) {
250 // Special attribute for allocator functions, which can't unwind
252 } else if let Some(id) = id {
253 let sig = cx.tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
254 if cx.tcx.is_foreign_item(id) {
255 // Foreign items like `extern "C" { fn foo(); }` are assumed not to
258 } else if sig.abi != Abi::Rust && sig.abi != Abi::RustCall {
259 // Any items defined in Rust that *don't* have the `extern` ABI are
260 // defined to not unwind. We insert shims to abort if an unwind
261 // happens to enforce this.
264 // Anything else defined in Rust is assumed that it can possibly
269 // assume this can possibly unwind, avoiding the application of a
270 // `nounwind` attribute below.
274 // Always annotate functions with the target-cpu they are compiled for.
275 // Without this, ThinLTO won't inline Rust functions into Clang generated
276 // functions (because Clang annotates functions this way too).
277 apply_target_cpu_attr(cx, llfn);
279 let features = llvm_target_features(cx.tcx.sess)
280 .map(|s| s.to_string())
282 codegen_fn_attrs.target_features
285 let feature = &*f.as_str();
286 format!("+{}", llvm_util::to_llvm_feature(cx.tcx.sess, feature))
289 .collect::<Vec<String>>()
292 if !features.is_empty() {
293 let val = CString::new(features).unwrap();
294 llvm::AddFunctionAttrStringValue(
295 llfn, llvm::AttributePlace::Function,
296 const_cstr!("target-features"), &val);
299 // Note that currently the `wasm-import-module` doesn't do anything, but
300 // eventually LLVM 7 should read this and ferry the appropriate import
301 // module to the output file.
302 if let Some(id) = id {
303 if cx.tcx.sess.target.target.arch == "wasm32" {
304 if let Some(module) = wasm_import_module(cx.tcx, id) {
305 llvm::AddFunctionAttrStringValue(
307 llvm::AttributePlace::Function,
308 const_cstr!("wasm-import-module"),
316 pub fn provide(providers: &mut Providers<'_>) {
317 providers.target_features_whitelist = |tcx, cnum| {
318 assert_eq!(cnum, LOCAL_CRATE);
319 if tcx.sess.opts.actually_rustdoc {
320 // rustdoc needs to be able to document functions that use all the features, so
321 // whitelist them all
322 tcx.arena.alloc(llvm_util::all_known_features()
323 .map(|(a, b)| (a.to_string(), b))
326 tcx.arena.alloc(llvm_util::target_feature_whitelist(tcx.sess)
328 .map(|&(a, b)| (a.to_string(), b))
333 provide_extern(providers);
336 pub fn provide_extern(providers: &mut Providers<'_>) {
337 providers.wasm_import_module_map = |tcx, cnum| {
338 // Build up a map from DefId to a `NativeLibrary` structure, where
339 // `NativeLibrary` internally contains information about
340 // `#[link(wasm_import_module = "...")]` for example.
341 let native_libs = tcx.native_libraries(cnum);
343 let def_id_to_native_lib = native_libs.iter().filter_map(|lib|
344 if let Some(id) = lib.foreign_module {
349 ).collect::<FxHashMap<_, _>>();
351 let mut ret = FxHashMap::default();
352 for lib in tcx.foreign_modules(cnum).iter() {
353 let module = def_id_to_native_lib
355 .and_then(|s| s.wasm_import_module);
356 let module = match module {
360 ret.extend(lib.foreign_items.iter().map(|id| {
361 assert_eq!(id.krate, cnum);
362 (*id, module.to_string())
370 fn wasm_import_module(tcx: TyCtxt<'_, '_, '_>, id: DefId) -> Option<CString> {
371 tcx.wasm_import_module_map(id.krate)
373 .map(|s| CString::new(&s[..]).unwrap())