attributes.rs 11.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Set and unset common attributes on LLVM values.

12
use std::ffi::CString;
13

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::TyCtxt;
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

25
use attributes;
26
use llvm::{self, Attribute};
A
Ariel Ben-Yehuda 已提交
27
use llvm::AttributePlace::Function;
28
use llvm_util;
29
pub use syntax::attr::{self, InlineAttr};
30

31
use context::CodegenCx;
32
use value::Value;
33 34 35

/// Mark LLVM function to use provided inline heuristic.
#[inline]
36
pub fn inline(cx: &CodegenCx<'ll, '_>, val: &'ll Value, inline: InlineAttr) {
37
    use self::InlineAttr::*;
38
    match inline {
A
Ariel Ben-Yehuda 已提交
39 40
        Hint   => Attribute::InlineHint.apply_llfn(Function, val),
        Always => Attribute::AlwaysInline.apply_llfn(Function, val),
41 42 43 44 45
        Never  => {
            if cx.tcx().sess.target.target.arch != "amdgpu" {
                Attribute::NoInline.apply_llfn(Function, val);
            }
        },
46
        None   => {
47 48 49
            Attribute::InlineHint.unapply_llfn(Function, val);
            Attribute::AlwaysInline.unapply_llfn(Function, val);
            Attribute::NoInline.unapply_llfn(Function, val);
50 51 52 53 54 55
        },
    };
}

/// Tell LLVM to emit or not emit the information necessary to unwind the stack for the function.
#[inline]
56
pub fn emit_uwtable(val: &'ll Value, emit: bool) {
A
Ariel Ben-Yehuda 已提交
57
    Attribute::UWTable.toggle_llfn(Function, val, emit);
58 59 60 61
}

/// Tell LLVM whether the function can or cannot unwind.
#[inline]
62
pub fn unwind(val: &'ll Value, can_unwind: bool) {
A
Ariel Ben-Yehuda 已提交
63
    Attribute::NoUnwind.toggle_llfn(Function, val, !can_unwind);
64 65
}

F
Fourchaux 已提交
66
/// Tell LLVM whether it should optimize function for size.
67 68
#[inline]
#[allow(dead_code)] // possibly useful function
69
pub fn set_optimize_for_size(val: &'ll Value, optimize: bool) {
A
Ariel Ben-Yehuda 已提交
70
    Attribute::OptimizeForSize.toggle_llfn(Function, val, optimize);
71 72
}

T
Ticki 已提交
73 74
/// Tell LLVM if this function should be 'naked', i.e. skip the epilogue and prologue.
#[inline]
75
pub fn naked(val: &'ll Value, is_naked: bool) {
A
Ariel Ben-Yehuda 已提交
76
    Attribute::Naked.toggle_llfn(Function, val, is_naked);
T
Ticki 已提交
77 78
}

79
pub fn set_frame_pointer_elimination(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
80
    if cx.sess().must_not_eliminate_frame_pointers() {
A
Ariel Ben-Yehuda 已提交
81
        llvm::AddFunctionAttrStringValue(
82
            llfn, llvm::AttributePlace::Function,
83
            const_cstr!("no-frame-pointer-elim"), const_cstr!("true"));
A
Alex Crichton 已提交
84
    }
85 86
}

87
pub fn set_probestack(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
88 89
    // Only use stack probes if the target specification indicates that we
    // should be using stack probes
90
    if !cx.sess().target.target.options.stack_probes {
91 92 93 94 95 96
        return
    }

    // Currently stack probes seem somewhat incompatible with the address
    // sanitizer. With asan we're already protected from stack overflow anyway
    // so we don't really need stack probes regardless.
L
ljedrz 已提交
97 98
    if let Some(Sanitizer::Address) = cx.sess().opts.debugging_opts.sanitizer {
        return
99 100
    }

101
    // probestack doesn't play nice either with pgo-gen.
102
    if cx.sess().opts.debugging_opts.pgo_gen.is_some() {
103 104 105
        return;
    }

106 107 108 109 110
    // probestack doesn't play nice either with gcov profiling.
    if cx.sess().opts.debugging_opts.profile {
        return;
    }

111 112 113 114
    // Flag our internal `__rust_probestack` function as the stack probe symbol.
    // This is defined in the `compiler-builtins` crate for each architecture.
    llvm::AddFunctionAttrStringValue(
        llfn, llvm::AttributePlace::Function,
115
        const_cstr!("probe-stack"), const_cstr!("__rust_probestack"));
116 117
}

