Skip to main content

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::base::wants_wasm_eh;
10use rustc_codegen_ssa::target_features::internal_target_features;
11use rustc_codegen_ssa::{TargetConfig, target_features};
12use rustc_data_structures::fx::FxHashSet;
13use rustc_data_structures::small_c_str::SmallCStr;
14use rustc_fs_util::path_to_c_string;
15use rustc_middle::bug;
16use rustc_session::Session;
17use rustc_session::config::{NATIVE_CPU, PrintKind, PrintRequest};
18use rustc_target::spec::{
19    Arch, CfgAbi, Env, MergeFunctions, Os, PanicStrategy, SmallDataThresholdSupport,
20};
21use smallvec::{SmallVec, smallvec};
22
23use crate::back::write::create_informational_target_machine;
24use crate::{diagnostics, llvm};
25
26static INIT: Once = Once::new();
27
28pub(crate) fn init(sess: &Session) {
29    unsafe {
30        // Before we touch LLVM, make sure that multithreading is enabled.
31        if !llvm::LLVMIsMultithreaded().is_true() {
32            ::rustc_middle::util::bug::bug_fmt(format_args!("LLVM compiled without support for threads"));bug!("LLVM compiled without support for threads");
33        }
34        INIT.call_once(|| {
35            configure_llvm(sess);
36        });
37    }
38}
39
40fn require_inited() {
41    if !INIT.is_completed() {
42        ::rustc_middle::util::bug::bug_fmt(format_args!("LLVM is not initialized"));bug!("LLVM is not initialized");
43    }
44}
45
46unsafe fn configure_llvm(sess: &Session) {
47    let n_args = sess.opts.cg.llvm_args.len() + sess.target.llvm_args.len();
48    let mut llvm_c_strs = Vec::with_capacity(n_args + 1);
49    let mut llvm_args = Vec::with_capacity(n_args + 1);
50
51    // Check to ensure we're running against the correct LLVM version.
52    unsafe {
53        let (llvm_major, llvm_minor, llvm_patch) = get_version();
54        let expected_version = llvm::LLVMRustVersionMajor();
55        if llvm_major != expected_version {
56            sess.dcx().emit_fatal(diagnostics::LlvmVersionMismatch {
57                expected_version,
58                llvm_major,
59                llvm_minor,
60                llvm_patch,
61                dll_loc: &match rustc_session::filesearch::dll_path(llvm::LLVMGetVersion as *mut _)
62                {
63                    Ok(path) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" at {0}", path.display()))
    })format!(" at {}", path.display()),
64                    Err(_) => String::new(),
65                },
66            })
67        }
68    }
69
70    unsafe {
71        llvm::LLVMRustInstallErrorHandlers();
72    }
73    // On Windows, an LLVM assertion will open an Abort/Retry/Ignore dialog
74    // box for the purpose of launching a debugger. However, on CI this will
75    // cause it to hang until it times out, which can take several hours.
76    if std::env::var_os("CI").is_some() {
77        unsafe {
78            llvm::LLVMRustDisableSystemDialogsOnCrash();
79        }
80    }
81
82    fn llvm_arg_to_arg_name(full_arg: &str) -> &str {
83        full_arg.trim().split(|c: char| c == '=' || c.is_whitespace()).next().unwrap_or("")
84    }
85
86    let cg_opts = sess.opts.cg.llvm_args.iter().map(AsRef::as_ref);
87    let tg_opts = sess.target.llvm_args.iter().map(AsRef::as_ref);
88    // Target-spec args are passed to LLVM before user `-Cllvm-args`. LLVM's
89    // `cl::opt` parser is last-wins, so this lets `-Cllvm-args=...` override
90    // a value already set in the target spec (e.g. `-wasm-use-legacy-eh`).
91    let sess_args = tg_opts.chain(cg_opts);
92
93    let user_specified_args: FxHashSet<_> =
94        sess_args.clone().map(|s| llvm_arg_to_arg_name(s)).filter(|s| !s.is_empty()).collect();
95
96    {
97        // This adds the given argument to LLVM. Unless `force` is true
98        // user specified arguments are *not* overridden.
99        let mut add = |arg: &str, force: bool| {
100            if force || !user_specified_args.contains(llvm_arg_to_arg_name(arg)) {
101                let s = CString::new(arg).unwrap();
102                llvm_args.push(s.as_ptr());
103                llvm_c_strs.push(s);
104            }
105        };
106        // Set the llvm "program name" to make usage and invalid argument messages more clear.
107        add("rustc -Cllvm-args=\"...\" with", true);
108        if sess.opts.unstable_opts.time_llvm_passes {
109            add("-time-passes", false);
110        }
111        if sess.opts.unstable_opts.print_llvm_passes {
112            add("-debug-pass=Structure", false);
113        }
114        if sess.target.generate_arange_section
115            && !sess.opts.unstable_opts.no_generate_arange_section
116        {
117            add("-generate-arange-section", false);
118        }
119
120        match sess.opts.unstable_opts.merge_functions.unwrap_or(sess.target.merge_functions) {
121            MergeFunctions::Disabled | MergeFunctions::Trampolines => {}
122            MergeFunctions::Aliases => {
123                add("-mergefunc-use-aliases", false);
124            }
125        }
126
127        if wants_wasm_eh(sess) {
128            add("-wasm-enable-eh", false);
129        }
130
131        // HACK(eddyb) LLVM inserts `llvm.assume` calls to preserve align attributes
132        // during inlining. Unfortunately these may block other optimizations.
133        add("-preserve-alignment-assumptions-during-inlining=false", false);
134
135        // Use non-zero `import-instr-limit` multiplier for cold callsites.
136        add("-import-cold-multiplier=0.1", false);
137
138        if sess.print_llvm_stats() || sess.print_llvm_stats_json().is_some() {
139            add("-stats", false);
140        }
141
142        for arg in sess_args {
143            add(&(*arg), true);
144        }
145
146        match (
147            sess.opts.unstable_opts.small_data_threshold,
148            sess.target.small_data_threshold_support(),
149        ) {
150            // Set up the small-data optimization limit for architectures that use
151            // an LLVM argument to control this.
152            (Some(threshold), SmallDataThresholdSupport::LlvmArg(arg)) => {
153                add(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("--{0}={1}", arg, threshold))
    })format!("--{arg}={threshold}"), false)
