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::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 for arg in sess_args {
106 if sess.opts.debugging_opts.llvm_time_trace {
107 // time-trace is not thread safe and running it in parallel will cause seg faults.
108 if !sess.opts.debugging_opts.no_parallel_llvm {
109 bug!("`-Z llvm-time-trace` requires `-Z no-parallel-llvm")
112 llvm::LLVMTimeTraceProfilerInitialize();
115 llvm::LLVMInitializePasses();
117 rustc_llvm::initialize_available_targets();
119 llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int, llvm_args.as_ptr());
122 pub fn time_trace_profiler_finish(file_name: &str) {
124 let file_name = CString::new(file_name).unwrap();
125 llvm::LLVMTimeTraceProfilerFinish(file_name.as_ptr());
129 // WARNING: the features after applying `to_llvm_feature` must be known
130 // to LLVM or the feature detection code will walk past the end of the feature
131 // array, leading to crashes.
132 // To find a list of LLVM's names, check llvm-project/llvm/include/llvm/Support/*TargetParser.def
133 // where the * matches the architecture's name
134 // Beware to not use the llvm github project for this, but check the git submodule
135 // found in src/llvm-project
136 // Though note that Rust can also be build with an external precompiled version of LLVM
137 // which might lead to failures if the oldest tested / supported LLVM version
138 // doesn't yet support the relevant intrinsics
139 pub fn to_llvm_feature<'a>(sess: &Session, s: &'a str) -> &'a str {
140 let arch = if sess.target.arch == "x86_64" { "x86" } else { &*sess.target.arch };
142 ("x86", "pclmulqdq") => "pclmul",
143 ("x86", "rdrand") => "rdrnd",
144 ("x86", "bmi1") => "bmi",
145 ("x86", "cmpxchg16b") => "cx16",
146 ("x86", "avx512vaes") => "vaes",
147 ("x86", "avx512gfni") => "gfni",
148 ("x86", "avx512vpclmulqdq") => "vpclmulqdq",
149 ("aarch64", "fp") => "fp-armv8",
150 ("aarch64", "fp16") => "fullfp16",
155 pub fn target_features(sess: &Session) -> Vec<Symbol> {
156 let target_machine = create_informational_target_machine(sess);
157 supported_target_features(sess)
161 if sess.is_nightly_build() || gate.is_none() { Some(feature) } else { None }
165 let llvm_feature = to_llvm_feature(sess, feature);
166 let cstr = CString::new(llvm_feature).unwrap();
167 unsafe { llvm::LLVMRustHasFeature(target_machine, cstr.as_ptr()) }
169 .map(|feature| Symbol::intern(feature))
173 pub fn print_version() {
174 // Can be called without initializing LLVM
176 println!("LLVM version: {}.{}", llvm::LLVMRustVersionMajor(), llvm::LLVMRustVersionMinor());
180 pub fn get_major_version() -> u32 {
181 unsafe { llvm::LLVMRustVersionMajor() }
184 pub fn print_passes() {
185 // Can be called without initializing LLVM
187 llvm::LLVMRustPrintPasses();
191 pub(crate) fn print(req: PrintRequest, sess: &Session) {
193 let tm = create_informational_target_machine(sess);
196 PrintRequest::TargetCPUs => llvm::LLVMRustPrintTargetCPUs(tm),
197 PrintRequest::TargetFeatures => llvm::LLVMRustPrintTargetFeatures(tm),
198 _ => bug!("rustc_codegen_llvm can't handle print request: {:?}", req),
203 fn handle_native(name: &str) -> &str {
204 if name != "native" {
210 let ptr = llvm::LLVMRustGetHostCPUName(&mut len);
211 str::from_utf8(slice::from_raw_parts(ptr as *const u8, len)).unwrap()
215 pub fn target_cpu(sess: &Session) -> &str {
216 let name = match sess.opts.cg.target_cpu {
218 None => &*sess.target.cpu,
224 pub fn tune_cpu(sess: &Session) -> Option<&str> {
225 match sess.opts.debugging_opts.tune_cpu {
226 Some(ref s) => Some(handle_native(&**s)),