118 119 120 121 122 123 124 125 126 127 128 129
pub fn llvm_target_features(sess: &Session) -> impl Iterator<Item = &str> {
    const RUSTC_SPECIFIC_FEATURES: &[&str] = &[
        "crt-static",
    ];

    let cmdline = sess.opts.cg.target_feature.split(',')
        .filter(|f| !RUSTC_SPECIFIC_FEATURES.iter().any(|s| f.contains(s)));
    sess.target.target.options.features.split(',')
        .chain(cmdline)
        .filter(|l| !l.is_empty())
}

130
pub fn apply_target_cpu_attr(cx: &CodegenCx<'ll, '_>, llfn: &'ll Value) {
131 132
    let cpu = llvm_util::target_cpu(cx.tcx.sess);
    let target_cpu = CString::new(cpu).unwrap();
133 134 135
    llvm::AddFunctionAttrStringValue(
            llfn,
            llvm::AttributePlace::Function,
136
            const_cstr!("target-cpu"),
137 138 139
            target_cpu.as_c_str());
}

140 141 142 143 144 145 146 147 148
/// Sets the `NonLazyBind` LLVM attribute on a given function,
/// assuming the codegen options allow skipping the PLT.
pub fn non_lazy_bind(sess: &Session, llfn: &'ll Value) {
    // Don't generate calls through PLT if it's not necessary
    if !sess.needs_plt() {
        Attribute::NonLazyBind.apply_llfn(Function, llfn);
    }
}

149 150
/// Composite function which sets LLVM attributes for function depending on its AST (#[attribute])
/// attributes.
151 152 153 154 155 156 157
pub fn from_fn_attrs(
    cx: &CodegenCx<'ll, '_>,
    llfn: &'ll Value,
    id: Option<DefId>,
) {
    let codegen_fn_attrs = id.map(|id| cx.tcx.codegen_fn_attrs(id))
        .unwrap_or(CodegenFnAttrs::new());
W
Wesley Wiser 已提交
158

159
    inline(cx, llfn, codegen_fn_attrs.inline);
160

161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
    // The `uwtable` attribute according to LLVM is:
    //
    //     This attribute indicates that the ABI being targeted requires that an
    //     unwind table entry be produced for this function even if we can show
    //     that no exceptions passes by it. This is normally the case for the
    //     ELF x86-64 abi, but it can be disabled for some compilation units.
    //
    // Typically when we're compiling with `-C panic=abort` (which implies this
    // `no_landing_pads` check) we don't need `uwtable` because we can't
    // generate any exceptions! On Windows, however, exceptions include other
    // events such as illegal instructions, segfaults, etc. This means that on
    // Windows we end up still needing the `uwtable` attribute even if the `-C
    // panic=abort` flag is passed.
    //
    // You can also find more info on why Windows is whitelisted here in:
    //      https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
    if !cx.sess().no_landing_pads() ||
       cx.sess().target.target.options.requires_uwtable {
        attributes::emit_uwtable(llfn, true);
    }

182 183
    set_frame_pointer_elimination(cx, llfn);
    set_probestack(cx, llfn);
184

I
Irina Popa 已提交
185
    if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
W
Wesley Wiser 已提交
186 187
        Attribute::Cold.apply_llfn(Function, llfn);
    }
I
Irina Popa 已提交
188
    if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
W
Wesley Wiser 已提交
189 190
        naked(llfn, true);
    }
I
Irina Popa 已提交
191
    if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::ALLOCATOR) {
W
Wesley Wiser 已提交
192 193 194
        Attribute::NoAlias.apply_llfn(
            llvm::AttributePlace::ReturnValue, llfn);
    }
195 196 197 198 199 200 201 202 203 204

    let can_unwind = if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::UNWIND) {
        Some(true)
    } else if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::RUSTC_ALLOCATOR_NOUNWIND) {
        Some(false)

    // Perhaps questionable, but we assume that anything defined
    // *in Rust code* may unwind. Foreign items like `extern "C" {
    // fn foo(); }` are assumed not to unwind **unless** they have
    // a `#[unwind]` attribute.
205
    } else if id.map(|id| !cx.tcx.is_foreign_item(id)).unwrap_or(false) {
206 207 208 209 210 211 212 213 214 215 216
        Some(true)
    } else {
        None
    };

    match can_unwind {
        Some(false) => attributes::unwind(llfn, false),
        Some(true) if cx.tcx.sess.panic_strategy() == PanicStrategy::Unwind => {
            attributes::unwind(llfn, true);
        }
        Some(true) | None => {}
217
    }
