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;
15 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
16 use rustc::session::Session;
17 use rustc::session::config::Sanitizer;
18 use rustc::ty::TyCtxt;
19 use rustc::ty::query::Providers;
20 use rustc_data_structures::sync::Lrc;
21 use rustc_data_structures::fx::FxHashMap;
22 use rustc_target::spec::PanicStrategy;
25 use llvm::{self, Attribute};
26 use llvm::AttributePlace::Function;
28 pub use syntax::attr::{self, InlineAttr};
30 use context::CodegenCx;
33 /// Mark LLVM function to use provided inline heuristic.
35 pub fn inline(val: &'ll Value, inline: InlineAttr) {
36 use self::InlineAttr::*;
38 Hint => Attribute::InlineHint.apply_llfn(Function, val),
39 Always => Attribute::AlwaysInline.apply_llfn(Function, val),
40 Never => Attribute::NoInline.apply_llfn(Function, val),
42 Attribute::InlineHint.unapply_llfn(Function, val);
43 Attribute::AlwaysInline.unapply_llfn(Function, val);
44 Attribute::NoInline.unapply_llfn(Function, val);
49 /// Tell LLVM to emit or not emit the information necessary to unwind the stack for the function.
51 pub fn emit_uwtable(val: &'ll Value, emit: bool) {
52 Attribute::UWTable.toggle_llfn(Function, val, emit);
55 /// Tell LLVM whether the function can or cannot unwind.
57 pub fn unwind(val: &'ll Value, can_unwind: bool) {
58 Attribute::NoUnwind.toggle_llfn(Function, val, !can_unwind);
61 /// Tell LLVM whether it should optimize function for size.
63 #[allow(dead_code)] // possibly useful function
64 pub fn set_optimize_for_size(val: &'ll Value, optimize: bool) {
65 Attribute::OptimizeForSize.toggle_llfn(Function, val, optimize);
68 /// Tell LLVM if this function should be 'naked', i.e. skip the epilogue and prologue.
70 pub fn naked(val: &'ll Value, is_naked: bool) {
71 Attribute::Naked.toggle_llfn(Function, val, is_naked);
74 pub fn set_frame_pointer_elimination(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
75 if cx.sess().must_not_eliminate_frame_pointers() {
76 llvm::AddFunctionAttrStringValue(
77 llfn, llvm::AttributePlace::Function,
78 const_cstr!("no-frame-pointer-elim"), const_cstr!("true"));
82 pub fn set_probestack(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
83 // Only use stack probes if the target specification indicates that we
84 // should be using stack probes
85 if !cx.sess().target.target.options.stack_probes {
89 // Currently stack probes seem somewhat incompatible with the address
90 // sanitizer. With asan we're already protected from stack overflow anyway
91 // so we don't really need stack probes regardless.
92 match cx.sess().opts.debugging_opts.sanitizer {
93 Some(Sanitizer::Address) => return,
97 // probestack doesn't play nice either with pgo-gen.
98 if cx.sess().opts.debugging_opts.pgo_gen.is_some() {
102 // probestack doesn't play nice either with gcov profiling.
103 if cx.sess().opts.debugging_opts.profile {
107 // Flag our internal `__rust_probestack` function as the stack probe symbol.
108 // This is defined in the `compiler-builtins` crate for each architecture.
109 llvm::AddFunctionAttrStringValue(
110 llfn, llvm::AttributePlace::Function,
111 const_cstr!("probe-stack"), const_cstr!("__rust_probestack"));
114 pub fn llvm_target_features(sess: &Session) -> impl Iterator<Item = &str> {
115 const RUSTC_SPECIFIC_FEATURES: &[&str] = &[
119 let cmdline = sess.opts.cg.target_feature.split(',')
120 .filter(|f| !RUSTC_SPECIFIC_FEATURES.iter().any(|s| f.contains(s)));
121 sess.target.target.options.features.split(',')
123 .filter(|l| !l.is_empty())
126 pub fn apply_target_cpu_attr(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
127 let target_cpu = CString::new(cx.tcx.sess.target_cpu().to_string()).unwrap();
128 llvm::AddFunctionAttrStringValue(
130 llvm::AttributePlace::Function,
131 const_cstr!("target-cpu"),
132 target_cpu.as_c_str());
135 /// Composite function which sets LLVM attributes for function depending on its AST (#[attribute])
137 pub fn from_fn_attrs(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value, id: DefId) {
138 let codegen_fn_attrs = cx.tcx.codegen_fn_attrs(id);
140 inline(llfn, codegen_fn_attrs.inline);
142 set_frame_pointer_elimination(cx, llfn);
143 set_probestack(cx, llfn);
145 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
146 Attribute::Cold.apply_llfn(Function, llfn);
148 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
151 if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::ALLOCATOR) {
152 Attribute::NoAlias.apply_llfn(
153 llvm::AttributePlace::ReturnValue, llfn);
156 let can_unwind = if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::UNWIND) {
158 } else if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_ALLOCATOR_NOUNWIND) {
161 // Perhaps questionable, but we assume that anything defined
162 // *in Rust code* may unwind. Foreign items like `extern "C" {
163 // fn foo(); }` are assumed not to unwind **unless** they have
164 // a `#[unwind]` attribute.
165 } else if !cx.tcx.is_foreign_item(id) {
172 Some(false) => attributes::unwind(llfn, false),
173 Some(true) if cx.tcx.sess.panic_strategy() == PanicStrategy::Unwind => {
174 attributes::unwind(llfn, true);
176 Some(true) | None => {}
179 // Always annotate functions with the target-cpu they are compiled for.
180 // Without this, ThinLTO won't inline Rust functions into Clang generated
181 // functions (because Clang annotates functions this way too).
182 // NOTE: For now we just apply this if -Zcross-lang-lto is specified, since
183 // it introduce a little overhead and isn't really necessary otherwise.
184 if cx.tcx.sess.opts.debugging_opts.cross_lang_lto.enabled() {
185 apply_target_cpu_attr(cx, llfn);
188 let features = llvm_target_features(cx.tcx.sess)
189 .map(|s| s.to_string())
191 codegen_fn_attrs.target_features
194 let feature = &*f.as_str();
195 format!("+{}", llvm_util::to_llvm_feature(cx.tcx.sess, feature))
198 .collect::<Vec<String>>()
201 if !features.is_empty() {
202 let val = CString::new(features).unwrap();
203 llvm::AddFunctionAttrStringValue(
204 llfn, llvm::AttributePlace::Function,
205 const_cstr!("target-features"), &val);
208 // Note that currently the `wasm-import-module` doesn't do anything, but
209 // eventually LLVM 7 should read this and ferry the appropriate import
210 // module to the output file.
211 if cx.tcx.sess.target.target.arch == "wasm32" {
212 if let Some(module) = wasm_import_module(cx.tcx, id) {
213 llvm::AddFunctionAttrStringValue(
215 llvm::AttributePlace::Function,
216 const_cstr!("wasm-import-module"),
223 pub fn provide(providers: &mut Providers) {
224 providers.target_features_whitelist = |tcx, cnum| {
225 assert_eq!(cnum, LOCAL_CRATE);
226 if tcx.sess.opts.actually_rustdoc {
227 // rustdoc needs to be able to document functions that use all the features, so
228 // whitelist them all
229 Lrc::new(llvm_util::all_known_features()
230 .map(|(a, b)| (a.to_string(), b.map(|s| s.to_string())))
233 Lrc::new(llvm_util::target_feature_whitelist(tcx.sess)
235 .map(|&(a, b)| (a.to_string(), b.map(|s| s.to_string())))
240 provide_extern(providers);
243 pub fn provide_extern(providers: &mut Providers) {
244 providers.wasm_import_module_map = |tcx, cnum| {
245 // Build up a map from DefId to a `NativeLibrary` structure, where
246 // `NativeLibrary` internally contains information about
247 // `#[link(wasm_import_module = "...")]` for example.
248 let native_libs = tcx.native_libraries(cnum);
249 let mut def_id_to_native_lib = FxHashMap();
250 for lib in native_libs.iter() {
251 if let Some(id) = lib.foreign_module {
252 def_id_to_native_lib.insert(id, lib);
256 let mut ret = FxHashMap();
257 for lib in tcx.foreign_modules(cnum).iter() {
258 let module = def_id_to_native_lib
260 .and_then(|s| s.wasm_import_module);
261 let module = match module {
265 for id in lib.foreign_items.iter() {
266 assert_eq!(id.krate, cnum);
267 ret.insert(*id, module.to_string());
275 fn wasm_import_module(tcx: TyCtxt, id: DefId) -> Option<CString> {
276 tcx.wasm_import_module_map(id.krate)
278 .map(|s| CString::new(&s[..]).unwrap())