1 use crate::back::write::create_informational_target_machine;
4 use rustc_codegen_ssa::target_features::supported_target_features;
5 use rustc_data_structures::fx::FxHashSet;
7 use rustc_session::config::PrintRequest;
8 use rustc_session::Session;
9 use rustc_span::symbol::Symbol;
10 use rustc_target::spec::{MergeFunctions, PanicStrategy};
11 use std::ffi::{CStr, CString};
15 use std::sync::atomic::{AtomicBool, Ordering};
18 static POISONED: AtomicBool = AtomicBool::new(false);
19 static INIT: Once = Once::new();
21 pub(crate) fn init(sess: &Session) {
23 // Before we touch LLVM, make sure that multithreading is enabled.
25 if llvm::LLVMStartMultithreaded() != 1 {
26 // use an extra bool to make sure that all future usage of LLVM
27 // cannot proceed despite the Once not running more than once.
28 POISONED.store(true, Ordering::SeqCst);
34 if POISONED.load(Ordering::SeqCst) {
35 bug!("couldn't enable multi-threaded LLVM");
41 INIT.call_once(|| bug!("llvm is not initialized"));
42 if POISONED.load(Ordering::SeqCst) {
43 bug!("couldn't enable multi-threaded LLVM");
47 unsafe fn configure_llvm(sess: &Session) {
48 let n_args = sess.opts.cg.llvm_args.len() + sess.target.llvm_args.len();
49 let mut llvm_c_strs = Vec::with_capacity(n_args + 1);
50 let mut llvm_args = Vec::with_capacity(n_args + 1);
52 llvm::LLVMRustInstallFatalErrorHandler();
54 fn llvm_arg_to_arg_name(full_arg: &str) -> &str {
55 full_arg.trim().split(|c: char| c == '=' || c.is_whitespace()).next().unwrap_or("")
58 let cg_opts = sess.opts.cg.llvm_args.iter();
59 let tg_opts = sess.target.llvm_args.iter();
60 let sess_args = cg_opts.chain(tg_opts);
62 let user_specified_args: FxHashSet<_> =
63 sess_args.clone().map(|s| llvm_arg_to_arg_name(s)).filter(|s| !s.is_empty()).collect();
66 // This adds the given argument to LLVM. Unless `force` is true
67 // user specified arguments are *not* overridden.
68 let mut add = |arg: &str, force: bool| {
69 if force || !user_specified_args.contains(llvm_arg_to_arg_name(arg)) {
70 let s = CString::new(arg).unwrap();
71 llvm_args.push(s.as_ptr());
75 // Set the llvm "program name" to make usage and invalid argument messages more clear.
76 add("rustc -Cllvm-args=\"...\" with", true);
77 if sess.time_llvm_passes() {
78 add("-time-passes", false);
80 if sess.print_llvm_passes() {
81 add("-debug-pass=Structure", false);
83 if !sess.opts.debugging_opts.no_generate_arange_section {
84 add("-generate-arange-section", false);
86 match sess.opts.debugging_opts.merge_functions.unwrap_or(sess.target.merge_functions) {
87 MergeFunctions::Disabled | MergeFunctions::Trampolines => {}
88 MergeFunctions::Aliases => {
89 add("-mergefunc-use-aliases", false);
93 if sess.target.os == "emscripten" && sess.panic_strategy() == PanicStrategy::Unwind {
94 add("-enable-emscripten-cxx-exceptions", false);
97 // HACK(eddyb) LLVM inserts `llvm.assume` calls to preserve align attributes
98 // during inlining. Unfortunately these may block other optimizations.
99 add("-preserve-alignment-assumptions-during-inlining=false", false);
101 // Use non-zero `import-instr-limit` multiplier for cold callsites.
102 add("-import-cold-multiplier=0.1", false);
104 for arg in sess_args {
109 if sess.opts.debugging_opts.llvm_time_trace {
110 // time-trace is not thread safe and running it in parallel will cause seg faults.
111 if !sess.opts.debugging_opts.no_parallel_llvm {
112 bug!("`-Z llvm-time-trace` requires `-Z no-parallel-llvm")
115 llvm::LLVMTimeTraceProfilerInitialize();
118 llvm::LLVMInitializePasses();
120 rustc_llvm::initialize_available_targets();
122 llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int, llvm_args.as_ptr());
125 pub fn time_trace_profiler_finish(file_name: &str) {
127 let file_name = CString::new(file_name).unwrap();
128 llvm::LLVMTimeTraceProfilerFinish(file_name.as_ptr());
132 // WARNING: the features after applying `to_llvm_feature` must be known
133 // to LLVM or the feature detection code will walk past the end of the feature
134 // array, leading to crashes.
135 // To find a list of LLVM's names, check llvm-project/llvm/include/llvm/Support/*TargetParser.def
136 // where the * matches the architecture's name
137 // Beware to not use the llvm github project for this, but check the git submodule
138 // found in src/llvm-project
139 // Though note that Rust can also be build with an external precompiled version of LLVM
140 // which might lead to failures if the oldest tested / supported LLVM version
141 // doesn't yet support the relevant intrinsics
142 pub fn to_llvm_feature<'a>(sess: &Session, s: &'a str) -> &'a str {
143 let arch = if sess.target.arch == "x86_64" { "x86" } else { &*sess.target.arch };
145 ("x86", "pclmulqdq") => "pclmul",
146 ("x86", "rdrand") => "rdrnd",
147 ("x86", "bmi1") => "bmi",
148 ("x86", "cmpxchg16b") => "cx16",
149 ("x86", "avx512vaes") => "vaes",
150 ("x86", "avx512gfni") => "gfni",
151 ("x86", "avx512vpclmulqdq") => "vpclmulqdq",
152 ("aarch64", "fp") => "fp-armv8",
153 ("aarch64", "fp16") => "fullfp16",
158 pub fn target_features(sess: &Session) -> Vec<Symbol> {
159 let target_machine = create_informational_target_machine(sess);
160 supported_target_features(sess)
164 if sess.is_nightly_build() || gate.is_none() { Some(feature) } else { None }
168 let llvm_feature = to_llvm_feature(sess, feature);
169 let cstr = CString::new(llvm_feature).unwrap();
170 unsafe { llvm::LLVMRustHasFeature(target_machine, cstr.as_ptr()) }
172 .map(|feature| Symbol::intern(feature))
176 pub fn print_version() {
177 let (major, minor, patch) = get_version();
178 println!("LLVM version: {}.{}.{}", major, minor, patch);
181 pub fn get_version() -> (u32, u32, u32) {
182 // Can be called without initializing LLVM
184 (llvm::LLVMRustVersionMajor(), llvm::LLVMRustVersionMinor(), llvm::LLVMRustVersionPatch())
188 pub fn print_passes() {
189 // Can be called without initializing LLVM
191 llvm::LLVMRustPrintPasses();
195 pub(crate) fn print(req: PrintRequest, sess: &Session) {
197 let tm = create_informational_target_machine(sess);
200 PrintRequest::TargetCPUs => llvm::LLVMRustPrintTargetCPUs(tm),
201 PrintRequest::TargetFeatures => llvm::LLVMRustPrintTargetFeatures(tm),
202 _ => bug!("rustc_codegen_llvm can't handle print request: {:?}", req),
207 fn handle_native(name: &str) -> &str {
208 if name != "native" {
214 let ptr = llvm::LLVMRustGetHostCPUName(&mut len);
215 str::from_utf8(slice::from_raw_parts(ptr as *const u8, len)).unwrap()
219 pub fn target_cpu(sess: &Session) -> &str {
220 let name = sess.opts.cg.target_cpu.as_ref().unwrap_or(&sess.target.cpu);
224 /// The list of LLVM features computed from CLI flags (`-Ctarget-cpu`, `-Ctarget-feature`,
225 /// `--target` and similar).
226 // FIXME(nagisa): Cache the output of this somehow? Maybe make this a query? We're calling this
227 // for every function that has `#[target_feature]` on it. The global features won't change between
228 // the functions; only crates, maybe…
229 pub fn llvm_global_features(sess: &Session) -> Vec<String> {
230 // FIXME(nagisa): this should definitely be available more centrally and to other codegen backends.
231 /// These features control behaviour of rustc rather than llvm.
232 const RUSTC_SPECIFIC_FEATURES: &[&str] = &["crt-static"];
234 // Features that come earlier are overriden by conflicting features later in the string.
235 // Typically we'll want more explicit settings to override the implicit ones, so:
237 // * Features from -Ctarget-cpu=*; are overriden by [^1]
238 // * Features implied by --target; are overriden by
239 // * Features from -Ctarget-feature; are overriden by
240 // * function specific features.
242 // [^1]: target-cpu=native is handled here, other target-cpu values are handled implicitly
243 // through LLVM TargetMachine implementation.
245 // FIXME(nagisa): it isn't clear what's the best interaction between features implied by
246 // `-Ctarget-cpu` and `--target` are. On one hand, you'd expect CLI arguments to always
247 // override anything that's implicit, so e.g. when there's no `--target` flag, features implied
248 // the host target are overriden by `-Ctarget-cpu=*`. On the other hand, what about when both
249 // `--target` and `-Ctarget-cpu=*` are specified? Both then imply some target features and both
250 // flags are specified by the user on the CLI. It isn't as clear-cut which order of precedence
251 // should be taken in cases like these.
252 let mut features = vec![];
254 // -Ctarget-cpu=native
255 match sess.opts.cg.target_cpu {
256 Some(ref s) if s == "native" => {
257 let features_string = unsafe {
258 let ptr = llvm::LLVMGetHostCPUFeatures();
259 let features_string = if !ptr.is_null() {
262 .unwrap_or_else(|e| {
263 bug!("LLVM returned a non-utf8 features string: {}", e);
267 bug!("could not allocate host CPU features, LLVM returned a `null` string");
270 llvm::LLVMDisposeMessage(ptr);
274 features.extend(features_string.split(",").map(String::from));
279 // Features implied by an implicit or explicit `--target`.
284 .filter(|f| !f.is_empty() && !RUSTC_SPECIFIC_FEATURES.iter().any(|s| f.contains(s)))
294 .filter(|f| !f.is_empty() && !RUSTC_SPECIFIC_FEATURES.iter().any(|s| f.contains(s)))
301 pub fn tune_cpu(sess: &Session) -> Option<&str> {
302 let name = sess.opts.debugging_opts.tune_cpu.as_ref()?;
303 Some(handle_native(name))