1 //! Set and unset common attributes on LLVM values.
5 use rustc::hir::CodegenFnAttrFlags;
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, Ty};
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::abi::call::Conv;
15 use rustc_target::spec::PanicStrategy;
16 use rustc_codegen_ssa::traits::*;
18 use crate::abi::FnAbi;
19 use crate::attributes;
20 use crate::llvm::{self, Attribute};
21 use crate::llvm::AttributePlace::Function;
23 pub use syntax::attr::{self, InlineAttr, OptimizeAttr};
25 use crate::context::CodegenCx;
26 use crate::value::Value;
28 /// Mark LLVM function to use provided inline heuristic.
30 fn inline(cx: &CodegenCx<'ll, '_>, val: &'ll Value, inline: InlineAttr) {
31 use self::InlineAttr::*;
33 Hint => Attribute::InlineHint.apply_llfn(Function, val),
34 Always => Attribute::AlwaysInline.apply_llfn(Function, val),
36 if cx.tcx().sess.target.target.arch != "amdgpu" {
37 Attribute::NoInline.apply_llfn(Function, val);
41 Attribute::InlineHint.unapply_llfn(Function, val);
42 Attribute::AlwaysInline.unapply_llfn(Function, val);
43 Attribute::NoInline.unapply_llfn(Function, val);
48 /// Tell LLVM to emit or not emit the information necessary to unwind the stack for the function.
50 pub fn emit_uwtable(val: &'ll Value, emit: bool) {
51 Attribute::UWTable.toggle_llfn(Function, val, emit);
54 /// Tell LLVM whether the function can or cannot unwind.
56 fn unwind(val: &'ll Value, can_unwind: bool) {
57 Attribute::NoUnwind.toggle_llfn(Function, val, !can_unwind);
60 /// Tell LLVM if this function should be 'naked', i.e., skip the epilogue and prologue.
62 fn naked(val: &'ll Value, is_naked: bool) {
63 Attribute::Naked.toggle_llfn(Function, val, is_naked);
66 pub fn set_frame_pointer_elimination(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
67 if cx.sess().must_not_eliminate_frame_pointers() {
68 llvm::AddFunctionAttrStringValue(
69 llfn, llvm::AttributePlace::Function,
70 const_cstr!("no-frame-pointer-elim"), const_cstr!("true"));
74 /// Tell LLVM what instrument function to insert.
76 fn set_instrument_function(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
77 if cx.sess().instrument_mcount() {
78 // Similar to `clang -pg` behavior. Handled by the
79 // `post-inline-ee-instrument` LLVM pass.
81 // The function name varies on platforms.
82 // See test/CodeGen/mcount.c in clang.
83 let mcount_name = CString::new(
84 cx.sess().target.target.options.target_mcount.as_str().as_bytes()).unwrap();
86 llvm::AddFunctionAttrStringValue(
87 llfn, llvm::AttributePlace::Function,
88 const_cstr!("instrument-function-entry-inlined"), &mcount_name);
92 fn set_probestack(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
93 // Only use stack probes if the target specification indicates that we
94 // should be using stack probes
95 if !cx.sess().target.target.options.stack_probes {
99 // Currently stack probes seem somewhat incompatible with the address
100 // sanitizer and thread sanitizer. With asan we're already protected from
101 // stack overflow anyway so we don't really need stack probes regardless.
102 match cx.sess().opts.debugging_opts.sanitizer {
103 Some(Sanitizer::Address) |
104 Some(Sanitizer::Thread) => return,
108 // probestack doesn't play nice either with `-C profile-generate`.
109 if cx.sess().opts.cg.profile_generate.enabled() {
113 // probestack doesn't play nice either with gcov profiling.
114 if cx.sess().opts.debugging_opts.profile {
118 // Flag our internal `__rust_probestack` function as the stack probe symbol.
119 // This is defined in the `compiler-builtins` crate for each architecture.
120 llvm::AddFunctionAttrStringValue(
121 llfn, llvm::AttributePlace::Function,
122 const_cstr!("probe-stack"), const_cstr!("__rust_probestack"));
125 fn translate_obsolete_target_features(feature: &str) -> &str {
126 const LLVM9_FEATURE_CHANGES: &[(&str, &str)] = &[
127 ("+fp-only-sp", "-fp64"),
128 ("-fp-only-sp", "+fp64"),
132 if llvm_util::get_major_version() >= 9 {
133 for &(old, new) in LLVM9_FEATURE_CHANGES {
139 for &(old, new) in LLVM9_FEATURE_CHANGES {
148 pub fn llvm_target_features(sess: &Session) -> impl Iterator<Item = &str> {
149 const RUSTC_SPECIFIC_FEATURES: &[&str] = &[
153 let cmdline = sess.opts.cg.target_feature.split(',')
154 .filter(|f| !RUSTC_SPECIFIC_FEATURES.iter().any(|s| f.contains(s)));
155 sess.target.target.options.features.split(',')
157 .filter(|l| !l.is_empty())
158 .map(translate_obsolete_target_features)
161 pub fn apply_target_cpu_attr(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
162 let target_cpu = SmallCStr::new(llvm_util::target_cpu(cx.tcx.sess));
163 llvm::AddFunctionAttrStringValue(
165 llvm::AttributePlace::Function,
166 const_cstr!("target-cpu"),
167 target_cpu.as_c_str());
170 /// Sets the `NonLazyBind` LLVM attribute on a given function,
171 /// assuming the codegen options allow skipping the PLT.
172 pub fn non_lazy_bind(sess: &Session, llfn: &'ll Value) {
173 // Don't generate calls through PLT if it's not necessary
174 if !sess.needs_plt() {
175 Attribute::NonLazyBind.apply_llfn(Function, llfn);
179 pub(crate) fn default_optimisation_attrs(sess: &Session, llfn: &'ll Value) {
180 match sess.opts.optimize {
182 llvm::Attribute::MinSize.unapply_llfn(Function, llfn);
183 llvm::Attribute::OptimizeForSize.apply_llfn(Function, llfn);
184 llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
186 OptLevel::SizeMin => {
187 llvm::Attribute::MinSize.apply_llfn(Function, llfn);
188 llvm::Attribute::OptimizeForSize.apply_llfn(Function, llfn);
189 llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
192 llvm::Attribute::MinSize.unapply_llfn(Function, llfn);
193 llvm::Attribute::OptimizeForSize.unapply_llfn(Function, llfn);
194 llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
201 /// Composite function which sets LLVM attributes for function depending on its AST (`#[attribute]`)
203 pub fn from_fn_attrs(
204 cx: &CodegenCx<'ll, 'tcx>,
206 instance: ty::Instance<'tcx>,
207 fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
209 let codegen_fn_attrs = cx.tcx.codegen_fn_attrs(instance.def_id());
211 match codegen_fn_attrs.optimize {
212 OptimizeAttr::None => {
213 default_optimisation_attrs(cx.tcx.sess, llfn);
215 OptimizeAttr::Speed => {
216 llvm::Attribute::MinSize.unapply_llfn(Function, llfn);
217 llvm::Attribute::OptimizeForSize.unapply_llfn(Function, llfn);
218 llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
220 OptimizeAttr::Size => {
221 llvm::Attribute::MinSize.apply_llfn(Function, llfn);
222 llvm::Attribute::OptimizeForSize.apply_llfn(Function, llfn);
223 llvm::Attribute::OptimizeNone.unapply_llfn(Function, llfn);
227 // FIXME(eddyb) consolidate these two `inline` calls (and avoid overwrites).
228 if instance.def.is_inline(cx.tcx) {
229 inline(cx, llfn, attributes::InlineAttr::Hint);
232 inline(cx, llfn, codegen_fn_attrs.inline);
234 // The `uwtable` attribute according to LLVM is:
236 // This attribute indicates that the ABI being targeted requires that an
237 // unwind table entry be produced for this function even if we can show
238 // that no exceptions passes by it. This is normally the case for the
239 // ELF x86-64 abi, but it can be disabled for some compilation units.
241 // Typically when we're compiling with `-C panic=abort` (which implies this
242 // `no_landing_pads` check) we don't need `uwtable` because we can't
243 // generate any exceptions! On Windows, however, exceptions include other
244 // events such as illegal instructions, segfaults, etc. This means that on
245 // Windows we end up still needing the `uwtable` attribute even if the `-C
246 // panic=abort` flag is passed.
248 // You can also find more info on why Windows is whitelisted here in:
249 // https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
250 if !cx.sess().no_landing_pads() ||
251 cx.sess().target.target.options.requires_uwtable {
252 attributes::emit_uwtable(llfn, true);
255 set_frame_pointer_elimination(cx, llfn);
256 set_instrument_function(cx, llfn);
257 set_probestack(cx, llfn);
259 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
260 Attribute::Cold.apply_llfn(Function, llfn);
262 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::FFI_RETURNS_TWICE) {
263 Attribute::ReturnsTwice.apply_llfn(Function, llfn);
265 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
268 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::ALLOCATOR) {
269 Attribute::NoAlias.apply_llfn(
270 llvm::AttributePlace::ReturnValue, llfn);
273 unwind(llfn, if cx.tcx.sess.panic_strategy() != PanicStrategy::Unwind {
274 // In panic=abort mode we assume nothing can unwind anywhere, so
275 // optimize based on this!
277 } else if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::UNWIND) {
278 // If a specific #[unwind] attribute is present, use that.
280 } else if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_ALLOCATOR_NOUNWIND) {
281 // Special attribute for allocator functions, which can't unwind.
284 if fn_abi.conv == Conv::Rust {
285 // Any Rust method (or `extern "Rust" fn` or `extern
286 // "rust-call" fn`) is explicitly allowed to unwind
287 // (unless it has no-unwind attribute, handled above).
290 // Anything else is either:
292 // 1. A foreign item using a non-Rust ABI (like `extern "C" { fn foo(); }`), or
294 // 2. A Rust item using a non-Rust ABI (like `extern "C" fn foo() { ... }`).
296 // Foreign items (case 1) are assumed to not unwind; it is
297 // UB otherwise. (At least for now; see also
298 // rust-lang/rust#63909 and Rust RFC 2753.)
300 // Items defined in Rust with non-Rust ABIs (case 2) are also
301 // not supposed to unwind. Whether this should be enforced
302 // (versus stating it is UB) and *how* it would be enforced
303 // is currently under discussion; see rust-lang/rust#58794.
305 // In either case, we mark item as explicitly nounwind.
310 // Always annotate functions with the target-cpu they are compiled for.
311 // Without this, ThinLTO won't inline Rust functions into Clang generated
312 // functions (because Clang annotates functions this way too).
313 apply_target_cpu_attr(cx, llfn);
315 let features = llvm_target_features(cx.tcx.sess)
316 .map(|s| s.to_string())
318 codegen_fn_attrs.target_features
321 let feature = &f.as_str();
322 format!("+{}", llvm_util::to_llvm_feature(cx.tcx.sess, feature))
325 .collect::<Vec<String>>()
328 if !features.is_empty() {
329 let val = CString::new(features).unwrap();
330 llvm::AddFunctionAttrStringValue(
331 llfn, llvm::AttributePlace::Function,
332 const_cstr!("target-features"), &val);
335 // Note that currently the `wasm-import-module` doesn't do anything, but
336 // eventually LLVM 7 should read this and ferry the appropriate import
337 // module to the output file.
338 if cx.tcx.sess.target.target.arch == "wasm32" {
339 if let Some(module) = wasm_import_module(cx.tcx, instance.def_id()) {
340 llvm::AddFunctionAttrStringValue(
342 llvm::AttributePlace::Function,
343 const_cstr!("wasm-import-module"),
347 let name = codegen_fn_attrs.link_name.unwrap_or_else(|| {
348 cx.tcx.item_name(instance.def_id())
350 let name = CString::new(&name.as_str()[..]).unwrap();
351 llvm::AddFunctionAttrStringValue(
353 llvm::AttributePlace::Function,
354 const_cstr!("wasm-import-name"),
361 pub fn provide(providers: &mut Providers<'_>) {
362 providers.target_features_whitelist = |tcx, cnum| {
363 assert_eq!(cnum, LOCAL_CRATE);
364 if tcx.sess.opts.actually_rustdoc {
365 // rustdoc needs to be able to document functions that use all the features, so
366 // whitelist them all
367 tcx.arena.alloc(llvm_util::all_known_features()
368 .map(|(a, b)| (a.to_string(), b))
371 tcx.arena.alloc(llvm_util::target_feature_whitelist(tcx.sess)
373 .map(|&(a, b)| (a.to_string(), b))
378 provide_extern(providers);
381 pub fn provide_extern(providers: &mut Providers<'_>) {
382 providers.wasm_import_module_map = |tcx, cnum| {
383 // Build up a map from DefId to a `NativeLibrary` structure, where
384 // `NativeLibrary` internally contains information about
385 // `#[link(wasm_import_module = "...")]` for example.
386 let native_libs = tcx.native_libraries(cnum);
388 let def_id_to_native_lib = native_libs.iter().filter_map(|lib|
389 lib.foreign_module.map(|id| (id, lib))
390 ).collect::<FxHashMap<_, _>>();
392 let mut ret = FxHashMap::default();
393 for lib in tcx.foreign_modules(cnum).iter() {
394 let module = def_id_to_native_lib
396 .and_then(|s| s.wasm_import_module);
397 let module = match module {
401 ret.extend(lib.foreign_items.iter().map(|id| {
402 assert_eq!(id.krate, cnum);
403 (*id, module.to_string())
411 fn wasm_import_module(tcx: TyCtxt<'_>, id: DefId) -> Option<CString> {
412 tcx.wasm_import_module_map(id.krate)
414 .map(|s| CString::new(&s[..]).unwrap())