]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/llvm_util.rs
Cleanup LLVM multi-threading checks
[rust.git] / compiler / rustc_codegen_llvm / src / llvm_util.rs
1 use crate::back::write::create_informational_target_machine;
2 use crate::{llvm, llvm_util};
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_metadata::dynamic_lib::DynamicLibrary;
7 use rustc_middle::bug;
8 use rustc_session::config::PrintRequest;
9 use rustc_session::Session;
10 use rustc_span::symbol::Symbol;
11 use rustc_target::spec::{MergeFunctions, PanicStrategy};
12 use std::ffi::{CStr, CString};
13 use tracing::debug;
14
15 use std::mem;
16 use std::path::Path;
17 use std::ptr;
18 use std::slice;
19 use std::str;
20 use std::sync::Once;
21
22 static INIT: Once = Once::new();
23
24 pub(crate) fn init(sess: &Session) {
25     unsafe {
26         // Before we touch LLVM, make sure that multithreading is enabled.
27         if llvm::LLVMIsMultithreaded() != 1 {
28             bug!("LLVM compiled without support for threads");
29         }
30         INIT.call_once(|| {
31             configure_llvm(sess);
32         });
33     }
34 }
35
36 fn require_inited() {
37     if !INIT.is_completed() {
38         bug!("LLVM is not initialized");
39     }
40 }
41
42 unsafe fn configure_llvm(sess: &Session) {
43     let n_args = sess.opts.cg.llvm_args.len() + sess.target.llvm_args.len();
44     let mut llvm_c_strs = Vec::with_capacity(n_args + 1);
45     let mut llvm_args = Vec::with_capacity(n_args + 1);
46
47     llvm::LLVMRustInstallFatalErrorHandler();
48
49     fn llvm_arg_to_arg_name(full_arg: &str) -> &str {
50         full_arg.trim().split(|c: char| c == '=' || c.is_whitespace()).next().unwrap_or("")
51     }
52
53     let cg_opts = sess.opts.cg.llvm_args.iter();
54     let tg_opts = sess.target.llvm_args.iter();
55     let sess_args = cg_opts.chain(tg_opts);
56
57     let user_specified_args: FxHashSet<_> =
58         sess_args.clone().map(|s| llvm_arg_to_arg_name(s)).filter(|s| !s.is_empty()).collect();
59
60     {
61         // This adds the given argument to LLVM. Unless `force` is true
62         // user specified arguments are *not* overridden.
63         let mut add = |arg: &str, force: bool| {
64             if force || !user_specified_args.contains(llvm_arg_to_arg_name(arg)) {
65                 let s = CString::new(arg).unwrap();
66                 llvm_args.push(s.as_ptr());
67                 llvm_c_strs.push(s);
68             }
69         };
70         // Set the llvm "program name" to make usage and invalid argument messages more clear.
71         add("rustc -Cllvm-args=\"...\" with", true);
72         if sess.time_llvm_passes() {
73             add("-time-passes", false);
74         }
75         if sess.print_llvm_passes() {
76             add("-debug-pass=Structure", false);
77         }
78         if !sess.opts.debugging_opts.no_generate_arange_section {
79             add("-generate-arange-section", false);
80         }
81
82         // Disable the machine outliner by default in LLVM versions 11 and LLVM
83         // version 12, where it leads to miscompilation.
84         //
85         // Ref:
86         // - https://github.com/rust-lang/rust/issues/85351
87         // - https://reviews.llvm.org/D103167
88         let llvm_version = llvm_util::get_version();
89         if llvm_version >= (11, 0, 0) && llvm_version < (13, 0, 0) {
90             add("-enable-machine-outliner=never", false);
91         }
92
93         match sess.opts.debugging_opts.merge_functions.unwrap_or(sess.target.merge_functions) {
94             MergeFunctions::Disabled | MergeFunctions::Trampolines => {}
95             MergeFunctions::Aliases => {
96                 add("-mergefunc-use-aliases", false);
97             }
98         }
99
100         if sess.target.os == "emscripten" && sess.panic_strategy() == PanicStrategy::Unwind {
101             add("-enable-emscripten-cxx-exceptions", false);
102         }
103
104         // HACK(eddyb) LLVM inserts `llvm.assume` calls to preserve align attributes
105         // during inlining. Unfortunately these may block other optimizations.
106         add("-preserve-alignment-assumptions-during-inlining=false", false);
107
108         // Use non-zero `import-instr-limit` multiplier for cold callsites.
109         add("-import-cold-multiplier=0.1", false);
110
111         for arg in sess_args {
112             add(&(*arg), true);
113         }
114     }
115
116     if sess.opts.debugging_opts.llvm_time_trace {
117         // time-trace is not thread safe and running it in parallel will cause seg faults.
118         if !sess.opts.debugging_opts.no_parallel_llvm {
119             bug!("`-Z llvm-time-trace` requires `-Z no-parallel-llvm")
120         }
121
122         llvm::LLVMTimeTraceProfilerInitialize();
123     }
124
125     llvm::LLVMInitializePasses();
126
127     for plugin in &sess.opts.debugging_opts.llvm_plugins {
128         let path = Path::new(plugin);
129         let res = DynamicLibrary::open(path);
130         match res {
131             Ok(_) => debug!("LLVM plugin loaded succesfully {} ({})", path.display(), plugin),
132             Err(e) => bug!("couldn't load plugin: {}", e),
133         }
134         mem::forget(res);
135     }
136
137     rustc_llvm::initialize_available_targets();
138
139     llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int, llvm_args.as_ptr());
140 }
141
142 pub fn time_trace_profiler_finish(file_name: &str) {
143     unsafe {
144         let file_name = CString::new(file_name).unwrap();
145         llvm::LLVMTimeTraceProfilerFinish(file_name.as_ptr());
146     }
147 }
148
149 // WARNING: the features after applying `to_llvm_feature` must be known
150 // to LLVM or the feature detection code will walk past the end of the feature
151 // array, leading to crashes.
152 // To find a list of LLVM's names, check llvm-project/llvm/include/llvm/Support/*TargetParser.def
153 // where the * matches the architecture's name
154 // Beware to not use the llvm github project for this, but check the git submodule
155 // found in src/llvm-project
156 // Though note that Rust can also be build with an external precompiled version of LLVM
157 // which might lead to failures if the oldest tested / supported LLVM version
158 // doesn't yet support the relevant intrinsics
159 pub fn to_llvm_feature<'a>(sess: &Session, s: &'a str) -> Vec<&'a str> {
160     let arch = if sess.target.arch == "x86_64" { "x86" } else { &*sess.target.arch };
161     match (arch, s) {
162         ("x86", "sse4.2") => {
163             if get_version() >= (14, 0, 0) {
164                 vec!["sse4.2", "crc32"]
165             } else {
166                 vec!["sse4.2"]
167             }
168         }
169         ("x86", "pclmulqdq") => vec!["pclmul"],
170         ("x86", "rdrand") => vec!["rdrnd"],
171         ("x86", "bmi1") => vec!["bmi"],
172         ("x86", "cmpxchg16b") => vec!["cx16"],
173         ("x86", "avx512vaes") => vec!["vaes"],
174         ("x86", "avx512gfni") => vec!["gfni"],
175         ("x86", "avx512vpclmulqdq") => vec!["vpclmulqdq"],
176         ("aarch64", "fp") => vec!["fp-armv8"],
177         ("aarch64", "fp16") => vec!["fullfp16"],
178         ("aarch64", "fhm") => vec!["fp16fml"],
179         ("aarch64", "rcpc2") => vec!["rcpc-immo"],
180         ("aarch64", "dpb") => vec!["ccpp"],
181         ("aarch64", "dpb2") => vec!["ccdp"],
182         ("aarch64", "frintts") => vec!["fptoint"],
183         ("aarch64", "fcma") => vec!["complxnum"],
184         (_, s) => vec![s],
185     }
186 }
187
188 pub fn target_features(sess: &Session) -> Vec<Symbol> {
189     let target_machine = create_informational_target_machine(sess);
190     supported_target_features(sess)
191         .iter()
192         .filter_map(
193             |&(feature, gate)| {
194                 if sess.is_nightly_build() || gate.is_none() { Some(feature) } else { None }
195             },
196         )
197         .filter(|feature| {
198             for llvm_feature in to_llvm_feature(sess, feature) {
199                 let cstr = CString::new(llvm_feature).unwrap();
200                 if unsafe { llvm::LLVMRustHasFeature(target_machine, cstr.as_ptr()) } {
201                     return true;
202                 }
203             }
204             false
205         })
206         .map(|feature| Symbol::intern(feature))
207         .collect()
208 }
209
210 pub fn print_version() {
211     let (major, minor, patch) = get_version();
212     println!("LLVM version: {}.{}.{}", major, minor, patch);
213 }
214
215 pub fn get_version() -> (u32, u32, u32) {
216     // Can be called without initializing LLVM
217     unsafe {
218         (llvm::LLVMRustVersionMajor(), llvm::LLVMRustVersionMinor(), llvm::LLVMRustVersionPatch())
219     }
220 }
221
222 pub fn print_passes() {
223     // Can be called without initializing LLVM
224     unsafe {
225         llvm::LLVMRustPrintPasses();
226     }
227 }
228
229 fn llvm_target_features(tm: &llvm::TargetMachine) -> Vec<(&str, &str)> {
230     let len = unsafe { llvm::LLVMRustGetTargetFeaturesCount(tm) };
231     let mut ret = Vec::with_capacity(len);
232     for i in 0..len {
233         unsafe {
234             let mut feature = ptr::null();
235             let mut desc = ptr::null();
236             llvm::LLVMRustGetTargetFeature(tm, i, &mut feature, &mut desc);
237             if feature.is_null() || desc.is_null() {
238                 bug!("LLVM returned a `null` target feature string");
239             }
240             let feature = CStr::from_ptr(feature).to_str().unwrap_or_else(|e| {
241                 bug!("LLVM returned a non-utf8 feature string: {}", e);
242             });
243             let desc = CStr::from_ptr(desc).to_str().unwrap_or_else(|e| {
244                 bug!("LLVM returned a non-utf8 feature string: {}", e);
245             });
246             ret.push((feature, desc));
247         }
248     }
249     ret
250 }
251
252 fn print_target_features(sess: &Session, tm: &llvm::TargetMachine) {
253     let mut target_features = llvm_target_features(tm);
254     let mut rustc_target_features = supported_target_features(sess)
255         .iter()
256         .filter_map(|(feature, _gate)| {
257             for llvm_feature in to_llvm_feature(sess, *feature) {
258                 // LLVM asserts that these are sorted. LLVM and Rust both use byte comparison for these strings.
259                 match target_features.binary_search_by_key(&llvm_feature, |(f, _d)| (*f)).ok().map(
260                     |index| {
261                         let (_f, desc) = target_features.remove(index);
262                         (*feature, desc)
263                     },
264                 ) {
265                     Some(v) => return Some(v),
266                     None => {}
267                 }
268             }
269             None
270         })
271         .collect::<Vec<_>>();
272     rustc_target_features.extend_from_slice(&[(
273         "crt-static",
274         "Enables C Run-time Libraries to be statically linked",
275     )]);
276     let max_feature_len = target_features
277         .iter()
278         .chain(rustc_target_features.iter())
279         .map(|(feature, _desc)| feature.len())
280         .max()
281         .unwrap_or(0);
282
283     println!("Features supported by rustc for this target:");
284     for (feature, desc) in &rustc_target_features {
285         println!("    {1:0$} - {2}.", max_feature_len, feature, desc);
286     }
287     println!("\nCode-generation features supported by LLVM for this target:");
288     for (feature, desc) in &target_features {
289         println!("    {1:0$} - {2}.", max_feature_len, feature, desc);
290     }
291     if target_features.is_empty() {
292         println!("    Target features listing is not supported by this LLVM version.");
293     }
294     println!("\nUse +feature to enable a feature, or -feature to disable it.");
295     println!("For example, rustc -C target-cpu=mycpu -C target-feature=+feature1,-feature2\n");
296     println!("Code-generation features cannot be used in cfg or #[target_feature],");
297     println!("and may be renamed or removed in a future version of LLVM or rustc.\n");
298 }
299
300 pub(crate) fn print(req: PrintRequest, sess: &Session) {
301     require_inited();
302     let tm = create_informational_target_machine(sess);
303     match req {
304         PrintRequest::TargetCPUs => unsafe { llvm::LLVMRustPrintTargetCPUs(tm) },
305         PrintRequest::TargetFeatures => print_target_features(sess, tm),
306         _ => bug!("rustc_codegen_llvm can't handle print request: {:?}", req),
307     }
308 }
309
310 fn handle_native(name: &str) -> &str {
311     if name != "native" {
312         return name;
313     }
314
315     unsafe {
316         let mut len = 0;
317         let ptr = llvm::LLVMRustGetHostCPUName(&mut len);
318         str::from_utf8(slice::from_raw_parts(ptr as *const u8, len)).unwrap()
319     }
320 }
321
322 pub fn target_cpu(sess: &Session) -> &str {
323     let name = sess.opts.cg.target_cpu.as_ref().unwrap_or(&sess.target.cpu);
324     handle_native(name)
325 }
326
327 /// The list of LLVM features computed from CLI flags (`-Ctarget-cpu`, `-Ctarget-feature`,
328 /// `--target` and similar).
329 // FIXME(nagisa): Cache the output of this somehow? Maybe make this a query? We're calling this
330 // for every function that has `#[target_feature]` on it. The global features won't change between
331 // the functions; only crates, maybe…
332 pub fn llvm_global_features(sess: &Session) -> Vec<String> {
333     // FIXME(nagisa): this should definitely be available more centrally and to other codegen backends.
334     /// These features control behaviour of rustc rather than llvm.
335     const RUSTC_SPECIFIC_FEATURES: &[&str] = &["crt-static"];
336
337     // Features that come earlier are overriden by conflicting features later in the string.
338     // Typically we'll want more explicit settings to override the implicit ones, so:
339     //
340     // * Features from -Ctarget-cpu=*; are overriden by [^1]
341     // * Features implied by --target; are overriden by
342     // * Features from -Ctarget-feature; are overriden by
343     // * function specific features.
344     //
345     // [^1]: target-cpu=native is handled here, other target-cpu values are handled implicitly
346     // through LLVM TargetMachine implementation.
347     //
348     // FIXME(nagisa): it isn't clear what's the best interaction between features implied by
349     // `-Ctarget-cpu` and `--target` are. On one hand, you'd expect CLI arguments to always
350     // override anything that's implicit, so e.g. when there's no `--target` flag, features implied
351     // the host target are overriden by `-Ctarget-cpu=*`. On the other hand, what about when both
352     // `--target` and `-Ctarget-cpu=*` are specified? Both then imply some target features and both
353     // flags are specified by the user on the CLI. It isn't as clear-cut which order of precedence
354     // should be taken in cases like these.
355     let mut features = vec![];
356
357     // -Ctarget-cpu=native
358     match sess.opts.cg.target_cpu {
359         Some(ref s) if s == "native" => {
360             let features_string = unsafe {
361                 let ptr = llvm::LLVMGetHostCPUFeatures();
362                 let features_string = if !ptr.is_null() {
363                     CStr::from_ptr(ptr)
364                         .to_str()
365                         .unwrap_or_else(|e| {
366                             bug!("LLVM returned a non-utf8 features string: {}", e);
367                         })
368                         .to_owned()
369                 } else {
370                     bug!("could not allocate host CPU features, LLVM returned a `null` string");
371                 };
372
373                 llvm::LLVMDisposeMessage(ptr);
374
375                 features_string
376             };
377             features.extend(features_string.split(',').map(String::from));
378         }
379         Some(_) | None => {}
380     };
381
382     let filter = |s: &str| {
383         if s.is_empty() {
384             return vec![];
385         }
386         let feature = if s.starts_with('+') || s.starts_with('-') {
387             &s[1..]
388         } else {
389             return vec![s.to_string()];
390         };
391         // Rustc-specific feature requests like `+crt-static` or `-crt-static`
392         // are not passed down to LLVM.
393         if RUSTC_SPECIFIC_FEATURES.contains(&feature) {
394             return vec![];
395         }
396         // ... otherwise though we run through `to_llvm_feature` feature when
397         // passing requests down to LLVM. This means that all in-language
398         // features also work on the command line instead of having two
399         // different names when the LLVM name and the Rust name differ.
400         to_llvm_feature(sess, feature).iter().map(|f| format!("{}{}", &s[..1], f)).collect()
401     };
402
403     // Features implied by an implicit or explicit `--target`.
404     features.extend(sess.target.features.split(',').flat_map(&filter));
405
406     // -Ctarget-features
407     features.extend(sess.opts.cg.target_feature.split(',').flat_map(&filter));
408
409     // FIXME: Move outline-atomics to target definition when earliest supported LLVM is 12.
410     if get_version() >= (12, 0, 0) && sess.target.llvm_target.contains("aarch64-unknown-linux") {
411         features.push("+outline-atomics".to_string());
412     }
413
414     features
415 }
416
417 pub fn tune_cpu(sess: &Session) -> Option<&str> {
418     let name = sess.opts.debugging_opts.tune_cpu.as_ref()?;
419     Some(handle_native(name))
420 }