]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/llvm_util.rs
Update the minimum external LLVM to 10
[rust.git] / compiler / rustc_codegen_llvm / src / llvm_util.rs
1 use crate::back::write::create_informational_target_machine;
2 use crate::llvm;
3 use libc::c_int;
4 use rustc_codegen_ssa::target_features::supported_target_features;
5 use rustc_data_structures::fx::FxHashSet;
6 use rustc_middle::bug;
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};
12
13 use std::slice;
14 use std::str;
15 use std::sync::atomic::{AtomicBool, Ordering};
16 use std::sync::Once;
17
18 static POISONED: AtomicBool = AtomicBool::new(false);
19 static INIT: Once = Once::new();
20
21 pub(crate) fn init(sess: &Session) {
22     unsafe {
23         // Before we touch LLVM, make sure that multithreading is enabled.
24         INIT.call_once(|| {
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);
29             }
30
31             configure_llvm(sess);
32         });
33
34         if POISONED.load(Ordering::SeqCst) {
35             bug!("couldn't enable multi-threaded LLVM");
36         }
37     }
38 }
39
40 fn require_inited() {
41     INIT.call_once(|| bug!("llvm is not initialized"));
42     if POISONED.load(Ordering::SeqCst) {
43         bug!("couldn't enable multi-threaded LLVM");
44     }
45 }
46
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);
51
52     llvm::LLVMRustInstallFatalErrorHandler();
53
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("")
56     }
57
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);
61
62     let user_specified_args: FxHashSet<_> =
63         sess_args.clone().map(|s| llvm_arg_to_arg_name(s)).filter(|s| !s.is_empty()).collect();
64
65     {
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());
72                 llvm_c_strs.push(s);
73             }
74         };
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);
79         }
80         if sess.print_llvm_passes() {
81             add("-debug-pass=Structure", false);
82         }
83         if !sess.opts.debugging_opts.no_generate_arange_section {
84             add("-generate-arange-section", false);
85         }
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);
90             }
91         }
92
93         if sess.target.os == "emscripten" && sess.panic_strategy() == PanicStrategy::Unwind {
94             add("-enable-emscripten-cxx-exceptions", false);
95         }
96
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);
100
101         for arg in sess_args {
102             add(&(*arg), true);
103         }
104     }
105
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")
110         }
111
112         llvm::LLVMTimeTraceProfilerInitialize();
113     }
114
115     llvm::LLVMInitializePasses();
116
117     rustc_llvm::initialize_available_targets();
118
119     llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int, llvm_args.as_ptr());
120 }
121
122 pub fn time_trace_profiler_finish(file_name: &str) {
123     unsafe {
124         let file_name = CString::new(file_name).unwrap();
125         llvm::LLVMTimeTraceProfilerFinish(file_name.as_ptr());
126     }
127 }
128
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 };
141     match (arch, s) {
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",
151         (_, s) => s,
152     }
153 }
154
155 pub fn target_features(sess: &Session) -> Vec<Symbol> {
156     let target_machine = create_informational_target_machine(sess);
157     supported_target_features(sess)
158         .iter()
159         .filter_map(
160             |&(feature, gate)| {
161                 if sess.is_nightly_build() || gate.is_none() { Some(feature) } else { None }
162             },
163         )
164         .filter(|feature| {
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()) }
168         })
169         .map(|feature| Symbol::intern(feature))
170         .collect()
171 }
172
173 pub fn print_version() {
174     let (major, minor, patch) = get_version();
175     println!("LLVM version: {}.{}.{}", major, minor, patch);
176 }
177
178 pub fn get_version() -> (u32, u32, u32) {
179     // Can be called without initializing LLVM
180     unsafe {
181         (llvm::LLVMRustVersionMajor(), llvm::LLVMRustVersionMinor(), llvm::LLVMRustVersionPatch())
182     }
183 }
184
185 pub fn print_passes() {
186     // Can be called without initializing LLVM
187     unsafe {
188         llvm::LLVMRustPrintPasses();
189     }
190 }
191
192 pub(crate) fn print(req: PrintRequest, sess: &Session) {
193     require_inited();
194     let tm = create_informational_target_machine(sess);
195     unsafe {
196         match req {
197             PrintRequest::TargetCPUs => llvm::LLVMRustPrintTargetCPUs(tm),
198             PrintRequest::TargetFeatures => llvm::LLVMRustPrintTargetFeatures(tm),
199             _ => bug!("rustc_codegen_llvm can't handle print request: {:?}", req),
200         }
201     }
202 }
203
204 fn handle_native(name: &str) -> &str {
205     if name != "native" {
206         return name;
207     }
208
209     unsafe {
210         let mut len = 0;
211         let ptr = llvm::LLVMRustGetHostCPUName(&mut len);
212         str::from_utf8(slice::from_raw_parts(ptr as *const u8, len)).unwrap()
213     }
214 }
215
216 pub fn target_cpu(sess: &Session) -> &str {
217     let name = sess.opts.cg.target_cpu.as_ref().unwrap_or(&sess.target.cpu);
218     handle_native(name)
219 }
220
221 /// The list of LLVM features computed from CLI flags (`-Ctarget-cpu`, `-Ctarget-feature`,
222 /// `--target` and similar).
223 // FIXME(nagisa): Cache the output of this somehow? Maybe make this a query? We're calling this
224 // for every function that has `#[target_feature]` on it. The global features won't change between
225 // the functions; only crates, maybe…
226 pub fn llvm_global_features(sess: &Session) -> Vec<String> {
227     // FIXME(nagisa): this should definitely be available more centrally and to other codegen backends.
228     /// These features control behaviour of rustc rather than llvm.
229     const RUSTC_SPECIFIC_FEATURES: &[&str] = &["crt-static"];
230
231     // Features that come earlier are overriden by conflicting features later in the string.
232     // Typically we'll want more explicit settings to override the implicit ones, so:
233     //
234     // * Features from -Ctarget-cpu=*; are overriden by [^1]
235     // * Features implied by --target; are overriden by
236     // * Features from -Ctarget-feature; are overriden by
237     // * function specific features.
238     //
239     // [^1]: target-cpu=native is handled here, other target-cpu values are handled implicitly
240     // through LLVM TargetMachine implementation.
241     //
242     // FIXME(nagisa): it isn't clear what's the best interaction between features implied by
243     // `-Ctarget-cpu` and `--target` are. On one hand, you'd expect CLI arguments to always
244     // override anything that's implicit, so e.g. when there's no `--target` flag, features implied
245     // the host target are overriden by `-Ctarget-cpu=*`. On the other hand, what about when both
246     // `--target` and `-Ctarget-cpu=*` are specified? Both then imply some target features and both
247     // flags are specified by the user on the CLI. It isn't as clear-cut which order of precedence
248     // should be taken in cases like these.
249     let mut features = vec![];
250
251     // -Ctarget-cpu=native
252     match sess.opts.cg.target_cpu {
253         Some(ref s) if s == "native" => {
254             let features_string = unsafe {
255                 let ptr = llvm::LLVMGetHostCPUFeatures();
256                 let features_string = if !ptr.is_null() {
257                     CStr::from_ptr(ptr)
258                         .to_str()
259                         .unwrap_or_else(|e| {
260                             bug!("LLVM returned a non-utf8 features string: {}", e);
261                         })
262                         .to_owned()
263                 } else {
264                     bug!("could not allocate host CPU features, LLVM returned a `null` string");
265                 };
266
267                 llvm::LLVMDisposeMessage(ptr);
268
269                 features_string
270             };
271             features.extend(features_string.split(",").map(String::from));
272         }
273         Some(_) | None => {}
274     };
275
276     // Features implied by an implicit or explicit `--target`.
277     features.extend(
278         sess.target
279             .features
280             .split(',')
281             .filter(|f| !f.is_empty() && !RUSTC_SPECIFIC_FEATURES.iter().any(|s| f.contains(s)))
282             .map(String::from),
283     );
284
285     // -Ctarget-features
286     features.extend(
287         sess.opts
288             .cg
289             .target_feature
290             .split(',')
291             .filter(|f| !f.is_empty() && !RUSTC_SPECIFIC_FEATURES.iter().any(|s| f.contains(s)))
292             .map(String::from),
293     );
294
295     features
296 }
297
298 pub fn tune_cpu(sess: &Session) -> Option<&str> {
299     let name = sess.opts.debugging_opts.tune_cpu.as_ref()?;
300     Some(handle_native(name))
301 }