154            }
155            _ => (),
156        };
157    }
158
159    if sess.opts.unstable_opts.llvm_time_trace {
160        unsafe { llvm::LLVMRustTimeTraceProfilerInitialize() };
161    }
162
163    rustc_llvm::initialize_available_targets();
164
165    unsafe { llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int, llvm_args.as_ptr()) };
166}
167
168pub(crate) fn time_trace_profiler_finish(file_name: &Path) {
169    unsafe {
170        let file_name = path_to_c_string(file_name);
171        llvm::LLVMRustTimeTraceProfilerFinish(file_name.as_ptr());
172    }
173}
174
175enum TargetFeatureFoldStrength<'a> {
176    // The feature is only tied when enabling the feature, disabling
177    // this feature shouldn't disable the tied feature.
178    EnableOnly(&'a str),
179    // The feature is tied for both enabling and disabling this feature.
180    Both(&'a str),
181}
182
183impl<'a> TargetFeatureFoldStrength<'a> {
184    fn as_str(&self) -> &'a str {
185        match self {
186            TargetFeatureFoldStrength::EnableOnly(feat) => feat,
187            TargetFeatureFoldStrength::Both(feat) => feat,
188        }
189    }
190}
191
192pub(crate) struct LLVMFeature<'a> {
193    llvm_feature_name: &'a str,
194    dependencies: SmallVec<[TargetFeatureFoldStrength<'a>; 1]>,
195}
196
197impl<'a> LLVMFeature<'a> {
198    fn new(llvm_feature_name: &'a str) -> Self {
199        Self { llvm_feature_name, dependencies: SmallVec::new() }
200    }
201
202    fn with_dependencies(
203        llvm_feature_name: &'a str,
204        dependencies: SmallVec<[TargetFeatureFoldStrength<'a>; 1]>,
205    ) -> Self {
206        Self { llvm_feature_name, dependencies }
207    }
208}
209
210impl<'a> IntoIterator for LLVMFeature<'a> {
211    type Item = &'a str;
212    type IntoIter = impl Iterator<Item = &'a str>;
213
214    fn into_iter(self) -> Self::IntoIter {
215        let dependencies = self.dependencies.into_iter().map(|feat| feat.as_str());
216        std::iter::once(self.llvm_feature_name).chain(dependencies)
217    }
218}
219
220/// Convert a Rust feature name to an LLVM feature name. Returning `None` means the
221/// feature should be skipped, usually because it is not supported by the current
222/// LLVM version.
223///
224/// WARNING: the features after applying `to_llvm_features` must be known
225/// to LLVM or the feature detection code will walk past the end of the feature
226/// array, leading to crashes.
227///
228/// To find a list of LLVM's names, see llvm-project/llvm/lib/Target/{ARCH}/*.td
229/// where `{ARCH}` is the architecture name. Look for instances of `SubtargetFeature`.
230///
231/// Check the current rustc fork of LLVM in the repo at
232/// <https://github.com/rust-lang/llvm-project/>. The commit in use can be found via the
233/// `llvm-project` submodule in <https://github.com/rust-lang/rust/tree/HEAD/src> Though note that
234/// Rust can also be build with an external precompiled version of LLVM which might lead to failures
235/// if the oldest tested / supported LLVM version doesn't yet support the relevant intrinsics.
236pub(crate) fn to_llvm_features<'a>(sess: &Session, s: &'a str) -> Option<LLVMFeature<'a>> {
237    let (major, _, _) = get_version();
238    match sess.target.arch {
239        Arch::AArch64 | Arch::Arm64EC => {
240            match s {
241                "rcpc2" => Some(LLVMFeature::new("rcpc-immo")),
242                "dpb" => Some(LLVMFeature::new("ccpp")),
243                "dpb2" => Some(LLVMFeature::new("ccdp")),
244                "frintts" => Some(LLVMFeature::new("fptoint")),
245                "fcma" => Some(LLVMFeature::new("complxnum")),
246                "pmuv3" => Some(LLVMFeature::new("perfmon")),
247                "paca" => Some(LLVMFeature::new("pauth")),
248                "pacg" => Some(LLVMFeature::new("pauth")),
249                "flagm2" => Some(LLVMFeature::new("altnzcv")),
250                // Rust ties fp and neon together.
251                "neon" => Some(LLVMFeature::with_dependencies(
252                    "neon",
253                    {
    let count = 0usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push(TargetFeatureFoldStrength::Both("fp-armv8"));
        vec
    } else {
        ::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                    [TargetFeatureFoldStrength::Both("fp-armv8")])))
    }
}smallvec![TargetFeatureFoldStrength::Both("fp-armv8")],
254                )),
255                // In LLVM neon implicitly enables fp, but we manually enable
256                // neon when a feature only implicitly enables fp
257                "fhm" => Some(LLVMFeature::new("fp16fml")),
258                "fp16" => Some(LLVMFeature::new("fullfp16")),
259                // Filter out features that are not supported by the current LLVM version
260                "fpmr" => None, // only existed in 18
261                // Withdrawn by ARM; removed from LLVM in 22
262                "tme" if major >= 22 => None,
263                s => Some(LLVMFeature::new(s)),
264            }
265        }
266        Arch::Arm => match s {
267            "fp16" => Some(LLVMFeature::new("fullfp16")),
268            s => Some(LLVMFeature::new(s)),
269        },
270        Arch::Bpf => match s {
271            "allows-misaligned-mem-access" if major < 22 => None,
272            s => Some(LLVMFeature::new(s)),
273        },
274        Arch::Nvptx64 => match s {
275            "sm_101" if major >= 24 => Some(LLVMFeature::new("sm_110")),
276            "sm_101a" if major >= 24 => Some(LLVMFeature::new("sm_110a")),
277            "sm_101f" if major >= 24 => Some(LLVMFeature::new("sm_110f")),
278            s => Some(LLVMFeature::new(s)),
279        },
280        // Filter out features that are not supported by the current LLVM version
281        Arch::PowerPC | Arch::PowerPC64 => match s {
282            "power8-crypto" => Some(LLVMFeature::new("crypto")),
283            s => Some(LLVMFeature::new(s)),
284        },
285        Arch::RiscV32 | Arch::RiscV64 => match s {
286            // Filter out Rust-specific *virtual* target feature
287            "zkne_or_zknd" => None,
288            s => Some(LLVMFeature::new(s)),
289        },
290        Arch::Sparc | Arch::Sparc64 => match s {
291            "leoncasa" => Some(LLVMFeature::new("hasleoncasa")),
292            s => Some(LLVMFeature::new(s)),
293        },
294        Arch::Wasm32 | Arch::Wasm64 => match s {
295            "gc" if major < 22 => None,
296            s => Some(LLVMFeature::new(s)),
297        },
298        Arch::X86 | Arch::X86_64 => {
299            match s {
300                "sse4.2" => Some(LLVMFeature::with_dependencies(
301                    "sse4.2",
302                    {
    let count = 0usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push(TargetFeatureFoldStrength::EnableOnly("crc32"));
        vec
    } else {
        ::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                    [TargetFeatureFoldStrength::EnableOnly("crc32")])))
    }
}smallvec![TargetFeatureFoldStrength::EnableOnly("crc32")],
303                )),
304                "pclmulqdq" => Some(LLVMFeature::new("pclmul")),
305                "rdrand" => Some(LLVMFeature::new("rdrnd")),
306                "bmi1" => Some(LLVMFeature::new("bmi")),
307                "cmpxchg16b" => Some(LLVMFeature::new("cx16")),
308                "lahfsahf" => Some(LLVMFeature::new("sahf")),
309                // Enable the evex512 target feature if an avx512 target feature is enabled.
310                s if s.starts_with("avx512") && major < 22 => Some(LLVMFeature::with_dependencies(
311                    s,
312                    {
    let count = 0usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push(TargetFeatureFoldStrength::EnableOnly("evex512"));
        vec
    } else {
        ::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                    [TargetFeatureFoldStrength::EnableOnly("evex512")])))
    }
}smallvec![TargetFeatureFoldStrength::EnableOnly("evex512")],
313                )),
314                "avx10.1" if major < 22 => Some(LLVMFeature::new("avx10.1-512")),
315                "avx10.2" if major < 22 => Some(LLVMFeature::new("avx10.2-512")),
316                "apxf" => Some(LLVMFeature::with_dependencies(
317                    "egpr",
318                    {
    let count =
        0usize + 1usize + 1usize + 1usize + 1usize + 1usize + 1usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push(TargetFeatureFoldStrength::Both("push2pop2"));
        vec.push(TargetFeatureFoldStrength::Both("ppx"));
        vec.push(TargetFeatureFoldStrength::Both("ndd"));
        vec.push(TargetFeatureFoldStrength::Both("ccmp"));
        vec.push(TargetFeatureFoldStrength::Both("cf"));
        vec.push(TargetFeatureFoldStrength::Both("nf"));
        vec.push(TargetFeatureFoldStrength::Both("zu"));
        vec
    } else {
        ::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                    [TargetFeatureFoldStrength::Both("push2pop2"),
                            TargetFeatureFoldStrength::Both("ppx"),
                            TargetFeatureFoldStrength::Both("ndd"),
                            TargetFeatureFoldStrength::Both("ccmp"),
                            TargetFeatureFoldStrength::Both("cf"),
                            TargetFeatureFoldStrength::Both("nf"),
                            TargetFeatureFoldStrength::Both("zu")])))
    }
}smallvec![
319                        TargetFeatureFoldStrength::Both("push2pop2"),
320                        TargetFeatureFoldStrength::Both("ppx"),
321                        TargetFeatureFoldStrength::Both("ndd"),
322                        TargetFeatureFoldStrength::Both("ccmp"),
323                        TargetFeatureFoldStrength::Both("cf"),
324                        TargetFeatureFoldStrength::Both("nf"),
325                        TargetFeatureFoldStrength::Both("zu"),
326                    ],
327                )),
328                s => Some(LLVMFeature::new(s)),
329            }
330        }
331        _ => Some(LLVMFeature::new(s)),
332    }
333}
334
335/// Used to generate cfg variables and apply features.
336/// Must express features in the way Rust understands them.
337///
338/// We do not have to worry about RUSTC_SPECIFIC_FEATURES here, those are handled outside codegen.
339pub(crate) fn target_config(sess: &Session) -> TargetConfig {
340    let target_machine = create_informational_target_machine(sess, true);
341
342    let internal_target_features = internal_target_features(
343        sess,
344        |feature| {
345            to_llvm_features(sess, feature)
346                .map(|f| SmallVec::<[&str; 2]>::from_iter(f.into_iter()))
347                .unwrap_or_default()
348        },
349        |feature| {
350            // This closure determines whether the target CPU has the feature according to LLVM. We
351            // do *not* consider the `-Ctarget-feature`s here, as that will be handled later in
352            // `internal_target_features`.
353            if let Some(feat) = to_llvm_features(sess, feature) {
354                // All the LLVM features this expands to must be enabled.
355                for llvm_feature in feat {
356                    let cstr = SmallCStr::new(llvm_feature);
357                    // `LLVMRustHasFeature` is moderately expensive. On targets with many
358                    // features (e.g. x86) these calls take a non-trivial fraction of runtime
359                    // when compiling very small programs.
360                    if !unsafe { llvm::LLVMRustHasFeature(target_machine.raw(), cstr.as_ptr()) } {
361                        return false;
362                    }
363                }
364                true
365            } else {
366                false
367            }
368        },
369    );
370
371    let mut cfg = TargetConfig {
372        internal_target_features,
373        has_reliable_f16: true,
374        has_reliable_f16_math: true,
375        has_reliable_f128: true,
376        has_reliable_f128_math: true,
377    };
378
379    update_target_reliable_float_cfg(sess, &mut cfg);
380    cfg
381}
382
383/// Determine whether or not experimental float types are reliable based on known bugs.
384fn update_target_reliable_float_cfg(sess: &Session, cfg: &mut TargetConfig) {
385    let target_arch = &sess.target.arch;
386    let target_os = &sess.target.options.os;
387    let target_env = &sess.target.options.env;
388    let target_abi = &sess.target.options.cfg_abi;
389    let target_pointer_width = sess.target.pointer_width;
390    let version = get_version();
391    let (major, _, _) = version;
392
393    cfg.has_reliable_f16 = match (target_arch, target_os) {
394        // Unsupported <https://github.com/llvm/llvm-project/issues/94434> (fixed in llvm22)
395        (Arch::Arm64EC, _) if major < 22 => false,
396        // MinGW ABI bugs <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=115054> resolved in GCC 16
397        // but our toolchain hasn't been updated.
398        (Arch::X86_64, Os::Windows) if *target_env == Env::Gnu && *target_abi != CfgAbi::Llvm => {
399            false
400        }
401        // Infinite recursion <https://github.com/llvm/llvm-project/issues/97981>
402        (Arch::CSky, _) if major < 22 => false, // (fixed in llvm22)
403        (Arch::PowerPC | Arch::PowerPC64, _) if major < 22 => false, // (fixed in llvm22)
404        (Arch::Sparc | Arch::Sparc64, _) if major < 22 => false, // (fixed in llvm22)
405        (Arch::Wasm32 | Arch::Wasm64, _) if major < 22 => false, // (fixed in llvm22)
406        // `f16` support only requires that symbols converting to and from `f32` are available. We
407        // provide these in `compiler-builtins`, so `f16` should be available on all platforms that
408        // do not have other ABI issues or LLVM crashes.
409        _ => true,
410    };
411
412    cfg.has_reliable_f128 = match (target_arch, target_os) {
413        // Unsupported https://github.com/llvm/llvm-project/issues/121122
414        (Arch::AmdGpu, _) => false,
415        (Arch::Arm64EC, _) if major < 23 => false, // (fixed in llvm23)
416        // Selection bug <https://github.com/llvm/llvm-project/issues/95471>. This issue is closed
417        // but basic math still does not work.
418        (Arch::Nvptx64, _) => false,
419        // ABI bugs <https://github.com/rust-lang/rust/issues/125109> et al. (full
420        // list at <https://github.com/rust-lang/rust/issues/116909>)
421        (Arch::PowerPC | Arch::PowerPC64, _) => false,
422        // ABI unsupported  <https://github.com/llvm/llvm-project/issues/41838> (fixed in llvm22)
423        (Arch::Sparc, _) if major < 22 => false,
424        // MinGW ABI bugs <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=115054> (fixed in llvm23)
425        (Arch::X86_64, Os::Windows)
426            if *target_env == Env::Gnu && *target_abi != CfgAbi::Llvm && major < 23 =>
427        {
428            false
429        }
430        // There are no known problems on other platforms, so the only requirement is that symbols
431        // are available. `compiler-builtins` provides all symbols required for core `f128`
432        // support, so this should work for everything else.
433        _ => true,
434    };
435
436    // Assume that working `f16` means working `f16` math for most platforms, since
437    // operations just go through `f32`.
438    cfg.has_reliable_f16_math = cfg.has_reliable_f16;
439
440    cfg.has_reliable_f128_math = match (target_arch, target_os) {
441        // LLVM lowers `fp128` math to `long double` symbols even on platforms where
442        // `long double` is not IEEE binary128. See
443        // <https://github.com/llvm/llvm-project/issues/44744>.
444        //
445        // This rules out anything that doesn't have `long double` = `binary128`; <= 32 bits
446        // (ld is `f64`), anything other than Linux (Windows and MacOS use `f64`), and `x86`
447        // (ld is 80-bit extended precision).
448        //
449        // musl does not implement the symbols required for f128 math at all.
450        _ if *target_env == Env::Musl => false,
451        (Arch::X86_64, _) => false,
452        (_, Os::Linux) if target_pointer_width == 64 => true,
453        _ => false,
454    } && cfg.has_reliable_f128;
455}
456
457pub(crate) fn print_version() {
458    let (major, minor, patch) = get_version();
459    {
    ::std::io::_print(format_args!("LLVM version: {0}.{1}.{2}\n", major,
            minor, patch));
};println!("LLVM version: {major}.{minor}.{patch}");
460}
461
462pub(crate) fn get_version() -> (u32, u32, u32) {
463    // Can be called without initializing LLVM
464    unsafe {
465        let mut llvm_major = 0;
466        let mut llvm_minor = 0;
467        let mut llvm_patch = 0;
468        llvm::LLVMGetVersion(&mut llvm_major, &mut llvm_minor, &mut llvm_patch);
469        (llvm_major, llvm_minor, llvm_patch)
470    }
471}
472
473pub(crate) fn print_passes() {
474    // Can be called without initializing LLVM
475    unsafe {
476        llvm::LLVMRustPrintPasses();
477    }
478}
479
480fn llvm_target_features(tm: &llvm::TargetMachine) -> Vec<(&str, &str)> {
481    let len = unsafe { llvm::LLVMRustGetTargetFeaturesCount(tm) };
482    let mut ret = Vec::with_capacity(len);
483    for i in 0..len {
484        unsafe {
485            let mut feature = ptr::null();
486            let mut desc = ptr::null();
487            llvm::LLVMRustGetTargetFeature(tm, i, &mut feature, &mut desc);
488            if feature.is_null() || desc.is_null() {
489                ::rustc_middle::util::bug::bug_fmt(format_args!("LLVM returned a `null` target feature string"));bug!("LLVM returned a `null` target feature string");
490            }
491            let feature = CStr::from_ptr(feature).to_str().unwrap_or_else(|e| {
492                ::rustc_middle::util::bug::bug_fmt(format_args!("LLVM returned a non-utf8 feature string: {0}",
        e));bug!("LLVM returned a non-utf8 feature string: {}", e);
493            });
494            let desc = CStr::from_ptr(desc).to_str().unwrap_or_else(|e| {
495                ::rustc_middle::util::bug::bug_fmt(format_args!("LLVM returned a non-utf8 feature string: {0}",
        e));bug!("LLVM returned a non-utf8 feature string: {}", e);
496            });
497            ret.push((feature, desc));
498        }
499    }
500    ret
501}
502
503pub(crate) fn print(req: &PrintRequest, out: &mut String, sess: &Session) {
504    require_inited();
505    let tm = create_informational_target_machine(sess, false);
506    match req.kind {
507        PrintKind::TargetCPUs => print_target_cpus(sess, tm.raw(), out),
508        PrintKind::TargetFeatures => print_target_features(sess, tm.raw(), out),
509        _ => ::rustc_middle::util::bug::bug_fmt(format_args!("rustc_codegen_llvm can\'t handle print request: {0:?}",
        req))bug!("rustc_codegen_llvm can't handle print request: {:?}", req),
510    }
511}
512
513fn print_target_cpus(sess: &Session, tm: &llvm::TargetMachine, out: &mut String) {
514    let cpu_names = llvm::build_string(|s| unsafe {
515        llvm::LLVMRustPrintTargetCPUs(&tm, s);
516    })
517    .unwrap();
518
519    struct Cpu<'a> {
520        cpu_name: &'a str,
521        remark: String,
522    }
523    // Compare CPU against current target to label the default.
524    let target_cpu = handle_native(&sess.target.cpu);
525    let make_remark = |cpu_name| {
526        if cpu_name == target_cpu {
527            // FIXME(#132514): This prints the LLVM target string, which can be
528            // different from the Rust target string. Is that intended?
529            let target = &sess.target.llvm_target;
530            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" - This is the default target CPU for the current build target (currently {0}).",
                target))
    })format!(
531                " - This is the default target CPU for the current build target (currently {target})."
532            )
533        } else {
534            "".to_owned()
535        }
536    };
537    let mut cpus = cpu_names
538        .lines()
539        .filter(|cpu_name| {
540            !sess.target.unsupported_cpus.contains(&std::borrow::Cow::Borrowed(*cpu_name))
541        })
542        .map(|cpu_name| Cpu { cpu_name, remark: make_remark(cpu_name) })
543        .collect::<VecDeque<_>>();
544
545    // Only print the "native" entry when host and target are the same arch,
546    // since otherwise it could be wrong or misleading.
547    // Also do not print it if `requires_consistent_cpu` is set, because in this case
548    // "native" would be rejected.
549    if sess.host.arch == sess.target.arch && !sess.target.requires_consistent_cpu {
550        let host = get_host_cpu_name();
551        cpus.push_front(Cpu {
552            cpu_name: NATIVE_CPU,
553            remark: ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" - Select the CPU of the current host (currently {0}).",
                host))
    })format!(" - Select the CPU of the current host (currently {host})."),
