1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10 //! Set and unset common attributes on LLVM values.
12 use std::ffi::CString;
14 use rustc::hir::{CodegenFnAttrFlags, CodegenFnAttrs};
15 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
16 use rustc::session::Session;
17 use rustc::session::config::Sanitizer;
18 use rustc::ty::{self, TyCtxt, PolyFnSig};
19 use rustc::ty::layout::HasTyCtxt;
20 use rustc::ty::query::Providers;
21 use rustc_data_structures::sync::Lrc;
22 use rustc_data_structures::fx::FxHashMap;
23 use rustc_target::spec::PanicStrategy;
24 use rustc_codegen_ssa::traits::*;
28 use llvm::{self, Attribute};
29 use llvm::AttributePlace::Function;
31 pub use syntax::attr::{self, InlineAttr};
33 use context::CodegenCx;
36 /// Mark LLVM function to use provided inline heuristic.
38 pub fn inline(cx: &CodegenCx<'ll, '_>, val: &'ll Value, inline: InlineAttr) {
39 use self::InlineAttr::*;
41 Hint => Attribute::InlineHint.apply_llfn(Function, val),
42 Always => Attribute::AlwaysInline.apply_llfn(Function, val),
44 if cx.tcx().sess.target.target.arch != "amdgpu" {
45 Attribute::NoInline.apply_llfn(Function, val);
49 Attribute::InlineHint.unapply_llfn(Function, val);
50 Attribute::AlwaysInline.unapply_llfn(Function, val);
51 Attribute::NoInline.unapply_llfn(Function, val);
56 /// Tell LLVM to emit or not emit the information necessary to unwind the stack for the function.
58 pub fn emit_uwtable(val: &'ll Value, emit: bool) {
59 Attribute::UWTable.toggle_llfn(Function, val, emit);
62 /// Tell LLVM whether the function can or cannot unwind.
64 fn unwind(val: &'ll Value, can_unwind: bool) {
65 Attribute::NoUnwind.toggle_llfn(Function, val, !can_unwind);
68 /// Tell LLVM whether it should optimize function for size.
70 #[allow(dead_code)] // possibly useful function
71 pub fn set_optimize_for_size(val: &'ll Value, optimize: bool) {
72 Attribute::OptimizeForSize.toggle_llfn(Function, val, optimize);
75 /// Tell LLVM if this function should be 'naked', i.e., skip the epilogue and prologue.
77 pub fn naked(val: &'ll Value, is_naked: bool) {
78 Attribute::Naked.toggle_llfn(Function, val, is_naked);
81 pub fn set_frame_pointer_elimination(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
82 if cx.sess().must_not_eliminate_frame_pointers() {
83 llvm::AddFunctionAttrStringValue(
84 llfn, llvm::AttributePlace::Function,
85 const_cstr!("no-frame-pointer-elim"), const_cstr!("true"));
89 pub fn set_probestack(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
90 // Only use stack probes if the target specification indicates that we
91 // should be using stack probes
92 if !cx.sess().target.target.options.stack_probes {
96 // Currently stack probes seem somewhat incompatible with the address
97 // sanitizer. With asan we're already protected from stack overflow anyway
98 // so we don't really need stack probes regardless.
99 if let Some(Sanitizer::Address) = cx.sess().opts.debugging_opts.sanitizer {
103 // probestack doesn't play nice either with pgo-gen.
104 if cx.sess().opts.debugging_opts.pgo_gen.is_some() {
108 // probestack doesn't play nice either with gcov profiling.
109 if cx.sess().opts.debugging_opts.profile {
113 // Flag our internal `__rust_probestack` function as the stack probe symbol.
114 // This is defined in the `compiler-builtins` crate for each architecture.
115 llvm::AddFunctionAttrStringValue(
116 llfn, llvm::AttributePlace::Function,
117 const_cstr!("probe-stack"), const_cstr!("__rust_probestack"));
120 pub fn llvm_target_features(sess: &Session) -> impl Iterator<Item = &str> {
121 const RUSTC_SPECIFIC_FEATURES: &[&str] = &[
125 let cmdline = sess.opts.cg.target_feature.split(',')
126 .filter(|f| !RUSTC_SPECIFIC_FEATURES.iter().any(|s| f.contains(s)));
127 sess.target.target.options.features.split(',')
129 .filter(|l| !l.is_empty())
132 pub fn apply_target_cpu_attr(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
133 let cpu = llvm_util::target_cpu(cx.tcx.sess);
134 let target_cpu = CString::new(cpu).unwrap();
135 llvm::AddFunctionAttrStringValue(
137 llvm::AttributePlace::Function,
138 const_cstr!("target-cpu"),
139 target_cpu.as_c_str());
142 /// Sets the `NonLazyBind` LLVM attribute on a given function,
143 /// assuming the codegen options allow skipping the PLT.
144 pub fn non_lazy_bind(sess: &Session, llfn: &'ll Value) {
145 // Don't generate calls through PLT if it's not necessary
146 if !sess.needs_plt() {
147 Attribute::NonLazyBind.apply_llfn(Function, llfn);
151 /// Composite function which sets LLVM attributes for function depending on its AST (`#[attribute]`)
153 pub fn from_fn_attrs(
154 cx: &CodegenCx<'ll, 'tcx>,
157 sig: PolyFnSig<'tcx>,
159 let codegen_fn_attrs = id.map(|id| cx.tcx.codegen_fn_attrs(id))
160 .unwrap_or_else(|| CodegenFnAttrs::new());
162 inline(cx, llfn, codegen_fn_attrs.inline);
164 // The `uwtable` attribute according to LLVM is:
166 // This attribute indicates that the ABI being targeted requires that an
167 // unwind table entry be produced for this function even if we can show
168 // that no exceptions passes by it. This is normally the case for the
169 // ELF x86-64 abi, but it can be disabled for some compilation units.
171 // Typically when we're compiling with `-C panic=abort` (which implies this
172 // `no_landing_pads` check) we don't need `uwtable` because we can't
173 // generate any exceptions! On Windows, however, exceptions include other
174 // events such as illegal instructions, segfaults, etc. This means that on
175 // Windows we end up still needing the `uwtable` attribute even if the `-C
176 // panic=abort` flag is passed.
178 // You can also find more info on why Windows is whitelisted here in:
179 // https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
180 if !cx.sess().no_landing_pads() ||
181 cx.sess().target.target.options.requires_uwtable {
182 attributes::emit_uwtable(llfn, true);
185 set_frame_pointer_elimination(cx, llfn);
186 set_probestack(cx, llfn);
188 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
189 Attribute::Cold.apply_llfn(Function, llfn);
191 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
194 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::ALLOCATOR) {
195 Attribute::NoAlias.apply_llfn(
196 llvm::AttributePlace::ReturnValue, llfn);
199 unwind(llfn, if cx.tcx.sess.panic_strategy() != PanicStrategy::Unwind {
200 // In panic=abort mode we assume nothing can unwind anywhere, so
201 // optimize based on this!
203 } else if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::UNWIND) {
204 // If a specific #[unwind] attribute is present, use that
206 } else if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_ALLOCATOR_NOUNWIND) {
207 // Special attribute for allocator functions, which can't unwind
209 } else if let Some(id) = id {
210 let sig = cx.tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
211 if cx.tcx.is_foreign_item(id) {
212 // Foreign items like `extern "C" { fn foo(); }` are assumed not to
215 } else if sig.abi != Abi::Rust && sig.abi != Abi::RustCall {
216 // Any items defined in Rust that *don't* have the `extern` ABI are
217 // defined to not unwind. We insert shims to abort if an unwind
218 // happens to enforce this.
221 // Anything else defined in Rust is assumed that it can possibly
226 // assume this can possibly unwind, avoiding the application of a
227 // `nounwind` attribute below.
231 // Always annotate functions with the target-cpu they are compiled for.
232 // Without this, ThinLTO won't inline Rust functions into Clang generated
233 // functions (because Clang annotates functions this way too).
234 // NOTE: For now we just apply this if -Zcross-lang-lto is specified, since
235 // it introduce a little overhead and isn't really necessary otherwise.
236 if cx.tcx.sess.opts.debugging_opts.cross_lang_lto.enabled() {
237 apply_target_cpu_attr(cx, llfn);
240 let features = llvm_target_features(cx.tcx.sess)
241 .map(|s| s.to_string())
243 codegen_fn_attrs.target_features
246 let feature = &*f.as_str();
247 format!("+{}", llvm_util::to_llvm_feature(cx.tcx.sess, feature))
250 .collect::<Vec<String>>()
253 if !features.is_empty() {
254 let val = CString::new(features).unwrap();
255 llvm::AddFunctionAttrStringValue(
256 llfn, llvm::AttributePlace::Function,
257 const_cstr!("target-features"), &val);
260 // Note that currently the `wasm-import-module` doesn't do anything, but
261 // eventually LLVM 7 should read this and ferry the appropriate import
262 // module to the output file.
263 if let Some(id) = id {
264 if cx.tcx.sess.target.target.arch == "wasm32" {
265 if let Some(module) = wasm_import_module(cx.tcx, id) {
266 llvm::AddFunctionAttrStringValue(
268 llvm::AttributePlace::Function,
269 const_cstr!("wasm-import-module"),
277 pub fn provide(providers: &mut Providers) {
278 providers.target_features_whitelist = |tcx, cnum| {
279 assert_eq!(cnum, LOCAL_CRATE);
280 if tcx.sess.opts.actually_rustdoc {
281 // rustdoc needs to be able to document functions that use all the features, so
282 // whitelist them all
283 Lrc::new(llvm_util::all_known_features()
284 .map(|(a, b)| (a.to_string(), b.map(|s| s.to_string())))
287 Lrc::new(llvm_util::target_feature_whitelist(tcx.sess)
289 .map(|&(a, b)| (a.to_string(), b.map(|s| s.to_string())))
294 provide_extern(providers);
297 pub fn provide_extern(providers: &mut Providers) {
298 providers.wasm_import_module_map = |tcx, cnum| {
299 // Build up a map from DefId to a `NativeLibrary` structure, where
300 // `NativeLibrary` internally contains information about
301 // `#[link(wasm_import_module = "...")]` for example.
302 let native_libs = tcx.native_libraries(cnum);
304 let def_id_to_native_lib = native_libs.iter().filter_map(|lib|
305 if let Some(id) = lib.foreign_module {
310 ).collect::<FxHashMap<_, _>>();
312 let mut ret = FxHashMap::default();
313 for lib in tcx.foreign_modules(cnum).iter() {
314 let module = def_id_to_native_lib
316 .and_then(|s| s.wasm_import_module);
317 let module = match module {
321 ret.extend(lib.foreign_items.iter().map(|id| {
322 assert_eq!(id.krate, cnum);
323 (*id, module.to_string())
331 fn wasm_import_module(tcx: TyCtxt, id: DefId) -> Option<CString> {
332 tcx.wasm_import_module_map(id.krate)
334 .map(|s| CString::new(&s[..]).unwrap())