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