218

219 220 221 222 223 224 225 226 227
    // Always annotate functions with the target-cpu they are compiled for.
    // Without this, ThinLTO won't inline Rust functions into Clang generated
    // functions (because Clang annotates functions this way too).
    // NOTE: For now we just apply this if -Zcross-lang-lto is specified, since
    //       it introduce a little overhead and isn't really necessary otherwise.
    if cx.tcx.sess.opts.debugging_opts.cross_lang_lto.enabled() {
        apply_target_cpu_attr(cx, llfn);
    }

228 229 230
    let features = llvm_target_features(cx.tcx.sess)
        .map(|s| s.to_string())
        .chain(
I
Irina Popa 已提交
231
            codegen_fn_attrs.target_features
232 233 234 235 236 237
                .iter()
                .map(|f| {
                    let feature = &*f.as_str();
                    format!("+{}", llvm_util::to_llvm_feature(cx.tcx.sess, feature))
                })
        )
238 239 240 241 242
        .collect::<Vec<String>>()
        .join(",");

    if !features.is_empty() {
        let val = CString::new(features).unwrap();
243 244
        llvm::AddFunctionAttrStringValue(
            llfn, llvm::AttributePlace::Function,
245
            const_cstr!("target-features"), &val);
246
    }
247 248 249 250

    // Note that currently the `wasm-import-module` doesn't do anything, but
    // eventually LLVM 7 should read this and ferry the appropriate import
    // module to the output file.
251 252 253 254 255 256 257 258 259 260
    if let Some(id) = id {
        if cx.tcx.sess.target.target.arch == "wasm32" {
            if let Some(module) = wasm_import_module(cx.tcx, id) {
                llvm::AddFunctionAttrStringValue(
                    llfn,
                    llvm::AttributePlace::Function,
                    const_cstr!("wasm-import-module"),
                    &module,
                );
            }
261 262
        }
    }
263 264
}

265 266 267
pub fn provide(providers: &mut Providers) {
    providers.target_features_whitelist = |tcx, cnum| {
        assert_eq!(cnum, LOCAL_CRATE);
268 269 270 271
        if tcx.sess.opts.actually_rustdoc {
            // rustdoc needs to be able to document functions that use all the features, so
            // whitelist them all
            Lrc::new(llvm_util::all_known_features()
272
                .map(|(a, b)| (a.to_string(), b.map(|s| s.to_string())))
273 274 275 276
                .collect())
        } else {
            Lrc::new(llvm_util::target_feature_whitelist(tcx.sess)
                .iter()
277
                .map(|&(a, b)| (a.to_string(), b.map(|s| s.to_string())))
278 279
                .collect())
        }
280
    };
281

282
    provide_extern(providers);
283 284
}

285 286
pub fn provide_extern(providers: &mut Providers) {
    providers.wasm_import_module_map = |tcx, cnum| {
287 288 289 290
        // Build up a map from DefId to a `NativeLibrary` structure, where
        // `NativeLibrary` internally contains information about
        // `#[link(wasm_import_module = "...")]` for example.
        let native_libs = tcx.native_libraries(cnum);
L
ljedrz 已提交
291 292

        let def_id_to_native_lib = native_libs.iter().filter_map(|lib|
293
            if let Some(id) = lib.foreign_module {
L
ljedrz 已提交
294 295 296
                Some((id, lib))
            } else {
                None
297
            }
L
ljedrz 已提交
298
        ).collect::<FxHashMap<_, _>>();
299

300 301
        let mut ret = FxHashMap();
        for lib in tcx.foreign_modules(cnum).iter() {
302 303 304
            let module = def_id_to_native_lib
                .get(&lib.def_id)
                .and_then(|s| s.wasm_import_module);
305 306 307 308
            let module = match module {
                Some(s) => s,
                None => continue,
            };
L
ljedrz 已提交
309
            ret.extend(lib.foreign_items.iter().map(|id| {
310
                assert_eq!(id.krate, cnum);
L
ljedrz 已提交
311 312
                (*id, module.to_string())
            }));
313 314 315
        }

        Lrc::new(ret)
316
    };
317 318 319 320 321 322 323
}

fn wasm_import_module(tcx: TyCtxt, id: DefId) -> Option<CString> {
    tcx.wasm_import_module_map(id.krate)
        .get(&id)
        .map(|s| CString::new(&s[..]).unwrap())
}