]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/llvm_util.rs
96d238eda59d08d417a5910a505d8c5ea0f5bcde
[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 libloading::Library;
5 use rustc_codegen_ssa::target_features::{
6     supported_target_features, tied_target_features, RUSTC_SPECIFIC_FEATURES,
7 };
8 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
9 use rustc_data_structures::small_c_str::SmallCStr;
10 use rustc_fs_util::path_to_c_string;
11 use rustc_middle::bug;
12 use rustc_session::config::PrintRequest;
13 use rustc_session::Session;
14 use rustc_span::symbol::Symbol;
15 use rustc_target::spec::{MergeFunctions, PanicStrategy};
16 use smallvec::{smallvec, SmallVec};
17 use std::ffi::{CStr, CString};
18 use tracing::debug;
19
20 use std::mem;
21 use std::path::Path;
22 use std::ptr;
23 use std::slice;
24 use std::str;
25 use std::sync::Once;
26
27 static INIT: Once = Once::new();
28
29 pub(crate) fn init(sess: &Session) {
30     unsafe {
31         // Before we touch LLVM, make sure that multithreading is enabled.
32         if llvm::LLVMIsMultithreaded() != 1 {
33             bug!("LLVM compiled without support for threads");
34         }
35         INIT.call_once(|| {
36             configure_llvm(sess);
37         });
38     }
39 }
40
41 fn require_inited() {
42     if !INIT.is_completed() {
43         bug!("LLVM is not initialized");
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     // On Windows, an LLVM assertion will open an Abort/Retry/Ignore dialog
54     // box for the purpose of launching a debugger. However, on CI this will
55     // cause it to hang until it times out, which can take several hours.
56     if std::env::var_os("CI").is_some() {
57         llvm::LLVMRustDisableSystemDialogsOnCrash();
58     }
59
60     fn llvm_arg_to_arg_name(full_arg: &str) -> &str {
61         full_arg.trim().split(|c: char| c == '=' || c.is_whitespace()).next().unwrap_or("")
62     }
63
64     let cg_opts = sess.opts.cg.llvm_args.iter().map(AsRef::as_ref);
65     let tg_opts = sess.target.llvm_args.iter().map(AsRef::as_ref);
66     let sess_args = cg_opts.chain(tg_opts);
67
68     let user_specified_args: FxHashSet<_> =
69         sess_args.clone().map(|s| llvm_arg_to_arg_name(s)).filter(|s| !s.is_empty()).collect();
70
71     {
72         // This adds the given argument to LLVM. Unless `force` is true
73         // user specified arguments are *not* overridden.
74         let mut add = |arg: &str, force: bool| {
75             if force || !user_specified_args.contains(llvm_arg_to_arg_name(arg)) {
76                 let s = CString::new(arg).unwrap();
77                 llvm_args.push(s.as_ptr());
78                 llvm_c_strs.push(s);
79             }
80         };
81         // Set the llvm "program name" to make usage and invalid argument messages more clear.
82         add("rustc -Cllvm-args=\"...\" with", true);
83         if sess.time_llvm_passes() {
84             add("-time-passes", false);
85         }
86         if sess.print_llvm_passes() {
87             add("-debug-pass=Structure", false);
88         }
89         if sess.target.generate_arange_section
90             && !sess.opts.unstable_opts.no_generate_arange_section
91         {
92             add("-generate-arange-section", false);
93         }
94
95         // Disable the machine outliner by default in LLVM versions 11 and LLVM
96         // version 12, where it leads to miscompilation.
97         //
98         // Ref:
99         // - https://github.com/rust-lang/rust/issues/85351
100         // - https://reviews.llvm.org/D103167
101         if llvm_util::get_version() < (13, 0, 0) {
102             add("-enable-machine-outliner=never", false);
103         }
104
105         match sess.opts.unstable_opts.merge_functions.unwrap_or(sess.target.merge_functions) {
106             MergeFunctions::Disabled | MergeFunctions::Trampolines => {}
107             MergeFunctions::Aliases => {
108                 add("-mergefunc-use-aliases", false);
109             }
110         }
111
112         if sess.target.os == "emscripten" && sess.panic_strategy() == PanicStrategy::Unwind {
113             add("-enable-emscripten-cxx-exceptions", false);
114         }
115
116         // HACK(eddyb) LLVM inserts `llvm.assume` calls to preserve align attributes
117         // during inlining. Unfortunately these may block other optimizations.
118         add("-preserve-alignment-assumptions-during-inlining=false", false);
119
120         // Use non-zero `import-instr-limit` multiplier for cold callsites.
121         add("-import-cold-multiplier=0.1", false);
122
123         for arg in sess_args {
124             add(&(*arg), true);
125         }
126     }
127
128     if sess.opts.unstable_opts.llvm_time_trace {
129         llvm::LLVMTimeTraceProfilerInitialize();
130     }
131
132     llvm::LLVMInitializePasses();
133
134     // Use the legacy plugin registration if we don't use the new pass manager
135     if !should_use_new_llvm_pass_manager(
136         &sess.opts.unstable_opts.new_llvm_pass_manager,
137         &sess.target.arch,
138     ) {
139         // Register LLVM plugins by loading them into the compiler process.
140         for plugin in &sess.opts.unstable_opts.llvm_plugins {
141             let lib = Library::new(plugin).unwrap_or_else(|e| bug!("couldn't load plugin: {}", e));
142             debug!("LLVM plugin loaded successfully {:?} ({})", lib, plugin);
143
144             // Intentionally leak the dynamic library. We can't ever unload it
145             // since the library can make things that will live arbitrarily long.
146             mem::forget(lib);
147         }
148     }
149
150     rustc_llvm::initialize_available_targets();
151
152     llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int, llvm_args.as_ptr());
153 }
154
155 pub fn time_trace_profiler_finish(file_name: &Path) {
156     unsafe {
157         let file_name = path_to_c_string(file_name);
158         llvm::LLVMTimeTraceProfilerFinish(file_name.as_ptr());
159     }
160 }
161
162 // WARNING: the features after applying `to_llvm_features` must be known
163 // to LLVM or the feature detection code will walk past the end of the feature
164 // array, leading to crashes.
165 //
166 // To find a list of LLVM's names, check llvm-project/llvm/include/llvm/Support/*TargetParser.def
167 // where the * matches the architecture's name
168 // Beware to not use the llvm github project for this, but check the git submodule
169 // found in src/llvm-project
170 // Though note that Rust can also be build with an external precompiled version of LLVM
171 // which might lead to failures if the oldest tested / supported LLVM version
172 // doesn't yet support the relevant intrinsics
173 pub fn to_llvm_features<'a>(sess: &Session, s: &'a str) -> SmallVec<[&'a str; 2]> {
174     let arch = if sess.target.arch == "x86_64" { "x86" } else { &*sess.target.arch };
175     match (arch, s) {
176         ("x86", "sse4.2") => {
177             if get_version() >= (14, 0, 0) {
178                 smallvec!["sse4.2", "crc32"]
179             } else {
180                 smallvec!["sse4.2"]
181             }
182         }
183         ("x86", "pclmulqdq") => smallvec!["pclmul"],
184         ("x86", "rdrand") => smallvec!["rdrnd"],
185         ("x86", "bmi1") => smallvec!["bmi"],
186         ("x86", "cmpxchg16b") => smallvec!["cx16"],
187         ("x86", "avx512vaes") => smallvec!["vaes"],
188         ("x86", "avx512gfni") => smallvec!["gfni"],
189         ("x86", "avx512vpclmulqdq") => smallvec!["vpclmulqdq"],
190         ("aarch64", "rcpc2") => smallvec!["rcpc-immo"],
191         ("aarch64", "dpb") => smallvec!["ccpp"],
192         ("aarch64", "dpb2") => smallvec!["ccdp"],
193         ("aarch64", "frintts") => smallvec!["fptoint"],
194         ("aarch64", "fcma") => smallvec!["complxnum"],
195         ("aarch64", "pmuv3") => smallvec!["perfmon"],
196         ("aarch64", "paca") => smallvec!["pauth"],
197         ("aarch64", "pacg") => smallvec!["pauth"],
198         // Rust ties fp and neon together. In LLVM neon implicitly enables fp,
199         // but we manually enable neon when a feature only implicitly enables fp
200         ("aarch64", "f32mm") => smallvec!["f32mm", "neon"],
201         ("aarch64", "f64mm") => smallvec!["f64mm", "neon"],
202         ("aarch64", "fhm") => smallvec!["fp16fml", "neon"],
203         ("aarch64", "fp16") => smallvec!["fullfp16", "neon"],
204         ("aarch64", "jsconv") => smallvec!["jsconv", "neon"],
205         ("aarch64", "sve") => smallvec!["sve", "neon"],
206         ("aarch64", "sve2") => smallvec!["sve2", "neon"],
207         ("aarch64", "sve2-aes") => smallvec!["sve2-aes", "neon"],
208         ("aarch64", "sve2-sm4") => smallvec!["sve2-sm4", "neon"],
209         ("aarch64", "sve2-sha3") => smallvec!["sve2-sha3", "neon"],
210         ("aarch64", "sve2-bitperm") => smallvec!["sve2-bitperm", "neon"],
211         (_, s) => smallvec![s],
212     }
213 }
214
215 // Given a map from target_features to whether they are enabled or disabled,
216 // ensure only valid combinations are allowed.
217 pub fn check_tied_features(
218     sess: &Session,
219     features: &FxHashMap<&str, bool>,
220 ) -> Option<&'static [&'static str]> {
221     if !features.is_empty() {
222         for tied in tied_target_features(sess) {
223             // Tied features must be set to the same value, or not set at all
224             let mut tied_iter = tied.iter();
225             let enabled = features.get(tied_iter.next().unwrap());
226             if tied_iter.any(|f| enabled != features.get(f)) {
227                 return Some(tied);
228             }
229         }
230     }
231     return None;
232 }
233
234 // Used to generate cfg variables and apply features
235 // Must express features in the way Rust understands them
236 pub fn target_features(sess: &Session, allow_unstable: bool) -> Vec<Symbol> {
237     let target_machine = create_informational_target_machine(sess);
238     let mut features: Vec<Symbol> = supported_target_features(sess)
239         .iter()
240         .filter_map(|&(feature, gate)| {
241             if sess.is_nightly_build() || allow_unstable || gate.is_none() {
242                 Some(feature)
243             } else {
244                 None
245             }
246         })
247         .filter(|feature| {
248             // check that all features in a given smallvec are enabled
249             for llvm_feature in to_llvm_features(sess, feature) {
250                 let cstr = SmallCStr::new(llvm_feature);
251                 if !unsafe { llvm::LLVMRustHasFeature(target_machine, cstr.as_ptr()) } {
252                     return false;
253                 }
254             }
255             true
256         })
257         .map(|feature| Symbol::intern(feature))
258         .collect();
259
260     // LLVM 14 changed the ABI for i128 arguments to __float/__fix builtins on Win64
261     // (see https://reviews.llvm.org/D110413). This unstable target feature is intended for use
262     // by compiler-builtins, to export the builtins with the expected, LLVM-version-dependent ABI.
263     // The target feature can be dropped once we no longer support older LLVM versions.
264     if sess.is_nightly_build() && get_version() >= (14, 0, 0) {
265         features.push(Symbol::intern("llvm14-builtins-abi"));
266     }
267     features
268 }
269
270 pub fn print_version() {
271     let (major, minor, patch) = get_version();
272     println!("LLVM version: {}.{}.{}", major, minor, patch);
273 }
274
275 pub fn get_version() -> (u32, u32, u32) {
276     // Can be called without initializing LLVM
277     unsafe {
278         (llvm::LLVMRustVersionMajor(), llvm::LLVMRustVersionMinor(), llvm::LLVMRustVersionPatch())
279     }
280 }
281
282 pub fn print_passes() {
283     // Can be called without initializing LLVM
284     unsafe {
285         llvm::LLVMRustPrintPasses();
286     }
287 }
288
289 fn llvm_target_features(tm: &llvm::TargetMachine) -> Vec<(&str, &str)> {
290     let len = unsafe { llvm::LLVMRustGetTargetFeaturesCount(tm) };
291     let mut ret = Vec::with_capacity(len);
292     for i in 0..len {
293         unsafe {
294             let mut feature = ptr::null();
295             let mut desc = ptr::null();
296             llvm::LLVMRustGetTargetFeature(tm, i, &mut feature, &mut desc);
297             if feature.is_null() || desc.is_null() {
298                 bug!("LLVM returned a `null` target feature string");
299             }
300             let feature = CStr::from_ptr(feature).to_str().unwrap_or_else(|e| {
301                 bug!("LLVM returned a non-utf8 feature string: {}", e);
302             });
303             let desc = CStr::from_ptr(desc).to_str().unwrap_or_else(|e| {
304                 bug!("LLVM returned a non-utf8 feature string: {}", e);
305             });
306             ret.push((feature, desc));
307         }
308     }
309     ret
310 }
311
312 fn print_target_features(sess: &Session, tm: &llvm::TargetMachine) {
313     let mut target_features = llvm_target_features(tm);
314     let mut rustc_target_features = supported_target_features(sess)
315         .iter()
316         .filter_map(|(feature, _gate)| {
317             for llvm_feature in to_llvm_features(sess, *feature) {
318                 // LLVM asserts that these are sorted. LLVM and Rust both use byte comparison for these strings.
319                 match target_features.binary_search_by_key(&llvm_feature, |(f, _d)| f).ok().map(
320                     |index| {
321                         let (_f, desc) = target_features.remove(index);
322                         (*feature, desc)
323                     },
324                 ) {
325                     Some(v) => return Some(v),
326                     None => {}
327                 }
328             }
329             None
330         })
331         .collect::<Vec<_>>();
332     rustc_target_features.extend_from_slice(&[(
333         "crt-static",
334         "Enables C Run-time Libraries to be statically linked",
335     )]);
336     let max_feature_len = target_features
337         .iter()
338         .chain(rustc_target_features.iter())
339         .map(|(feature, _desc)| feature.len())
340         .max()
341         .unwrap_or(0);
342
343     println!("Features supported by rustc for this target:");
344     for (feature, desc) in &rustc_target_features {
345         println!("    {1:0$} - {2}.", max_feature_len, feature, desc);
346     }
347     println!("\nCode-generation features supported by LLVM for this target:");
348     for (feature, desc) in &target_features {
349         println!("    {1:0$} - {2}.", max_feature_len, feature, desc);
350     }
351     if target_features.is_empty() {
352         println!("    Target features listing is not supported by this LLVM version.");
353     }
354     println!("\nUse +feature to enable a feature, or -feature to disable it.");
355     println!("For example, rustc -C target-cpu=mycpu -C target-feature=+feature1,-feature2\n");
356     println!("Code-generation features cannot be used in cfg or #[target_feature],");
357     println!("and may be renamed or removed in a future version of LLVM or rustc.\n");
358 }
359
360 pub(crate) fn print(req: PrintRequest, sess: &Session) {
361     require_inited();
362     let tm = create_informational_target_machine(sess);
363     match req {
364         PrintRequest::TargetCPUs => unsafe { llvm::LLVMRustPrintTargetCPUs(tm) },
365         PrintRequest::TargetFeatures => print_target_features(sess, tm),
366         _ => bug!("rustc_codegen_llvm can't handle print request: {:?}", req),
367     }
368 }
369
370 fn handle_native(name: &str) -> &str {
371     if name != "native" {
372         return name;
373     }
374
375     unsafe {
376         let mut len = 0;
377         let ptr = llvm::LLVMRustGetHostCPUName(&mut len);
378         str::from_utf8(slice::from_raw_parts(ptr as *const u8, len)).unwrap()
379     }
380 }
381
382 pub fn target_cpu(sess: &Session) -> &str {
383     match sess.opts.cg.target_cpu {
384         Some(ref name) => handle_native(name),
385         None => handle_native(sess.target.cpu.as_ref()),
386     }
387 }
388
389 /// The list of LLVM features computed from CLI flags (`-Ctarget-cpu`, `-Ctarget-feature`,
390 /// `--target` and similar).
391 pub(crate) fn global_llvm_features(sess: &Session, diagnostics: bool) -> Vec<String> {
392     // Features that come earlier are overridden by conflicting features later in the string.
393     // Typically we'll want more explicit settings to override the implicit ones, so:
394     //
395     // * Features from -Ctarget-cpu=*; are overridden by [^1]
396     // * Features implied by --target; are overridden by
397     // * Features from -Ctarget-feature; are overridden by
398     // * function specific features.
399     //
400     // [^1]: target-cpu=native is handled here, other target-cpu values are handled implicitly
401     // through LLVM TargetMachine implementation.
402     //
403     // FIXME(nagisa): it isn't clear what's the best interaction between features implied by
404     // `-Ctarget-cpu` and `--target` are. On one hand, you'd expect CLI arguments to always
405     // override anything that's implicit, so e.g. when there's no `--target` flag, features implied
406     // the host target are overridden by `-Ctarget-cpu=*`. On the other hand, what about when both
407     // `--target` and `-Ctarget-cpu=*` are specified? Both then imply some target features and both
408     // flags are specified by the user on the CLI. It isn't as clear-cut which order of precedence
409     // should be taken in cases like these.
410     let mut features = vec![];
411
412     // -Ctarget-cpu=native
413     match sess.opts.cg.target_cpu {
414         Some(ref s) if s == "native" => {
415             let features_string = unsafe {
416                 let ptr = llvm::LLVMGetHostCPUFeatures();
417                 let features_string = if !ptr.is_null() {
418                     CStr::from_ptr(ptr)
419                         .to_str()
420                         .unwrap_or_else(|e| {
421                             bug!("LLVM returned a non-utf8 features string: {}", e);
422                         })
423                         .to_owned()
424                 } else {
425                     bug!("could not allocate host CPU features, LLVM returned a `null` string");
426                 };
427
428                 llvm::LLVMDisposeMessage(ptr);
429
430                 features_string
431             };
432             features.extend(features_string.split(',').map(String::from));
433         }
434         Some(_) | None => {}
435     };
436
437     // Features implied by an implicit or explicit `--target`.
438     features.extend(
439         sess.target
440             .features
441             .split(',')
442             .filter(|v| !v.is_empty() && backend_feature_name(v).is_some())
443             // Drop +atomics-32 feature introduced in LLVM 15.
444             .filter(|v| *v != "+atomics-32" || get_version() >= (15, 0, 0))
445             .map(String::from),
446     );
447
448     // -Ctarget-features
449     let supported_features = supported_target_features(sess);
450     let mut featsmap = FxHashMap::default();
451     let feats = sess
452         .opts
453         .cg
454         .target_feature
455         .split(',')
456         .filter_map(|s| {
457             let enable_disable = match s.chars().next() {
458                 None => return None,
459                 Some(c @ '+' | c @ '-') => c,
460                 Some(_) => {
461                     if diagnostics {
462                         let mut diag = sess.struct_warn(&format!(
463                             "unknown feature specified for `-Ctarget-feature`: `{}`",
464                             s
465                         ));
466                         diag.note("features must begin with a `+` to enable or `-` to disable it");
467                         diag.emit();
468                     }
469                     return None;
470                 }
471             };
472
473             let feature = backend_feature_name(s)?;
474             // Warn against use of LLVM specific feature names on the CLI.
475             if diagnostics && !supported_features.iter().any(|&(v, _)| v == feature) {
476                 let rust_feature = supported_features.iter().find_map(|&(rust_feature, _)| {
477                     let llvm_features = to_llvm_features(sess, rust_feature);
478                     if llvm_features.contains(&feature) && !llvm_features.contains(&rust_feature) {
479                         Some(rust_feature)
480                     } else {
481                         None
482                     }
483                 });
484                 let mut diag = sess.struct_warn(&format!(
485                     "unknown feature specified for `-Ctarget-feature`: `{}`",
486                     feature
487                 ));
488                 diag.note("it is still passed through to the codegen backend");
489                 if let Some(rust_feature) = rust_feature {
490                     diag.help(&format!("you might have meant: `{}`", rust_feature));
491                 } else {
492                     diag.note("consider filing a feature request");
493                 }
494                 diag.emit();
495             }
496
497             if diagnostics {
498                 // FIXME(nagisa): figure out how to not allocate a full hashset here.
499                 featsmap.insert(feature, enable_disable == '+');
500             }
501
502             // rustc-specific features do not get passed down to LLVM…
503             if RUSTC_SPECIFIC_FEATURES.contains(&feature) {
504                 return None;
505             }
506             // ... otherwise though we run through `to_llvm_features` when
507             // passing requests down to LLVM. This means that all in-language
508             // features also work on the command line instead of having two
509             // different names when the LLVM name and the Rust name differ.
510             Some(
511                 to_llvm_features(sess, feature)
512                     .into_iter()
513                     .map(move |f| format!("{}{}", enable_disable, f)),
514             )
515         })
516         .flatten();
517     features.extend(feats);
518
519     if diagnostics && let Some(f) = check_tied_features(sess, &featsmap) {
520         sess.err(&format!(
521             "target features {} must all be enabled or disabled together",
522             f.join(", ")
523         ));
524     }
525
526     features
527 }
528
529 /// Returns a feature name for the given `+feature` or `-feature` string.
530 ///
531 /// Only allows features that are backend specific (i.e. not [`RUSTC_SPECIFIC_FEATURES`].)
532 fn backend_feature_name(s: &str) -> Option<&str> {
533     // features must start with a `+` or `-`.
534     let feature = s.strip_prefix(&['+', '-'][..]).unwrap_or_else(|| {
535         bug!("target feature `{}` must begin with a `+` or `-`", s);
536     });
537     // Rustc-specific feature requests like `+crt-static` or `-crt-static`
538     // are not passed down to LLVM.
539     if RUSTC_SPECIFIC_FEATURES.contains(&feature) {
540         return None;
541     }
542     Some(feature)
543 }
544
545 pub fn tune_cpu(sess: &Session) -> Option<&str> {
546     let name = sess.opts.unstable_opts.tune_cpu.as_ref()?;
547     Some(handle_native(name))
548 }
549
550 pub(crate) fn should_use_new_llvm_pass_manager(user_opt: &Option<bool>, target_arch: &str) -> bool {
551     // The new pass manager is enabled by default for LLVM >= 13.
552     // This matches Clang, which also enables it since Clang 13.
553
554     // Since LLVM 15, the legacy pass manager is no longer supported.
555     if llvm_util::get_version() >= (15, 0, 0) {
556         return true;
557     }
558
559     // There are some perf issues with the new pass manager when targeting
560     // s390x with LLVM 13, so enable the new pass manager only with LLVM 14.
561     // See https://github.com/rust-lang/rust/issues/89609.
562     let min_version = if target_arch == "s390x" { 14 } else { 13 };
563     user_opt.unwrap_or_else(|| llvm_util::get_version() >= (min_version, 0, 0))
564 }