rustc_codegen_llvm/
llvm_util.rs

1use std::collections::VecDeque;
2use std::ffi::{CStr, CString};
3use std::fmt::Write;
4use std::path::Path;
5use std::sync::Once;
6use std::{ptr, slice, str};
7
8use libc::c_int;
9use rustc_codegen_ssa::TargetConfig;
10use rustc_codegen_ssa::base::wants_wasm_eh;
11use rustc_codegen_ssa::codegen_attrs::check_tied_features;
12use rustc_data_structures::fx::{FxHashMap, FxHashSet};
13use rustc_data_structures::small_c_str::SmallCStr;
14use rustc_data_structures::unord::UnordSet;
15use rustc_fs_util::path_to_c_string;
16use rustc_middle::bug;
17use rustc_session::Session;
18use rustc_session::config::{PrintKind, PrintRequest};
19use rustc_span::Symbol;
20use rustc_target::spec::{MergeFunctions, PanicStrategy, SmallDataThresholdSupport};
21use rustc_target::target_features::{RUSTC_SPECIAL_FEATURES, RUSTC_SPECIFIC_FEATURES};
22use smallvec::{SmallVec, smallvec};
23
24use crate::back::write::create_informational_target_machine;
25use crate::errors::{
26    FixedX18InvalidArch, ForbiddenCTargetFeature, PossibleFeature, UnknownCTargetFeature,
27    UnknownCTargetFeaturePrefix, UnstableCTargetFeature,
28};
29use crate::llvm;
30
31static INIT: Once = Once::new();
32
33pub(crate) fn init(sess: &Session) {
34    unsafe {
35        // Before we touch LLVM, make sure that multithreading is enabled.
36        if llvm::LLVMIsMultithreaded() != 1 {
37            bug!("LLVM compiled without support for threads");
38        }
39        INIT.call_once(|| {
40            configure_llvm(sess);
41        });
42    }
43}
44
45fn require_inited() {
46    if !INIT.is_completed() {
47        bug!("LLVM is not initialized");
48    }
49}
50
51unsafe fn configure_llvm(sess: &Session) {
52    let n_args = sess.opts.cg.llvm_args.len() + sess.target.llvm_args.len();
53    let mut llvm_c_strs = Vec::with_capacity(n_args + 1);
54    let mut llvm_args = Vec::with_capacity(n_args + 1);
55
56    unsafe {
57        llvm::LLVMRustInstallErrorHandlers();
58    }
59    // On Windows, an LLVM assertion will open an Abort/Retry/Ignore dialog
60    // box for the purpose of launching a debugger. However, on CI this will
61    // cause it to hang until it times out, which can take several hours.
62    if std::env::var_os("CI").is_some() {
63        unsafe {
64            llvm::LLVMRustDisableSystemDialogsOnCrash();
65        }
66    }
67
68    fn llvm_arg_to_arg_name(full_arg: &str) -> &str {
69        full_arg.trim().split(|c: char| c == '=' || c.is_whitespace()).next().unwrap_or("")
70    }
71
72    let cg_opts = sess.opts.cg.llvm_args.iter().map(AsRef::as_ref);
73    let tg_opts = sess.target.llvm_args.iter().map(AsRef::as_ref);
74    let sess_args = cg_opts.chain(tg_opts);
75
76    let user_specified_args: FxHashSet<_> =
77        sess_args.clone().map(|s| llvm_arg_to_arg_name(s)).filter(|s| !s.is_empty()).collect();
78
79    {
80        // This adds the given argument to LLVM. Unless `force` is true
81        // user specified arguments are *not* overridden.
82        let mut add = |arg: &str, force: bool| {
83            if force || !user_specified_args.contains(llvm_arg_to_arg_name(arg)) {
84                let s = CString::new(arg).unwrap();
85                llvm_args.push(s.as_ptr());
86                llvm_c_strs.push(s);
87            }
88        };
89        // Set the llvm "program name" to make usage and invalid argument messages more clear.
90        add("rustc -Cllvm-args=\"...\" with", true);
91        if sess.opts.unstable_opts.time_llvm_passes {
92            add("-time-passes", false);
93        }
94        if sess.opts.unstable_opts.print_llvm_passes {
95            add("-debug-pass=Structure", false);
96        }
97        if sess.target.generate_arange_section
98            && !sess.opts.unstable_opts.no_generate_arange_section
99        {
100            add("-generate-arange-section", false);
101        }
102
103        match sess.opts.unstable_opts.merge_functions.unwrap_or(sess.target.merge_functions) {
104            MergeFunctions::Disabled | MergeFunctions::Trampolines => {}
105            MergeFunctions::Aliases => {
106                add("-mergefunc-use-aliases", false);
107            }
108        }
109
110        if wants_wasm_eh(sess) {
111            add("-wasm-enable-eh", false);
112        }
113
114        if sess.target.os == "emscripten"
115            && !sess.opts.unstable_opts.emscripten_wasm_eh
116            && sess.panic_strategy() == PanicStrategy::Unwind
117        {
118            add("-enable-emscripten-cxx-exceptions", false);
119        }
120
121        // HACK(eddyb) LLVM inserts `llvm.assume` calls to preserve align attributes
122        // during inlining. Unfortunately these may block other optimizations.
123        add("-preserve-alignment-assumptions-during-inlining=false", false);
124
125        // Use non-zero `import-instr-limit` multiplier for cold callsites.
126        add("-import-cold-multiplier=0.1", false);
127
128        if sess.print_llvm_stats() {
129            add("-stats", false);
130        }
131
132        for arg in sess_args {
133            add(&(*arg), true);
134        }
135
136        match (
137            sess.opts.unstable_opts.small_data_threshold,
138            sess.target.small_data_threshold_support(),
139        ) {
140            // Set up the small-data optimization limit for architectures that use
141            // an LLVM argument to control this.
142            (Some(threshold), SmallDataThresholdSupport::LlvmArg(arg)) => {
143                add(&format!("--{arg}={threshold}"), false)
144            }
145            _ => (),
146        };
147    }
148
149    if sess.opts.unstable_opts.llvm_time_trace {
150        unsafe { llvm::LLVMRustTimeTraceProfilerInitialize() };
151    }
152
153    rustc_llvm::initialize_available_targets();
154
155    unsafe { llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int, llvm_args.as_ptr()) };
156}
157
158pub(crate) fn time_trace_profiler_finish(file_name: &Path) {
159    unsafe {
160        let file_name = path_to_c_string(file_name);
161        llvm::LLVMRustTimeTraceProfilerFinish(file_name.as_ptr());
162    }
163}
164
165enum TargetFeatureFoldStrength<'a> {
166    // The feature is only tied when enabling the feature, disabling
167    // this feature shouldn't disable the tied feature.
168    EnableOnly(&'a str),
169    // The feature is tied for both enabling and disabling this feature.
170    Both(&'a str),
171}
172
173impl<'a> TargetFeatureFoldStrength<'a> {
174    fn as_str(&self) -> &'a str {
175        match self {
176            TargetFeatureFoldStrength::EnableOnly(feat) => feat,
177            TargetFeatureFoldStrength::Both(feat) => feat,
178        }
179    }
180}
181
182pub(crate) struct LLVMFeature<'a> {
183    llvm_feature_name: &'a str,
184    dependencies: SmallVec<[TargetFeatureFoldStrength<'a>; 1]>,
185}
186
187impl<'a> LLVMFeature<'a> {
188    fn new(llvm_feature_name: &'a str) -> Self {
189        Self { llvm_feature_name, dependencies: SmallVec::new() }
190    }
191
192    fn with_dependencies(
193        llvm_feature_name: &'a str,
194        dependencies: SmallVec<[TargetFeatureFoldStrength<'a>; 1]>,
195    ) -> Self {
196        Self { llvm_feature_name, dependencies }
197    }
198
199    fn contains(&'a self, feat: &str) -> bool {
200        self.iter().any(|dep| dep == feat)
201    }
202
203    fn iter(&'a self) -> impl Iterator<Item = &'a str> {
204        let dependencies = self.dependencies.iter().map(|feat| feat.as_str());
205        std::iter::once(self.llvm_feature_name).chain(dependencies)
206    }
207}
208
209impl<'a> IntoIterator for LLVMFeature<'a> {
210    type Item = &'a str;
211    type IntoIter = impl Iterator<Item = &'a str>;
212
213    fn into_iter(self) -> Self::IntoIter {
214        let dependencies = self.dependencies.into_iter().map(|feat| feat.as_str());
215        std::iter::once(self.llvm_feature_name).chain(dependencies)
216    }
217}
218
219// WARNING: the features after applying `to_llvm_features` must be known
220// to LLVM or the feature detection code will walk past the end of the feature
221// array, leading to crashes.
222//
223// To find a list of LLVM's names, see llvm-project/llvm/lib/Target/{ARCH}/*.td
224// where `{ARCH}` is the architecture name. Look for instances of `SubtargetFeature`.
225//
226// Check the current rustc fork of LLVM in the repo at https://github.com/rust-lang/llvm-project/.
227// The commit in use can be found via the `llvm-project` submodule in
228// https://github.com/rust-lang/rust/tree/master/src Though note that Rust can also be build with
229// an external precompiled version of LLVM which might lead to failures if the oldest tested /
230// supported LLVM version doesn't yet support the relevant intrinsics.
231pub(crate) fn to_llvm_features<'a>(sess: &Session, s: &'a str) -> Option<LLVMFeature<'a>> {
232    let arch = if sess.target.arch == "x86_64" {
233        "x86"
234    } else if sess.target.arch == "arm64ec" {
235        "aarch64"
236    } else if sess.target.arch == "sparc64" {
237        "sparc"
238    } else if sess.target.arch == "powerpc64" {
239        "powerpc"
240    } else {
241        &*sess.target.arch
242    };
243    match (arch, s) {
244        ("x86", "sse4.2") => Some(LLVMFeature::with_dependencies(
245            "sse4.2",
246            smallvec![TargetFeatureFoldStrength::EnableOnly("crc32")],
247        )),
248        ("x86", "pclmulqdq") => Some(LLVMFeature::new("pclmul")),
249        ("x86", "rdrand") => Some(LLVMFeature::new("rdrnd")),
250        ("x86", "bmi1") => Some(LLVMFeature::new("bmi")),
251        ("x86", "cmpxchg16b") => Some(LLVMFeature::new("cx16")),
252        ("x86", "lahfsahf") => Some(LLVMFeature::new("sahf")),
253        ("aarch64", "rcpc2") => Some(LLVMFeature::new("rcpc-immo")),
254        ("aarch64", "dpb") => Some(LLVMFeature::new("ccpp")),
255        ("aarch64", "dpb2") => Some(LLVMFeature::new("ccdp")),
256        ("aarch64", "frintts") => Some(LLVMFeature::new("fptoint")),
257        ("aarch64", "fcma") => Some(LLVMFeature::new("complxnum")),
258        ("aarch64", "pmuv3") => Some(LLVMFeature::new("perfmon")),
259        ("aarch64", "paca") => Some(LLVMFeature::new("pauth")),
260        ("aarch64", "pacg") => Some(LLVMFeature::new("pauth")),
261        // Before LLVM 20 those two features were packaged together as b16b16
262        ("aarch64", "sve-b16b16") if get_version().0 < 20 => Some(LLVMFeature::new("b16b16")),
263        ("aarch64", "sme-b16b16") if get_version().0 < 20 => Some(LLVMFeature::new("b16b16")),
264        ("aarch64", "flagm2") => Some(LLVMFeature::new("altnzcv")),
265        // Rust ties fp and neon together.
266        ("aarch64", "neon") => Some(LLVMFeature::with_dependencies(
267            "neon",
268            smallvec![TargetFeatureFoldStrength::Both("fp-armv8")],
269        )),
270        // In LLVM neon implicitly enables fp, but we manually enable
271        // neon when a feature only implicitly enables fp
272        ("aarch64", "fhm") => Some(LLVMFeature::new("fp16fml")),
273        ("aarch64", "fp16") => Some(LLVMFeature::new("fullfp16")),
274        // Filter out features that are not supported by the current LLVM version
275        ("aarch64", "fpmr") => None, // only existed in 18
276        ("arm", "fp16") => Some(LLVMFeature::new("fullfp16")),
277        // Filter out features that are not supported by the current LLVM version
278        ("loongarch64", "div32" | "lam-bh" | "lamcas" | "ld-seq-sa" | "scq")
279            if get_version().0 < 20 =>
280        {
281            None
282        }
283        // Filter out features that are not supported by the current LLVM version
284        ("riscv32" | "riscv64", "zacas") if get_version().0 < 20 => None,
285        // Enable the evex512 target feature if an avx512 target feature is enabled.
286        ("x86", s) if s.starts_with("avx512") => Some(LLVMFeature::with_dependencies(
287            s,
288            smallvec![TargetFeatureFoldStrength::EnableOnly("evex512")],
289        )),
290        // Support for `wide-arithmetic` will first land in LLVM 20 as part of
291        // llvm/llvm-project#111598
292        ("wasm32" | "wasm64", "wide-arithmetic") if get_version() < (20, 0, 0) => None,
293        ("sparc", "leoncasa") => Some(LLVMFeature::new("hasleoncasa")),
294        // In LLVM 19, there is no `v8plus` feature and `v9` means "SPARC-V9 instruction available and SPARC-V8+ ABI used".
295        // https://github.com/llvm/llvm-project/blob/llvmorg-19.1.0/llvm/lib/Target/Sparc/MCTargetDesc/SparcELFObjectWriter.cpp#L27-L28
296        // Before LLVM 19, there was no `v8plus` feature and `v9` means "SPARC-V9 instruction available".
297        // https://github.com/llvm/llvm-project/blob/llvmorg-18.1.0/llvm/lib/Target/Sparc/MCTargetDesc/SparcELFObjectWriter.cpp#L26
298        ("sparc", "v8plus") if get_version().0 == 19 => Some(LLVMFeature::new("v9")),
299        ("powerpc", "power8-crypto") => Some(LLVMFeature::new("crypto")),
300        // These new `amx` variants and `movrs` were introduced in LLVM20
301        ("x86", "amx-avx512" | "amx-fp8" | "amx-movrs" | "amx-tf32" | "amx-transpose")
302            if get_version().0 < 20 =>
303        {
304            None
305        }
306        ("x86", "movrs") if get_version().0 < 20 => None,
307        ("x86", "avx10.1") => Some(LLVMFeature::new("avx10.1-512")),
308        ("x86", "avx10.2") if get_version().0 < 20 => None,
309        ("x86", "avx10.2") if get_version().0 >= 20 => Some(LLVMFeature::new("avx10.2-512")),
310        ("x86", "apxf") => Some(LLVMFeature::with_dependencies(
311            "egpr",
312            smallvec![
313                TargetFeatureFoldStrength::Both("push2pop2"),
314                TargetFeatureFoldStrength::Both("ppx"),
315                TargetFeatureFoldStrength::Both("ndd"),
316                TargetFeatureFoldStrength::Both("ccmp"),
317                TargetFeatureFoldStrength::Both("cf"),
318                TargetFeatureFoldStrength::Both("nf"),
319                TargetFeatureFoldStrength::Both("zu"),
320            ],
321        )),
322        (_, s) => Some(LLVMFeature::new(s)),
323    }
324}
325
326/// Used to generate cfg variables and apply features.
327/// Must express features in the way Rust understands them.
328///
329/// We do not have to worry about RUSTC_SPECIFIC_FEATURES here, those are handled outside codegen.
330pub(crate) fn target_config(sess: &Session) -> TargetConfig {
331    // Add base features for the target.
332    // We do *not* add the -Ctarget-features there, and instead duplicate the logic for that below.
333    // The reason is that if LLVM considers a feature implied but we do not, we don't want that to
334    // show up in `cfg`. That way, `cfg` is entirely under our control -- except for the handling of
335    // the target CPU, that is still expanded to target features (with all their implied features)
336    // by LLVM.
337    let target_machine = create_informational_target_machine(sess, true);
338    // Compute which of the known target features are enabled in the 'base' target machine. We only
339    // consider "supported" features; "forbidden" features are not reflected in `cfg` as of now.
340    let mut features: FxHashSet<Symbol> = sess
341        .target
342        .rust_target_features()
343        .iter()
344        .filter(|(feature, _, _)| {
345            // skip checking special features, as LLVM may not understand them
346            if RUSTC_SPECIAL_FEATURES.contains(feature) {
347                return true;
348            }
349            if let Some(feat) = to_llvm_features(sess, feature) {
350                for llvm_feature in feat {
351                    let cstr = SmallCStr::new(llvm_feature);
352                    // `LLVMRustHasFeature` is moderately expensive. On targets with many
353                    // features (e.g. x86) these calls take a non-trivial fraction of runtime
354                    // when compiling very small programs.
355                    if !unsafe { llvm::LLVMRustHasFeature(target_machine.raw(), cstr.as_ptr()) } {
356                        return false;
357                    }
358                }
359                true
360            } else {
361                false
362            }
363        })
364        .map(|(feature, _, _)| Symbol::intern(feature))
365        .collect();
366
367    // Add enabled and remove disabled features.
368    for (enabled, feature) in
369        sess.opts.cg.target_feature.split(',').filter_map(|s| match s.chars().next() {
370            Some('+') => Some((true, Symbol::intern(&s[1..]))),
371            Some('-') => Some((false, Symbol::intern(&s[1..]))),
372            _ => None,
373        })
374    {
375        if enabled {
376            // Also add all transitively implied features.
377
378            // We don't care about the order in `features` since the only thing we use it for is the
379            // `features.contains` below.
380            #[allow(rustc::potential_query_instability)]
381            features.extend(
382                sess.target
383                    .implied_target_features(feature.as_str())
384                    .iter()
385                    .map(|s| Symbol::intern(s)),
386            );
387        } else {
388            // Remove transitively reverse-implied features.
389
390            // We don't care about the order in `features` since the only thing we use it for is the
391            // `features.contains` below.
392            #[allow(rustc::potential_query_instability)]
393            features.retain(|f| {
394                if sess.target.implied_target_features(f.as_str()).contains(&feature.as_str()) {
395                    // If `f` if implies `feature`, then `!feature` implies `!f`, so we have to
396                    // remove `f`. (This is the standard logical contraposition principle.)
397                    false
398                } else {
399                    // We can keep `f`.
400                    true
401                }
402            });
403        }
404    }
405
406    // Filter enabled features based on feature gates.
407    let f = |allow_unstable| {
408        sess.target
409            .rust_target_features()
410            .iter()
411            .filter_map(|(feature, gate, _)| {
412                // The `allow_unstable` set is used by rustc internally to determined which target
413                // features are truly available, so we want to return even perma-unstable
414                // "forbidden" features.
415                if allow_unstable
416                    || (gate.in_cfg()
417                        && (sess.is_nightly_build() || gate.requires_nightly().is_none()))
418                {
419                    Some(Symbol::intern(feature))
420                } else {
421                    None
422                }
423            })
424            .filter(|feature| features.contains(&feature))
425            .collect()
426    };
427
428    let target_features = f(false);
429    let unstable_target_features = f(true);
430    let mut cfg = TargetConfig {
431        target_features,
432        unstable_target_features,
433        has_reliable_f16: true,
434        has_reliable_f16_math: true,
435        has_reliable_f128: true,
436        has_reliable_f128_math: true,
437    };
438
439    update_target_reliable_float_cfg(sess, &mut cfg);
440    cfg
441}
442
443/// Determine whether or not experimental float types are reliable based on known bugs.
444fn update_target_reliable_float_cfg(sess: &Session, cfg: &mut TargetConfig) {
445    let target_arch = sess.target.arch.as_ref();
446    let target_os = sess.target.options.os.as_ref();
447    let target_env = sess.target.options.env.as_ref();
448    let target_abi = sess.target.options.abi.as_ref();
449    let target_pointer_width = sess.target.pointer_width;
450
451    cfg.has_reliable_f16 = match (target_arch, target_os) {
452        // Selection failure <https://github.com/llvm/llvm-project/issues/50374>
453        ("s390x", _) => false,
454        // Unsupported <https://github.com/llvm/llvm-project/issues/94434>
455        ("arm64ec", _) => false,
456        // MinGW ABI bugs <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=115054>
457        ("x86_64", "windows") if target_env == "gnu" && target_abi != "llvm" => false,
458        // Infinite recursion <https://github.com/llvm/llvm-project/issues/97981>
459        ("csky", _) => false,
460        ("hexagon", _) => false,
461        ("powerpc" | "powerpc64", _) => false,
462        ("sparc" | "sparc64", _) => false,
463        ("wasm32" | "wasm64", _) => false,
464        // `f16` support only requires that symbols converting to and from `f32` are available. We
465        // provide these in `compiler-builtins`, so `f16` should be available on all platforms that
466        // do not have other ABI issues or LLVM crashes.
467        _ => true,
468    };
469
470    cfg.has_reliable_f128 = match (target_arch, target_os) {
471        // Unsupported <https://github.com/llvm/llvm-project/issues/94434>
472        ("arm64ec", _) => false,
473        // Selection bug <https://github.com/llvm/llvm-project/issues/96432>
474        ("mips64" | "mips64r6", _) => false,
475        // Selection bug <https://github.com/llvm/llvm-project/issues/95471>
476        ("nvptx64", _) => false,
477        // ABI bugs <https://github.com/rust-lang/rust/issues/125109> et al. (full
478        // list at <https://github.com/rust-lang/rust/issues/116909>)
479        ("powerpc" | "powerpc64", _) => false,
480        // ABI unsupported  <https://github.com/llvm/llvm-project/issues/41838>
481        ("sparc", _) => false,
482        // Stack alignment bug <https://github.com/llvm/llvm-project/issues/77401>. NB: tests may
483        // not fail if our compiler-builtins is linked.
484        ("x86", _) => false,
485        // MinGW ABI bugs <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=115054>
486        ("x86_64", "windows") if target_env == "gnu" && target_abi != "llvm" => false,
487        // There are no known problems on other platforms, so the only requirement is that symbols
488        // are available. `compiler-builtins` provides all symbols required for core `f128`
489        // support, so this should work for everything else.
490        _ => true,
491    };
492
493    // Assume that working `f16` means working `f16` math for most platforms, since
494    // operations just go through `f32`.
495    cfg.has_reliable_f16_math = cfg.has_reliable_f16;
496
497    cfg.has_reliable_f128_math = match (target_arch, target_os) {
498        // LLVM lowers `fp128` math to `long double` symbols even on platforms where
499        // `long double` is not IEEE binary128. See
500        // <https://github.com/llvm/llvm-project/issues/44744>.
501        //
502        // This rules out anything that doesn't have `long double` = `binary128`; <= 32 bits
503        // (ld is `f64`), anything other than Linux (Windows and MacOS use `f64`), and `x86`
504        // (ld is 80-bit extended precision).
505        ("x86_64", _) => false,
506        (_, "linux") if target_pointer_width == 64 => true,
507        _ => false,
508    } && cfg.has_reliable_f128;
509}
510
511pub(crate) fn print_version() {
512    let (major, minor, patch) = get_version();
513    println!("LLVM version: {major}.{minor}.{patch}");
514}
515
516pub(crate) fn get_version() -> (u32, u32, u32) {
517    // Can be called without initializing LLVM
518    unsafe {
519        (llvm::LLVMRustVersionMajor(), llvm::LLVMRustVersionMinor(), llvm::LLVMRustVersionPatch())
520    }
521}
522
523pub(crate) fn print_passes() {
524    // Can be called without initializing LLVM
525    unsafe {
526        llvm::LLVMRustPrintPasses();
527    }
528}
529
530fn llvm_target_features(tm: &llvm::TargetMachine) -> Vec<(&str, &str)> {
531    let len = unsafe { llvm::LLVMRustGetTargetFeaturesCount(tm) };
532    let mut ret = Vec::with_capacity(len);
533    for i in 0..len {
534        unsafe {
535            let mut feature = ptr::null();
536            let mut desc = ptr::null();
537            llvm::LLVMRustGetTargetFeature(tm, i, &mut feature, &mut desc);
538            if feature.is_null() || desc.is_null() {
539                bug!("LLVM returned a `null` target feature string");
540            }
541            let feature = CStr::from_ptr(feature).to_str().unwrap_or_else(|e| {
542                bug!("LLVM returned a non-utf8 feature string: {}", e);
543            });
544            let desc = CStr::from_ptr(desc).to_str().unwrap_or_else(|e| {
545                bug!("LLVM returned a non-utf8 feature string: {}", e);
546            });
547            ret.push((feature, desc));
548        }
549    }
550    ret
551}
552
553pub(crate) fn print(req: &PrintRequest, out: &mut String, sess: &Session) {
554    require_inited();
555    let tm = create_informational_target_machine(sess, false);
556    match req.kind {
557        PrintKind::TargetCPUs => print_target_cpus(sess, tm.raw(), out),
558        PrintKind::TargetFeatures => print_target_features(sess, tm.raw(), out),
559        _ => bug!("rustc_codegen_llvm can't handle print request: {:?}", req),
560    }
561}
562
563fn print_target_cpus(sess: &Session, tm: &llvm::TargetMachine, out: &mut String) {
564    let cpu_names = llvm::build_string(|s| unsafe {
565        llvm::LLVMRustPrintTargetCPUs(&tm, s);
566    })
567    .unwrap();
568
569    struct Cpu<'a> {
570        cpu_name: &'a str,
571        remark: String,
572    }
573    // Compare CPU against current target to label the default.
574    let target_cpu = handle_native(&sess.target.cpu);
575    let make_remark = |cpu_name| {
576        if cpu_name == target_cpu {
577            // FIXME(#132514): This prints the LLVM target string, which can be
578            // different from the Rust target string. Is that intended?
579            let target = &sess.target.llvm_target;
580            format!(
581                " - This is the default target CPU for the current build target (currently {target})."
582            )
583        } else {
584            "".to_owned()
585        }
586    };
587    let mut cpus = cpu_names
588        .lines()
589        .map(|cpu_name| Cpu { cpu_name, remark: make_remark(cpu_name) })
590        .collect::<VecDeque<_>>();
591
592    // Only print the "native" entry when host and target are the same arch,
593    // since otherwise it could be wrong or misleading.
594    if sess.host.arch == sess.target.arch {
595        let host = get_host_cpu_name();
596        cpus.push_front(Cpu {
597            cpu_name: "native",
598            remark: format!(" - Select the CPU of the current host (currently {host})."),
599        });
600    }
601
602    let max_name_width = cpus.iter().map(|cpu| cpu.cpu_name.len()).max().unwrap_or(0);
603    writeln!(out, "Available CPUs for this target:").unwrap();
604    for Cpu { cpu_name, remark } in cpus {
605        // Only pad the CPU name if there's a remark to print after it.
606        let width = if remark.is_empty() { 0 } else { max_name_width };
607        writeln!(out, "    {cpu_name:<width$}{remark}").unwrap();
608    }
609}
610
611fn print_target_features(sess: &Session, tm: &llvm::TargetMachine, out: &mut String) {
612    let mut llvm_target_features = llvm_target_features(tm);
613    let mut known_llvm_target_features = FxHashSet::<&'static str>::default();
614    let mut rustc_target_features = sess
615        .target
616        .rust_target_features()
617        .iter()
618        .filter_map(|(feature, gate, _implied)| {
619            if !gate.in_cfg() {
620                // Only list (experimentally) supported features.
621                return None;
622            }
623            // LLVM asserts that these are sorted. LLVM and Rust both use byte comparison for these
624            // strings.
625            let llvm_feature = to_llvm_features(sess, *feature)?.llvm_feature_name;
626            let desc =
627                match llvm_target_features.binary_search_by_key(&llvm_feature, |(f, _d)| f).ok() {
628                    Some(index) => {
629                        known_llvm_target_features.insert(llvm_feature);
630                        llvm_target_features[index].1
631                    }
632                    None => "",
633                };
634
635            Some((*feature, desc))
636        })
637        .collect::<Vec<_>>();
638
639    // Since we add this at the end ...
640    rustc_target_features.extend_from_slice(&[(
641        "crt-static",
642        "Enables C Run-time Libraries to be statically linked",
643    )]);
644    // ... we need to sort the list again.
645    rustc_target_features.sort();
646
647    llvm_target_features.retain(|(f, _d)| !known_llvm_target_features.contains(f));
648
649    let max_feature_len = llvm_target_features
650        .iter()
651        .chain(rustc_target_features.iter())
652        .map(|(feature, _desc)| feature.len())
653        .max()
654        .unwrap_or(0);
655
656    writeln!(out, "Features supported by rustc for this target:").unwrap();
657    for (feature, desc) in &rustc_target_features {
658        writeln!(out, "    {feature:max_feature_len$} - {desc}.").unwrap();
659    }
660    writeln!(out, "\nCode-generation features supported by LLVM for this target:").unwrap();
661    for (feature, desc) in &llvm_target_features {
662        writeln!(out, "    {feature:max_feature_len$} - {desc}.").unwrap();
663    }
664    if llvm_target_features.is_empty() {
665        writeln!(out, "    Target features listing is not supported by this LLVM version.")
666            .unwrap();
667    }
668    writeln!(out, "\nUse +feature to enable a feature, or -feature to disable it.").unwrap();
669    writeln!(out, "For example, rustc -C target-cpu=mycpu -C target-feature=+feature1,-feature2\n")
670        .unwrap();
671    writeln!(out, "Code-generation features cannot be used in cfg or #[target_feature],").unwrap();
672    writeln!(out, "and may be renamed or removed in a future version of LLVM or rustc.\n").unwrap();
673}
674
675/// Returns the host CPU name, according to LLVM.
676fn get_host_cpu_name() -> &'static str {
677    let mut len = 0;
678    // SAFETY: The underlying C++ global function returns a `StringRef` that
679    // isn't tied to any particular backing buffer, so it must be 'static.
680    let slice: &'static [u8] = unsafe {
681        let ptr = llvm::LLVMRustGetHostCPUName(&mut len);
682        assert!(!ptr.is_null());
683        slice::from_raw_parts(ptr, len)
684    };
685    str::from_utf8(slice).expect("host CPU name should be UTF-8")
686}
687
688/// If the given string is `"native"`, returns the host CPU name according to
689/// LLVM. Otherwise, the string is returned as-is.
690fn handle_native(cpu_name: &str) -> &str {
691    match cpu_name {
692        "native" => get_host_cpu_name(),
693        _ => cpu_name,
694    }
695}
696
697pub(crate) fn target_cpu(sess: &Session) -> &str {
698    let cpu_name = sess.opts.cg.target_cpu.as_deref().unwrap_or_else(|| &sess.target.cpu);
699    handle_native(cpu_name)
700}
701
702/// The list of LLVM features computed from CLI flags (`-Ctarget-cpu`, `-Ctarget-feature`,
703/// `--target` and similar).
704pub(crate) fn global_llvm_features(
705    sess: &Session,
706    diagnostics: bool,
707    only_base_features: bool,
708) -> Vec<String> {
709    // Features that come earlier are overridden by conflicting features later in the string.
710    // Typically we'll want more explicit settings to override the implicit ones, so:
711    //
712    // * Features from -Ctarget-cpu=*; are overridden by [^1]
713    // * Features implied by --target; are overridden by
714    // * Features from -Ctarget-feature; are overridden by
715    // * function specific features.
716    //
717    // [^1]: target-cpu=native is handled here, other target-cpu values are handled implicitly
718    // through LLVM TargetMachine implementation.
719    //
720    // FIXME(nagisa): it isn't clear what's the best interaction between features implied by
721    // `-Ctarget-cpu` and `--target` are. On one hand, you'd expect CLI arguments to always
722    // override anything that's implicit, so e.g. when there's no `--target` flag, features implied
723    // the host target are overridden by `-Ctarget-cpu=*`. On the other hand, what about when both
724    // `--target` and `-Ctarget-cpu=*` are specified? Both then imply some target features and both
725    // flags are specified by the user on the CLI. It isn't as clear-cut which order of precedence
726    // should be taken in cases like these.
727    let mut features = vec![];
728
729    // -Ctarget-cpu=native
730    match sess.opts.cg.target_cpu {
731        Some(ref s) if s == "native" => {
732            // We have already figured out the actual CPU name with `LLVMRustGetHostCPUName` and set
733            // that for LLVM, so the features implied by that CPU name will be available everywhere.
734            // However, that is not sufficient: e.g. `skylake` alone is not sufficient to tell if
735            // some of the instructions are available or not. So we have to also explicitly ask for
736            // the exact set of features available on the host, and enable all of them.
737            let features_string = unsafe {
738                let ptr = llvm::LLVMGetHostCPUFeatures();
739                let features_string = if !ptr.is_null() {
740                    CStr::from_ptr(ptr)
741                        .to_str()
742                        .unwrap_or_else(|e| {
743                            bug!("LLVM returned a non-utf8 features string: {}", e);
744                        })
745                        .to_owned()
746                } else {
747                    bug!("could not allocate host CPU features, LLVM returned a `null` string");
748                };
749
750                llvm::LLVMDisposeMessage(ptr);
751
752                features_string
753            };
754            features.extend(features_string.split(',').map(String::from));
755        }
756        Some(_) | None => {}
757    };
758
759    // Features implied by an implicit or explicit `--target`.
760    features.extend(
761        sess.target
762            .features
763            .split(',')
764            .filter(|v| !v.is_empty())
765            // Drop +v8plus feature introduced in LLVM 20.
766            .filter(|v| *v != "+v8plus" || get_version() >= (20, 0, 0))
767            .map(String::from),
768    );
769
770    if wants_wasm_eh(sess) && sess.panic_strategy() == PanicStrategy::Unwind {
771        features.push("+exception-handling".into());
772    }
773
774    // -Ctarget-features
775    if !only_base_features {
776        let known_features = sess.target.rust_target_features();
777        // Will only be filled when `diagnostics` is set!
778        let mut featsmap = FxHashMap::default();
779
780        // Compute implied features
781        let mut all_rust_features = vec![];
782        for feature in sess.opts.cg.target_feature.split(',') {
783            if let Some(feature) = feature.strip_prefix('+') {
784                all_rust_features.extend(
785                    UnordSet::from(sess.target.implied_target_features(feature))
786                        .to_sorted_stable_ord()
787                        .iter()
788                        .map(|&&s| (true, s)),
789                )
790            } else if let Some(feature) = feature.strip_prefix('-') {
791                // FIXME: Why do we not remove implied features on "-" here?
792                // We do the equivalent above in `target_config`.
793                // See <https://github.com/rust-lang/rust/issues/134792>.
794                all_rust_features.push((false, feature));
795            } else if !feature.is_empty() {
796                if diagnostics {
797                    sess.dcx().emit_warn(UnknownCTargetFeaturePrefix { feature });
798                }
799            }
800        }
801        // Remove features that are meant for rustc, not LLVM.
802        all_rust_features.retain(|(_, feature)| {
803            // Retain if it is not a rustc feature
804            !RUSTC_SPECIFIC_FEATURES.contains(feature)
805        });
806
807        // Check feature validity.
808        if diagnostics {
809            for &(enable, feature) in &all_rust_features {
810                let feature_state = known_features.iter().find(|&&(v, _, _)| v == feature);
811                match feature_state {
812                    None => {
813                        let rust_feature =
814                            known_features.iter().find_map(|&(rust_feature, _, _)| {
815                                let llvm_features = to_llvm_features(sess, rust_feature)?;
816                                if llvm_features.contains(feature)
817                                    && !llvm_features.contains(rust_feature)
818                                {
819                                    Some(rust_feature)
820                                } else {
821                                    None
822                                }
823                            });
824                        let unknown_feature = if let Some(rust_feature) = rust_feature {
825                            UnknownCTargetFeature {
826                                feature,
827                                rust_feature: PossibleFeature::Some { rust_feature },
828                            }
829                        } else {
830                            UnknownCTargetFeature { feature, rust_feature: PossibleFeature::None }
831                        };
832                        sess.dcx().emit_warn(unknown_feature);
833                    }
834                    Some((_, stability, _)) => {
835                        if let Err(reason) = stability.toggle_allowed() {
836                            sess.dcx().emit_warn(ForbiddenCTargetFeature {
837                                feature,
838                                enabled: if enable { "enabled" } else { "disabled" },
839                                reason,
840                            });
841                        } else if stability.requires_nightly().is_some() {
842                            // An unstable feature. Warn about using it. It makes little sense
843                            // to hard-error here since we just warn about fully unknown
844                            // features above.
845                            sess.dcx().emit_warn(UnstableCTargetFeature { feature });
846                        }
847                    }
848                }
849
850                // FIXME(nagisa): figure out how to not allocate a full hashset here.
851                featsmap.insert(feature, enable);
852            }
853        }
854
855        // Translate this into LLVM features.
856        let feats = all_rust_features
857            .iter()
858            .filter_map(|&(enable, feature)| {
859                let enable_disable = if enable { '+' } else { '-' };
860                // We run through `to_llvm_features` when
861                // passing requests down to LLVM. This means that all in-language
862                // features also work on the command line instead of having two
863                // different names when the LLVM name and the Rust name differ.
864                let llvm_feature = to_llvm_features(sess, feature)?;
865
866                Some(
867                    std::iter::once(format!(
868                        "{}{}",
869                        enable_disable, llvm_feature.llvm_feature_name
870                    ))
871                    .chain(llvm_feature.dependencies.into_iter().filter_map(
872                        move |feat| match (enable, feat) {
873                            (_, TargetFeatureFoldStrength::Both(f))
874                            | (true, TargetFeatureFoldStrength::EnableOnly(f)) => {
875                                Some(format!("{enable_disable}{f}"))
876                            }
877                            _ => None,
878                        },
879                    )),
880                )
881            })
882            .flatten();
883        features.extend(feats);
884
885        if diagnostics && let Some(f) = check_tied_features(sess, &featsmap) {
886            sess.dcx().emit_err(rustc_codegen_ssa::errors::TargetFeatureDisableOrEnable {
887                features: f,
888                span: None,
889                missing_features: None,
890            });
891        }
892    }
893
894    // -Zfixed-x18
895    if sess.opts.unstable_opts.fixed_x18 {
896        if sess.target.arch != "aarch64" {
897            sess.dcx().emit_fatal(FixedX18InvalidArch { arch: &sess.target.arch });
898        } else {
899            features.push("+reserve-x18".into());
900        }
901    }
902
903    features
904}
905
906pub(crate) fn tune_cpu(sess: &Session) -> Option<&str> {
907    let name = sess.opts.unstable_opts.tune_cpu.as_ref()?;
908    Some(handle_native(name))
909}