554        });
555    }
556
557    let max_name_width = cpus.iter().map(|cpu| cpu.cpu_name.len()).max().unwrap_or(0);
558    out.write_fmt(format_args!("Available CPUs for this target:\n"))writeln!(out, "Available CPUs for this target:").unwrap();
559    for Cpu { cpu_name, remark } in cpus {
560        // Only pad the CPU name if there's a remark to print after it.
561        let width = if remark.is_empty() { 0 } else { max_name_width };
562        out.write_fmt(format_args!("    {0:<1$}{2}\n", cpu_name, width, remark))writeln!(out, "    {cpu_name:<width$}{remark}").unwrap();
563    }
564}
565
566fn print_target_features(sess: &Session, tm: &llvm::TargetMachine, out: &mut String) {
567    let mut llvm_target_features = llvm_target_features(tm);
568    let mut known_llvm_target_features = FxHashSet::<&'static str>::default();
569    let mut rustc_target_features = sess
570        .target
571        .rust_target_features()
572        .iter()
573        .filter_map(|(feature, gate, _implied)| {
574            if !gate.in_cfg() {
575                // Only list (experimentally) supported features.
576                return None;
577            }
578            // LLVM asserts that these are sorted. LLVM and Rust both use byte comparison for these
579            // strings.
580            let llvm_feature = to_llvm_features(sess, *feature)?.llvm_feature_name;
581            let desc =
582                match llvm_target_features.binary_search_by_key(&llvm_feature, |(f, _d)| f).ok() {
583                    Some(index) => {
584                        known_llvm_target_features.insert(llvm_feature);
585                        llvm_target_features[index].1
586                    }
587                    None => "",
588                };
589
590            Some((*feature, desc))
591        })
592        .collect::<Vec<_>>();
593
594    // Since we add this at the end ...
595    rustc_target_features.extend_from_slice(&[(
596        "crt-static",
597        "Enables C Run-time Libraries to be statically linked",
598    )]);
599    // ... we need to sort the list again.
600    rustc_target_features.sort();
601
602    llvm_target_features.retain(|(f, _d)| !known_llvm_target_features.contains(f));
603
604    let max_feature_len = llvm_target_features
605        .iter()
606        .chain(rustc_target_features.iter())
607        .map(|(feature, _desc)| feature.len())
608        .max()
609        .unwrap_or(0);
610
611    out.write_fmt(format_args!("Features supported by rustc for this target:\n"))writeln!(out, "Features supported by rustc for this target:").unwrap();
612    for (feature, desc) in &rustc_target_features {
613        out.write_fmt(format_args!("    {0:1$} - {2}.\n", feature, max_feature_len,
        desc))writeln!(out, "    {feature:max_feature_len$} - {desc}.").unwrap();
614    }
615    out.write_fmt(format_args!("\nCode-generation features supported by LLVM for this target:\n"))writeln!(out, "\nCode-generation features supported by LLVM for this target:").unwrap();
616    for (feature, desc) in &llvm_target_features {
617        out.write_fmt(format_args!("    {0:1$} - {2}.\n", feature, max_feature_len,
        desc))writeln!(out, "    {feature:max_feature_len$} - {desc}.").unwrap();
618    }
619    if llvm_target_features.is_empty() {
620        out.write_fmt(format_args!("    Target features listing is not supported by this LLVM version.\n"))writeln!(out, "    Target features listing is not supported by this LLVM version.")
621            .unwrap();
622    }
623    out.write_fmt(format_args!("\nUse +feature to enable a feature, or -feature to disable it.\n"))writeln!(out, "\nUse +feature to enable a feature, or -feature to disable it.").unwrap();
624    out.write_fmt(format_args!("For example, rustc -C target-cpu=mycpu -C target-feature=+feature1,-feature2\n\n"))writeln!(out, "For example, rustc -C target-cpu=mycpu -C target-feature=+feature1,-feature2\n")
625        .unwrap();
626    out.write_fmt(format_args!("Code-generation features cannot be used in cfg or #[target_feature],\n"))writeln!(out, "Code-generation features cannot be used in cfg or #[target_feature],").unwrap();
627    out.write_fmt(format_args!("and may be renamed or removed in a future version of LLVM or rustc.\n\n"))writeln!(out, "and may be renamed or removed in a future version of LLVM or rustc.\n").unwrap();
628}
629
630/// Returns the host CPU name, according to LLVM.
631fn get_host_cpu_name() -> &'static str {
632    let mut len = 0;
633    // SAFETY: The underlying C++ global function returns a `StringRef` that
634    // isn't tied to any particular backing buffer, so it must be 'static.
635    let slice: &'static [u8] = unsafe {
636        let ptr = llvm::LLVMRustGetHostCPUName(&mut len);
637        if !!ptr.is_null() {
    ::core::panicking::panic("assertion failed: !ptr.is_null()")
};assert!(!ptr.is_null());
638        slice::from_raw_parts(ptr, len)
639    };
640    str::from_utf8(slice).expect("host CPU name should be UTF-8")
641}
642
643/// If the given string is `"native"`, returns the host CPU name according to
644/// LLVM. Otherwise, the string is returned as-is.
645fn handle_native(cpu_name: &str) -> &str {
646    match cpu_name {
647        NATIVE_CPU => get_host_cpu_name(),
648        _ => cpu_name,
649    }
650}
651
652pub(crate) fn target_cpu(sess: &Session) -> &str {
653    let cpu_name = sess.opts.cg.target_cpu.as_deref().unwrap_or_else(|| &sess.target.cpu);
654    handle_native(cpu_name)
655}
656
657/// The target features for compiler flags other than `-Ctarget-features`.
658fn llvm_features_by_flags(sess: &Session, features: &mut Vec<String>) {
659    if wants_wasm_eh(sess) && sess.panic_strategy() == PanicStrategy::Unwind {
660        features.push("+exception-handling".into());
661    }
662
663    target_features::retpoline_features_by_flags(sess, features);
664    target_features::sanitizer_features_by_flags(sess, features);
665
666    // -Zfixed-x18
667    if sess.opts.unstable_opts.fixed_x18 {
668        if sess.target.arch != Arch::AArch64 {
669            sess.dcx()
670                .emit_fatal(diagnostics::FixedX18InvalidArch { arch: sess.target.arch.desc() });
671        } else {
672            features.push("+reserve-x18".into());
673        }
674    }
675}
676
677/// The list of LLVM features computed from CLI flags (`-Ctarget-cpu`, `-Ctarget-feature`,
678/// `--target` and similar).
679///
680/// If `for_cfg` is `true` then we are assembling the feature list for the purpose of populating
681/// [`rustc_codegen_ssa::TargetConfig`] based on what LLVM actually enables in this configuration.
682/// `-Ctarget-feature` should be ignored in that case since it is already processed separately.
683pub(crate) fn global_llvm_features(sess: &Session, for_cfg: bool) -> Vec<String> {
684    // Features that come earlier are overridden by conflicting features later in the string.
685    // Typically we'll want more explicit settings to override the implicit ones, so:
686    //
687    // * Features from -Ctarget-cpu=*; are overridden by [^1]
688    // * Features implied by --target; are overridden by
689    // * Features from -Ctarget-feature; are overridden by
690    // * function specific features.
691    //
692    // [^1]: target-cpu=native is handled here, other target-cpu values are handled implicitly
693    // through LLVM TargetMachine implementation.
694    //
695    // FIXME(nagisa): it isn't clear what's the best interaction between features implied by
696    // `-Ctarget-cpu` and `--target` are. On one hand, you'd expect CLI arguments to always
697    // override anything that's implicit, so e.g. when there's no `--target` flag, features implied
698    // the host target are overridden by `-Ctarget-cpu=*`. On the other hand, what about when both
699    // `--target` and `-Ctarget-cpu=*` are specified? Both then imply some target features and both
700    // flags are specified by the user on the CLI. It isn't as clear-cut which order of precedence
701    // should be taken in cases like these.
702    let mut features = ::alloc::vec::Vec::new()vec![];
703
704    // -Ctarget-cpu=native
705    match sess.opts.cg.target_cpu {
706        Some(ref s) if s == NATIVE_CPU => {
707            // We have already figured out the actual CPU name with `LLVMRustGetHostCPUName` and set
708            // that for LLVM, so the features implied by that CPU name will be available everywhere.
709            // However, that is not sufficient: e.g. `skylake` alone is not sufficient to tell if
710            // some of the instructions are available or not. So we have to also explicitly ask for
711            // the exact set of features available on the host, and enable all of them.
712            let features_string = unsafe {
713                let ptr = llvm::LLVMGetHostCPUFeatures();
714                let features_string = if !ptr.is_null() {
715                    CStr::from_ptr(ptr)
716                        .to_str()
717                        .unwrap_or_else(|e| {
718                            ::rustc_middle::util::bug::bug_fmt(format_args!("LLVM returned a non-utf8 features string: {0}",
        e));bug!("LLVM returned a non-utf8 features string: {}", e);
719                        })
720                        .to_owned()
721                } else {
722                    ::rustc_middle::util::bug::bug_fmt(format_args!("could not allocate host CPU features, LLVM returned a `null` string"));bug!("could not allocate host CPU features, LLVM returned a `null` string");
723                };
724
725                llvm::LLVMDisposeMessage(ptr);
726
727                features_string
728            };
729            if !features_string.is_empty() {
730                features.extend(features_string.split(',').map(String::from));
731            }
732        }
733        Some(_) | None => {}
734    };
735
736    let mut extend_backend_features = |feature: &str, enable: bool| {
737        let enable_disable = if enable { '+' } else { '-' };
738        // We run through `to_llvm_features` when
739        // passing requests down to LLVM. This means that all in-language
740        // features also work on the command line instead of having two
741        // different names when the LLVM name and the Rust name differ.
742        let Some(llvm_feature) = to_llvm_features(sess, feature) else { return };
743
744        features.extend(
745            std::iter::once(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}", enable_disable,
                llvm_feature.llvm_feature_name))
    })format!("{}{}", enable_disable, llvm_feature.llvm_feature_name)).chain(
746                llvm_feature.dependencies.into_iter().filter_map(move |feat| {
747                    match (enable, feat) {
748                        (_, TargetFeatureFoldStrength::Both(f))
749                        | (true, TargetFeatureFoldStrength::EnableOnly(f)) => {
750                            Some(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}", enable_disable, f))
    })format!("{enable_disable}{f}"))
751                        }
752                        _ => None,
753                    }
754                }),
755            ),
756        );
757    };
758
759    // Features implied by an implicit or explicit `--target`.
760    target_features::target_spec_to_backend_features(sess, &mut extend_backend_features);
761
762    // -Ctarget-features. Skipped for `cfg` as there we parse -Ctarget-features directly instead of
763    // going via an LLVM target machine (which avoids accidentally picking up LLVM-level target
764    // feature implications that we do not want).
765    if !for_cfg {
766        target_features::flag_to_backend_features(sess, extend_backend_features);
767    }
768
769    // `-C` flags that map to LLVM target features.
770    // We need to include them even with `only_base_features` as this is used to populate
771    // `sess.internal_target_features` where we very much want them to be present (e.g. the inline
772    // asm logic uses that to check which registers may be used).
773    llvm_features_by_flags(sess, &mut features);
774
775    // `-Zllvm-target-features`, all the way at the end to overwrite everything.
776    // Should be picked up by `cfg` (e.g. if someone enables AVX this way).
777    for feature in sess.opts.unstable_opts.llvm_target_feature.split(',') {
778        if feature.is_empty() {
779            continue;
780        }
781        if feature.starts_with('+') || feature.starts_with('-') {
782            features.push(feature.to_owned());
783        } else {
784            // LLVM seems to silently ignore entries without leading `+`/`-`. Let's emit a warning
785            // to avoid confusion. But only emit this warning once, under `for_cfg`.
786            if for_cfg {
787                sess.dcx().emit_warn(diagnostics::UnknownLlvmTargetFeaturePrefix { feature });
788            }
789        }
790    }
791
792    features
793}
794
795pub(crate) fn tune_cpu(sess: &Session) -> Option<&str> {
796    let name = sess.opts.unstable_opts.tune_cpu.as_ref()?;
797    Some(handle_native(name))
798}
799
800pub(crate) fn target_has_mnemonic(sess: &Session, mnemonic: &str) -> bool {
801    require_inited();
802    let tm = create_informational_target_machine(sess, false);
803    let cstr = SmallCStr::new(mnemonic);
804    unsafe { llvm::LLVMRustTargetHasMnemonic(tm.raw(), cstr.as_ptr()) }
805}