1use std::borrow::Cow;
2use std::collections::VecDeque;
3use std::ffi::{CStr, CString};
4use std::fmt::Write;
5use std::path::Path;
6use std::sync::Once;
7use std::{ptr, slice, str};
89use libc::c_int;
10use rustc_abi::Endian;
11use rustc_codegen_ssa::back::versioned_llvm_target;
12use rustc_codegen_ssa::base::wants_wasm_eh;
13use rustc_codegen_ssa::target_features::rust_target_features;
14use rustc_codegen_ssa::{TargetConfig, target_features};
15use rustc_data_structures::fx::FxHashSet;
16use rustc_data_structures::small_c_str::SmallCStr;
17use rustc_fs_util::path_to_c_string;
18use rustc_session::config::{NATIVE_CPU, PrintKind, PrintRequest};
19use rustc_session::{EarlySession, Session};
20use rustc_span::{bug, sym};
21use rustc_target::spec::{
22Arch, CfgAbi, Env, MergeFunctions, Os, PanicStrategy, SmallDataThresholdSupport, Target,
23};
24use smallvec::{SmallVec, smallvec};
2526use crate::back::owned_mc_subtarget_info::OwnedMCSubtargetInfo;
27use crate::back::write::{create_informational_target_machine, llvm_err};
28use crate::{diagnostics, llvm};
2930static INIT: Once = Once::new();
3132pub(crate) fn init(sess: &EarlySession) {
33unsafe {
34// Before we touch LLVM, make sure that multithreading is enabled.
35if !llvm::LLVMIsMultithreaded().is_true() {
36::rustc_span::macros::bug_impl(None,
format_args!("LLVM compiled without support for threads"),
Location::caller());bug!("LLVM compiled without support for threads");
37 }
38INIT.call_once(|| {
39configure_llvm(sess);
40 });
41 }
42}
4344fn require_inited() {
45if !INIT.is_completed() {
46::rustc_span::macros::bug_impl(None, format_args!("LLVM is not initialized"),
Location::caller());bug!("LLVM is not initialized");
47 }
48}
4950unsafe fn configure_llvm(sess: &EarlySession) {
51let n_args = sess.opts.cg.llvm_args.len() + sess.target.llvm_args.len();
52let mut llvm_c_strs = Vec::with_capacity(n_args + 1);
53let mut llvm_args = Vec::with_capacity(n_args + 1);
5455// Check to ensure we're running against the correct LLVM version.
56unsafe {
57let (llvm_major, llvm_minor, llvm_patch) = get_version();
58let expected_version = llvm::LLVMRustVersionMajor();
59if llvm_major != expected_version {
60sess.dcx().emit_fatal(diagnostics::LlvmVersionMismatch {
61expected_version,
62llvm_major,
63llvm_minor,
64llvm_patch,
65 dll_loc: &match rustc_session::filesearch::dll_path(llvm::LLVMGetVersionas *mut _)
66 {
67Ok(path) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" at {0}", path.display()))
})format!(" at {}", path.display()),
68Err(_) => String::new(),
69 },
70 })
71 }
72 }
7374unsafe {
75 llvm::LLVMRustInstallErrorHandlers();
76 }
77// On Windows, an LLVM assertion will open an Abort/Retry/Ignore dialog
78 // box for the purpose of launching a debugger. However, on CI this will
79 // cause it to hang until it times out, which can take several hours.
80if std::env::var_os("CI").is_some() {
81unsafe {
82 llvm::LLVMRustDisableSystemDialogsOnCrash();
83 }
84 }
8586fn llvm_arg_to_arg_name(full_arg: &str) -> &str {
87full_arg.trim().split(|c: char| c == '=' || c.is_whitespace()).next().unwrap_or("")
88 }
8990let cg_opts = sess.opts.cg.llvm_args.iter().map(AsRef::as_ref);
91let tg_opts = sess.target.llvm_args.iter().map(AsRef::as_ref);
92// Target-spec args are passed to LLVM before user `-Cllvm-args`. LLVM's
93 // `cl::opt` parser is last-wins, so this lets `-Cllvm-args=...` override
94 // a value already set in the target spec (e.g. `-wasm-use-legacy-eh`).
95let sess_args = tg_opts.chain(cg_opts);
9697let user_specified_args: FxHashSet<_> =
98sess_args.clone().map(llvm_arg_to_arg_name).filter(|s| !s.is_empty()).collect();
99100 {
101// This adds the given argument to LLVM. Unless `force` is true
102 // user specified arguments are *not* overridden.
103let mut add = |arg: &str, force: bool| {
104if force || !user_specified_args.contains(llvm_arg_to_arg_name(arg)) {
105let s = CString::new(arg).unwrap();
106llvm_args.push(s.as_ptr());
107llvm_c_strs.push(s);
108 }
109 };
110// Set the llvm "program name" to make usage and invalid argument messages more clear.
111add("rustc -Cllvm-args=\"...\" with", true);
112if sess.opts.unstable_opts.time_llvm_passes {
113add("-time-passes", false);
114 }
115if sess.opts.unstable_opts.print_llvm_passes {
116add("-debug-pass=Structure", false);
117 }
118if sess.target.generate_arange_section
119 && !sess.opts.unstable_opts.no_generate_arange_section
120 {
121add("-generate-arange-section", false);
122 }
123124match sess.merge_functions() {
125 MergeFunctions::Disabled | MergeFunctions::Trampolines => {}
126 MergeFunctions::Aliases => {
127add("-mergefunc-use-aliases", false);
128 }
129 }
130131if get_version() < (24, 0, 0) && wants_wasm_eh(&sess.target) {
132add("-wasm-enable-eh", false);
133 }
134135// HACK(eddyb) LLVM inserts `llvm.assume` calls to preserve align attributes
136 // during inlining. Unfortunately these may block other optimizations.
137add("-preserve-alignment-assumptions-during-inlining=false", false);
138139// Use non-zero `import-instr-limit` multiplier for cold callsites.
140add("-import-cold-multiplier=0.1", false);
141142// LLVM has an "auto-upgrade" mechanism: newer LLVM versions can handle bitcode (needed for
143 // LTO) produced by older LLVM versions. If debuginfo is present in the bitcode, the
144 // debuginfo part of this mechanism (`UpgradeDebugInfo`) will run `verifyModule`, an
145 // expensive check which (oddly enough) verifies all parts of the bitcode. On verification
146 // failure, LLVM will warn in some cases and abort in others.
147 //
148 // The following flag tells LLVM to skip the debuginfo-triggered bitcode verification step.
149 // This is ok for Rust because rlibs involved in Rust compilation will always be produced
150 // by the same LLVM version. (Except possibly in very strange scenarios, such as mixing
151 // rlibs from different builds of the same rustc version linked against different LLVMs,
152 // and that would only cause problems if those different LLVMs used different debuginfo
153 // formats.)
154 //
155 // This is a small compile-time win for (non-default) release + debuginfo configurations.
156 // The protection against malformed bitcode is also eliminated in that configuration, but
157 // since the bitcode verifier doesn't run in other, more common configurations, this hardly
158 // matters.
159 //
160 // Note that Rust was a motivating example in the design of this flag. See
161 // https://reviews.llvm.org/D143229.
162if get_version() >= (24, 0, 0) {
163add("-auto-upgrade-debug-info=false", false);
164 } else {
165add("-disable-auto-upgrade-debug-info", false);
166 }
167168if sess.print_llvm_stats() || sess.print_llvm_stats_json().is_some() {
169add("-stats", false);
170 }
171172for arg in sess_args {
173 add(arg, true);
174 }
175176// Set up the small-data optimization limit for architectures that use
177 // an LLVM argument to control this.
178if let Some(threshold) = sess.opts.unstable_opts.small_data_threshold
179 && let SmallDataThresholdSupport::LlvmArg(arg) =
180sess.target.small_data_threshold_support()
181 {
182add(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("--{0}={1}", arg, threshold))
})format!("--{arg}={threshold}"), false);
183 }
184 }
185186if sess.opts.unstable_opts.llvm_time_trace {
187unsafe { llvm::LLVMRustTimeTraceProfilerInitialize() };
188 }
189190 rustc_llvm::initialize_available_targets();
191192unsafe { llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int, llvm_args.as_ptr()) };
193}
194195pub(crate) fn time_trace_profiler_finish(file_name: &Path) {
196unsafe {
197let file_name = path_to_c_string(file_name);
198 llvm::LLVMRustTimeTraceProfilerFinish(file_name.as_ptr());
199 }
200}
201202enum TargetFeatureFoldStrength<'a> {
203// The feature is only tied when enabling the feature, disabling
204 // this feature shouldn't disable the tied feature.
205EnableOnly(&'a str),
206// The feature is tied for both enabling and disabling this feature.
207Both(&'a str),
208}
209210impl<'a> TargetFeatureFoldStrength<'a> {
211fn as_str(&self) -> &'a str {
212match self {
213 TargetFeatureFoldStrength::EnableOnly(feat) => feat,
214 TargetFeatureFoldStrength::Both(feat) => feat,
215 }
216 }
217}
218219pub(crate) struct LLVMFeature<'a> {
220 llvm_feature_name: &'a str,
221 dependencies: SmallVec<[TargetFeatureFoldStrength<'a>; 1]>,
222}
223224impl<'a> LLVMFeature<'a> {
225fn new(llvm_feature_name: &'a str) -> Self {
226Self { llvm_feature_name, dependencies: SmallVec::new() }
227 }
228229fn with_dependencies(
230 llvm_feature_name: &'a str,
231 dependencies: SmallVec<[TargetFeatureFoldStrength<'a>; 1]>,
232 ) -> Self {
233Self { llvm_feature_name, dependencies }
234 }
235}
236237impl<'a> IntoIteratorfor LLVMFeature<'a> {
238type Item = &'a str;
239type IntoIter = impl Iterator<Item = &'a str>;
240241fn into_iter(self) -> Self::IntoIter {
242let dependencies = self.dependencies.into_iter().map(|feat| feat.as_str());
243 std::iter::once(self.llvm_feature_name).chain(dependencies)
244 }
245}
246247/// Convert a Rust feature name to an LLVM feature name. Returning `None` means the
248/// feature should be skipped, usually because it is not supported by the current
249/// LLVM version.
250///
251/// WARNING: the features after applying `to_llvm_features` must be known
252/// to LLVM or the feature detection code will walk past the end of the feature
253/// array, leading to crashes.
254///
255/// To find a list of LLVM's names, see llvm-project/llvm/lib/Target/{ARCH}/*.td
256/// where `{ARCH}` is the architecture name. Look for instances of `SubtargetFeature`.
257///
258/// Check the current rustc fork of LLVM in the repo at
259/// <https://github.com/rust-lang/llvm-project/>. The commit in use can be found via the
260/// `llvm-project` submodule in <https://github.com/rust-lang/rust/tree/HEAD/src> Though note that
261/// Rust can also be build with an external precompiled version of LLVM which might lead to failures
262/// if the oldest tested / supported LLVM version doesn't yet support the relevant intrinsics.
263pub(crate) fn to_llvm_features<'a>(target: &Target, s: &'a str) -> Option<LLVMFeature<'a>> {
264let (major, _, _) = get_version();
265match target.arch {
266 Arch::AArch64 | Arch::Arm64EC => {
267match s {
268"rcpc2" => Some(LLVMFeature::new("rcpc-immo")),
269"dpb" => Some(LLVMFeature::new("ccpp")),
270"dpb2" => Some(LLVMFeature::new("ccdp")),
271"frintts" => Some(LLVMFeature::new("fptoint")),
272"fcma" => Some(LLVMFeature::new("complxnum")),
273"pmuv3" => Some(LLVMFeature::new("perfmon")),
274"paca" => Some(LLVMFeature::new("pauth")),
275"pacg" => Some(LLVMFeature::new("pauth")),
276"flagm2" => Some(LLVMFeature::new("altnzcv")),
277// Rust ties fp and neon together.
278"neon" => Some(LLVMFeature::with_dependencies(
279"neon",
280{
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")],
281 )),
282// In LLVM neon implicitly enables fp, but we manually enable
283 // neon when a feature only implicitly enables fp
284"fhm" => Some(LLVMFeature::new("fp16fml")),
285"fp16" => Some(LLVMFeature::new("fullfp16")),
286// Filter out features that are not supported by the current LLVM version
287"fpmr" => None, // only existed in 18
288 // Withdrawn by ARM; removed from LLVM in 22
289"tme" => None,
290 s => Some(LLVMFeature::new(s)),
291 }
292 }
293 Arch::Arm => match s {
294"fp16" => Some(LLVMFeature::new("fullfp16")),
295 s => Some(LLVMFeature::new(s)),
296 },
297 Arch::Nvptx64 => match s {
298"ptx91" | "ptx92" | "ptx93" if major < 23 => None,
299"sm_101" if major >= 24 => Some(LLVMFeature::new("sm_110")),
300"sm_101a" if major >= 24 => Some(LLVMFeature::new("sm_110a")),
301"sm_101f" if major >= 24 => Some(LLVMFeature::new("sm_110f")),
302 s => Some(LLVMFeature::new(s)),
303 },
304// Filter out features that are not supported by the current LLVM version
305Arch::PowerPC | Arch::PowerPC64 => match s {
306"power8-crypto" => Some(LLVMFeature::new("crypto")),
307 s => Some(LLVMFeature::new(s)),
308 },
309 Arch::RiscV32 | Arch::RiscV64 => match s {
310// Filter out Rust-specific *virtual* target feature
311"zkne_or_zknd" => None,
312 s => Some(LLVMFeature::new(s)),
313 },
314 Arch::Sparc | Arch::Sparc64 => match s {
315"leoncasa" => Some(LLVMFeature::new("hasleoncasa")),
316 s => Some(LLVMFeature::new(s)),
317 },
318 Arch::X86 | Arch::X86_64 => match s {
319"sse4.2" => Some(LLVMFeature::with_dependencies(
320"sse4.2",
321{
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")],
322 )),
323"pclmulqdq" => Some(LLVMFeature::new("pclmul")),
324"rdrand" => Some(LLVMFeature::new("rdrnd")),
325"bmi1" => Some(LLVMFeature::new("bmi")),
326"cmpxchg16b" => Some(LLVMFeature::new("cx16")),
327"lahfsahf" => Some(LLVMFeature::new("sahf")),
328"apxf" => Some(LLVMFeature::with_dependencies(
329"egpr",
330{
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![
331 TargetFeatureFoldStrength::Both("push2pop2"),
332 TargetFeatureFoldStrength::Both("ppx"),
333 TargetFeatureFoldStrength::Both("ndd"),
334 TargetFeatureFoldStrength::Both("ccmp"),
335 TargetFeatureFoldStrength::Both("cf"),
336 TargetFeatureFoldStrength::Both("nf"),
337 TargetFeatureFoldStrength::Both("zu"),
338 ],
339 )),
340 s => Some(LLVMFeature::new(s)),
341 },
342_ => Some(LLVMFeature::new(s)),
343 }
344}
345346/// Extends the given list of target features with the LLVM target features that correspond
347/// to the given Rust target feature.
348/// This is written in curried style (returning a closure) so that it can be easily used with
349/// `target_spec_to_backend_features` and `flag_to_backend_features`.
350pub(crate) fn extend_with_llvm_features_for_rust_feature(
351 sess: &EarlySession,
352 llvm_features: &mut Vec<String>,
353) -> impl FnMut(/* rust_feature */ &str, /* enable */ bool) {
354 |rust_feature, enable| {
355let enable_disable = if enable { '+' } else { '-' };
356// We run through `to_llvm_features` when
357 // passing requests down to LLVM. This means that all in-language
358 // features also work on the command line instead of having two
359 // different names when the LLVM name and the Rust name differ.
360let Some(llvm_feature) = to_llvm_features(&sess.target, rust_feature) else { return };
361362// Add the feature itself.
363llvm_features.push(::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));
364// Add its dependencies.
365llvm_features.extend(llvm_feature.dependencies.into_iter().filter_map(move |feat| match (
366enable, feat,
367 ) {
368 (_, TargetFeatureFoldStrength::Both(f))
369 | (true, TargetFeatureFoldStrength::EnableOnly(f)) => {
370Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}", enable_disable, f))
})format!("{enable_disable}{f}"))
371 }
372_ => None,
373 }));
374 }
375}
376377/// Used to generate cfg variables and apply features.
378/// Must express features in the way Rust understands them.
379///
380/// We do not have to worry about RUSTC_SPECIFIC_FEATURES here, those are handled outside codegen.
381pub(crate) fn target_config(sess: &EarlySession, global_llvm_features: &[String]) -> TargetConfig {
382require_inited();
383384let triple = SmallCStr::new(&llvm_target(sess));
385let cpu = SmallCStr::new(target_cpu(sess));
386let features = CString::new(global_llvm_features.join(",")).unwrap();
387let mc_subtarget_info = OwnedMCSubtargetInfo::new(&triple, &cpu, &features)
388 .unwrap_or_else(|err| llvm_err(sess.dcx(), err));
389390let rust_target_features = rust_target_features(
391sess,
392 |feature| {
393to_llvm_features(&sess.target, feature)
394 .map(SmallVec::<[&str; 2]>::from_iter)
395 .unwrap_or_default()
396 },
397 |feature| {
398// Determine whether the target CPU has the feature according to LLVM. We do *not*
399 // consider `-Ctarget-features` here, `rust_target_features` handles those itself.
400to_llvm_features(&sess.target, feature)
401 .is_some_and(|feat| mc_subtarget_info.has_features(feat))
402 },
403 );
404405let mut cfg = TargetConfig {
406rust_target_features,
407 has_reliable_f16: true,
408 has_reliable_f16_math: true,
409 has_reliable_f16b: true,
410 has_reliable_f128: true,
411 has_reliable_f128_math: true,
412 };
413414update_target_reliable_float_cfg(&sess.target, &mut cfg);
415cfg416}
417418/// Determine whether or not experimental float types are reliable based on known bugs.
419fn update_target_reliable_float_cfg(target: &Target, cfg: &mut TargetConfig) {
420let target_arch = &target.arch;
421let target_os = &target.options.os;
422let target_endian = &target.options.endian;
423let target_env = &target.options.env;
424let target_abi = &target.options.cfg_abi;
425let target_pointer_width = target.pointer_width;
426let version = get_version();
427let (major, _, _) = version;
428429cfg.has_reliable_f16 = match (target_arch, target_os) {
430// MinGW ABI bugs <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=115054> resolved in GCC 16
431 // but our toolchain hasn't been updated.
432(Arch::X86_64, Os::Windows) if *target_env == Env::Gnu && *target_abi != CfgAbi::Llvm => {
433false
434}
435// `f16` support only requires that symbols converting to and from `f32` are available. We
436 // provide these in `compiler-builtins`, so `f16` should be available on all platforms that
437 // do not have other ABI issues or LLVM crashes.
438_ => true,
439 };
440441// The heuristic for evaluating to true is twofold, namely;
442 //
443 // 1. Can LLVM compile an IR snippet containing `fpext bfloat %<var> to float`
444 // 2. Does the documentation indicate `bf16` support, can be seen in the
445 // tracking issue; <https://github.com/rust-lang/rust/issues/160630>
446cfg.has_reliable_f16b = match (target_arch, target_os) {
447// This is similar to <https://github.com/llvm/llvm-project/issues/94434>, however
448 // does not work until LLVM 23 on Windows.
449(Arch::Arm64EC, _) => major >= 23,
450 (Arch::AArch64 | Arch::Arm, _) => true,
451// FIXME(f16b) until <https://github.com/llvm/llvm-project/issues/97896>
452 // is resolved the below do not have a reliable `f16b`, on a widening
453 // path a call to `__truncsfbf2` is emitted. Or when using architectural
454 // extensions a non-portable narrowing instruction is emitted.
455(Arch::X86_64 | Arch::RiscV64 | Arch::LoongArch64, _) => false,
456_ => false,
457 };
458459cfg.has_reliable_f128 = match (target_arch, target_os) {
460// Unsupported https://github.com/llvm/llvm-project/issues/121122
461(Arch::AmdGpu, _) => false,
462 (Arch::Arm64EC, _) if major < 23 => false, // (fixed in llvm23)
463 // Selection bug <https://github.com/llvm/llvm-project/issues/95471>. This issue is closed
464 // but basic math still does not work.
465(Arch::Nvptx64, _) => false,
466// ABI/LLVM bugs:
467 // - with +vsx <https://github.com/llvm/llvm-project/pull/216613>
468 // - without +vsx <https://github.com/rust-lang/rust/issues/125109>
469(Arch::PowerPC, _) => false,
470// AIX does not support f128.
471(Arch::PowerPC64, Os::Aix) => false,
472// ABI bugs on BE without +vsx <https://github.com/rust-lang/rust/issues/125109>.
473(Arch::PowerPC64, _) => cfg.rust_target_features.contains(&sym::vsx),
474// MinGW ABI bugs <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=115054> (fixed in llvm23)
475(Arch::X86_64, Os::Windows)
476if *target_env == Env::Gnu && *target_abi != CfgAbi::Llvm && major < 23 =>
477 {
478false
479}
480// There are no known problems on other platforms, so the only requirement is that symbols
481 // are available. `compiler-builtins` provides all symbols required for core `f128`
482 // support, so this should work for everything else.
483_ => true,
484 };
485486// Assume that working `f16` means working `f16` math for most platforms, since
487 // operations just go through `f32`.
488cfg.has_reliable_f16_math = cfg.has_reliable_f16;
489490cfg.has_reliable_f128_math = match (target_arch, target_os) {
491// LLVM lowers `fp128` math to `long double` symbols even on platforms where
492 // `long double` is not IEEE binary128. See
493 // <https://github.com/llvm/llvm-project/issues/44744>.
494 //
495 // This rules out anything that doesn't have `long double` = `binary128`: <= 32 bits
496 // (`long double` is `f64`) and anything other than Linux (Windows and MacOS use `f64`).
497 // x86-64 would also be a problem, except there's a special fix for linux-gnu.
498 // We have to reject musl anyway because it doesn't have the symbols for f128 math.
499_ if target_pointer_width <= 32 => false,
500_ if *target_os != Os::Linux => false,
501_ if *target_env != Env::Gnu => false,
502// On big-endian powerpc the symbol selection is correct, despite __ibmf128 being
503 // long double on the target, but the f128 symbols are not defined.
504(Arch::PowerPC | Arch::PowerPC64, _) if *target_endian == Endian::Big => false,
505// After applying all these exceptions, the rest should work.
506_ => true,
507 } && cfg.has_reliable_f128;
508}
509510pub(crate) fn print_version() {
511let (major, minor, patch) = get_version();
512{
::std::io::_print(format_args!("LLVM version: {0}.{1}.{2}\n", major,
minor, patch));
};println!("LLVM version: {major}.{minor}.{patch}");
513}
514515/// Returns the version of LLVM that we are actually linked to at runtime.
516pub(crate) fn get_version() -> (u32, u32, u32) {
517let mut llvm_major = 0;
518let mut llvm_minor = 0;
519let mut llvm_patch = 0;
520 llvm::LLVMGetVersion(&mut llvm_major, &mut llvm_minor, &mut llvm_patch);
521 (llvm_major, llvm_minor, llvm_patch)
522}
523524/// The LLVM target triple to use for the session's target.
525///
526/// The UEFI targets are lowered through LLVM's `*-unknown-uefi` targets with
527/// LLVM 24 or later, and through the Windows targets with older LLVMs.
528pub(crate) fn llvm_target(sess: &EarlySession) -> Cow<'_, str> {
529let triple = versioned_llvm_target(sess);
530if sess.target.os == Os::Uefi && get_version() < (24, 0, 0) {
531return triple.replace("-unknown-uefi", "-unknown-windows").into();
532 }
533triple534}
535536pub(crate) fn print_passes() {
537// Can be called without initializing LLVM
538unsafe {
539 llvm::LLVMRustPrintPasses();
540 }
541}
542543fn llvm_target_features(tm: &llvm::TargetMachine) -> Vec<(&str, &str)> {
544let len = unsafe { llvm::LLVMRustGetTargetFeaturesCount(tm) };
545let mut ret = Vec::with_capacity(len);
546for i in 0..len {
547unsafe {
548let mut feature = ptr::null();
549let mut desc = ptr::null();
550 llvm::LLVMRustGetTargetFeature(tm, i, &mut feature, &mut desc);
551if feature.is_null() || desc.is_null() {
552::rustc_span::macros::bug_impl(None,
format_args!("LLVM returned a `null` target feature string"),
Location::caller());bug!("LLVM returned a `null` target feature string");
553 }
554let feature = CStr::from_ptr(feature).to_str().unwrap_or_else(|e| {
555::rustc_span::macros::bug_impl(None,
format_args!("LLVM returned a non-utf8 feature string: {0}", e),
Location::caller());bug!("LLVM returned a non-utf8 feature string: {}", e);
556 });
557let desc = CStr::from_ptr(desc).to_str().unwrap_or_else(|e| {
558::rustc_span::macros::bug_impl(None,
format_args!("LLVM returned a non-utf8 feature string: {0}", e),
Location::caller());bug!("LLVM returned a non-utf8 feature string: {}", e);
559 });
560 ret.push((feature, desc));
561 }
562 }
563ret564}
565566pub(crate) fn print(req: &PrintRequest, out: &mut String, sess: &Session) {
567require_inited();
568let tm = create_informational_target_machine(sess);
569match req.kind {
570 PrintKind::TargetCPUs => print_target_cpus(sess, tm.raw(), out),
571 PrintKind::TargetFeatures => print_target_features(sess, tm.raw(), out),
572_ => ::rustc_span::macros::bug_impl(None,
format_args!("rustc_codegen_llvm can\'t handle print request: {0:?}",
req), Location::caller())bug!("rustc_codegen_llvm can't handle print request: {:?}", req),
573 }
574}
575576fn print_target_cpus(sess: &Session, tm: &llvm::TargetMachine, out: &mut String) {
577let cpu_names = llvm::build_string(|s| unsafe {
578 llvm::LLVMRustPrintTargetCPUs(tm, s);
579 })
580 .unwrap();
581582struct Cpu<'a> {
583 cpu_name: &'a str,
584 remark: String,
585 }
586// Compare CPU against current target to label the default. Do not print it if
587 // `need_explicit_cpu` is set, because in that case the concept of default makes less sense.
588let target_cpu = handle_native(&sess.target.cpu);
589let make_remark = |cpu_name| {
590if cpu_name == target_cpu && !sess.target.need_explicit_cpu {
591// FIXME(#132514): This prints the LLVM target string, which can be
592 // different from the Rust target string. Is that intended?
593let target = &sess.target.llvm_target;
594::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" - This is the default target CPU for the current build target (currently {0}).",
target))
})format!(
595" - This is the default target CPU for the current build target (currently {target})."
596)597 } else {
598"".to_owned()
599 }
600 };
601let mut cpus = cpu_names602 .lines()
603 .filter(|cpu_name| {
604 !sess.target.unsupported_cpus.contains(&std::borrow::Cow::Borrowed(*cpu_name))
605 })
606 .map(|cpu_name| Cpu { cpu_name, remark: make_remark(cpu_name) })
607 .collect::<VecDeque<_>>();
608609// Only print the "native" entry when host and target are the same arch,
610 // since otherwise it could be wrong or misleading.
611 // Also do not print it if `requires_consistent_cpu` is set, because in this case
612 // "native" would be rejected.
613if sess.host.arch == sess.target.arch && !sess.target.requires_consistent_cpu {
614let host = get_host_cpu_name();
615cpus.push_front(Cpu {
616 cpu_name: NATIVE_CPU,
617 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})."),
618 });
619 }
620621let max_name_width = cpus.iter().map(|cpu| cpu.cpu_name.len()).max().unwrap_or(0);
622out.write_fmt(format_args!("Available CPUs for this target:\n"))writeln!(out, "Available CPUs for this target:").unwrap();
623for Cpu { cpu_name, remark } in cpus {
624// Only pad the CPU name if there's a remark to print after it.
625let width = if remark.is_empty() { 0 } else { max_name_width };
626out.write_fmt(format_args!(" {0:<1$}{2}\n", cpu_name, width, remark))writeln!(out, " {cpu_name:<width$}{remark}").unwrap();
627 }
628}
629630fn print_target_features(sess: &Session, tm: &llvm::TargetMachine, out: &mut String) {
631let mut llvm_target_features = llvm_target_features(tm);
632let mut known_llvm_target_features = FxHashSet::<&'static str>::default();
633let mut rustc_target_features = sess634 .target
635 .existing_rust_target_features()
636 .iter()
637 .filter_map(|(feature, gate, _implied)| {
638if !gate.in_cfg() {
639// Only list (experimentally) supported features.
640return None;
641 }
642// LLVM asserts that these are sorted. LLVM and Rust both use byte comparison for these
643 // strings.
644let llvm_feature = to_llvm_features(&sess.target, feature)?.llvm_feature_name;
645let desc =
646match llvm_target_features.binary_search_by_key(&llvm_feature, |(f, _d)| f).ok() {
647Some(index) => {
648known_llvm_target_features.insert(llvm_feature);
649llvm_target_features[index].1
650}
651None => "",
652 };
653654Some((*feature, desc))
655 })
656 .collect::<Vec<_>>();
657658// Since we add this at the end ...
659rustc_target_features.extend_from_slice(&[(
660"crt-static",
661"Enables C Run-time Libraries to be statically linked",
662 )]);
663// ... we need to sort the list again.
664rustc_target_features.sort();
665666llvm_target_features.retain(|(f, _d)| !known_llvm_target_features.contains(f));
667668let max_feature_len = llvm_target_features669 .iter()
670 .chain(rustc_target_features.iter())
671 .map(|(feature, _desc)| feature.len())
672 .max()
673 .unwrap_or(0);
674675out.write_fmt(format_args!("Features supported by rustc for this target:\n"))writeln!(out, "Features supported by rustc for this target:").unwrap();
676for (feature, desc) in &rustc_target_features {
677out.write_fmt(format_args!(" {0:1$} - {2}.\n", feature, max_feature_len,
desc))writeln!(out, " {feature:max_feature_len$} - {desc}.").unwrap();
678 }
679out.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();
680for (feature, desc) in &llvm_target_features {
681out.write_fmt(format_args!(" {0:1$} - {2}.\n", feature, max_feature_len,
desc))writeln!(out, " {feature:max_feature_len$} - {desc}.").unwrap();
682 }
683if llvm_target_features.is_empty() {
684out.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.")685 .unwrap();
686 }
687out.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();
688out.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")689 .unwrap();
690out.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();
691out.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();
692}
693694/// Returns the host CPU name, according to LLVM.
695fn get_host_cpu_name() -> &'static str {
696let mut len = 0;
697// SAFETY: The underlying C++ global function returns a `StringRef` that
698 // isn't tied to any particular backing buffer, so it must be 'static.
699let slice: &'static [u8] = unsafe {
700let ptr = llvm::LLVMRustGetHostCPUName(&mut len);
701if !!ptr.is_null() {
::core::panicking::panic("assertion failed: !ptr.is_null()")
};assert!(!ptr.is_null());
702 slice::from_raw_parts(ptr, len)
703 };
704 str::from_utf8(slice).expect("host CPU name should be UTF-8")
705}
706707/// If the given string is `"native"`, returns the host CPU name according to
708/// LLVM. Otherwise, the string is returned as-is.
709fn handle_native(cpu_name: &str) -> &str {
710match cpu_name {
711NATIVE_CPU => get_host_cpu_name(),
712_ => cpu_name,
713 }
714}
715716pub(crate) fn target_cpu(sess: &EarlySession) -> &str {
717let cpu_name = sess.opts.cg.target_cpu.as_deref().unwrap_or_else(|| &sess.target.cpu);
718handle_native(cpu_name)
719}
720721/// The target features for compiler flags other than `-Ctarget-features`.
722fn llvm_features_by_flags(sess: &EarlySession, features: &mut Vec<String>) {
723if wants_wasm_eh(&sess.target) && sess.panic_strategy() == PanicStrategy::Unwind {
724features.push("+exception-handling".into());
725 }
726727 target_features::retpoline_features_by_flags(sess, features);
728 target_features::sanitizer_features_by_flags(sess, features);
729730// -Zfixed-x18
731if sess.opts.unstable_opts.fixed_x18 {
732if sess.target.arch != Arch::AArch64 {
733sess.dcx()
734 .emit_fatal(diagnostics::FixedX18InvalidArch { arch: sess.target.arch.desc() });
735 } else {
736features.push("+reserve-x18".into());
737 }
738 }
739}
740741/// The list of LLVM features computed from the target itself as well as from `-Ctarget-cpu` and
742/// `-Zllvm-target-feature` and from `-C` flags that under the hood are mapped to target features in
743/// LLVM. Does NOT include the features in `-Ctarget-feature`!
744pub(crate) fn base_llvm_features(sess: &EarlySession) -> Vec<String> {
745// Features that come earlier are overridden by conflicting features later in the string.
746 // Typically we'll want more explicit settings to override the implicit ones, so we process
747 // features in the following order:
748 //
749 // * Features from -Ctarget-cpu=*; are overridden by [^1]
750 // * Features implied by --target; are overridden by
751 // * Features from -Zllvm-target-feature; are overridden by
752 // [this function is done here, the rest happens elsewhere]
753 // * Features from -Ctarget-feature; are overridden by
754 // * function specific features
755 //
756 // [^1]: target-cpu=native is handled here, other target-cpu values are handled implicitly
757 // through LLVM TargetMachine implementation.
758 //
759 // The reason this function stops before -Ctarget-feature is because for -Ctarget-feature we do
760 // *not* want backend-side implications to apply, only implications that we explicitly configure
761 // for Rust target features. The Rust session (for `cfg(target_feature)`) and the backend
762 // therefore start with the target features computed here, and then add -Ctarget-feature and
763 // function-specific features themselves. To ensure both are consistent in terms of which
764 // features end up being enabled, it is therefore necessary to do those two after everything
765 // else. (It is worth mentioning that the target features implied by --target are also Rust
766 // target features but for those, we *do* let the backend add its own implications before
767 // computing `cfg(target_feature)`).
768 //
769 // FIXME(nagisa): it isn't clear what's the best interaction between features implied by
770 // `-Ctarget-cpu` and `--target` are. On one hand, you'd expect CLI arguments to always
771 // override anything that's implicit, so e.g. when there's no `--target` flag, features implied
772 // the host target are overridden by `-Ctarget-cpu=*`. On the other hand, what about when both
773 // `--target` and `-Ctarget-cpu=*` are specified? Both then imply some target features and both
774 // flags are specified by the user on the CLI. It isn't as clear-cut which order of precedence
775 // should be taken in cases like these.
776let mut features = ::alloc::vec::Vec::new()vec![];
777778// -Ctarget-cpu=native
779match sess.opts.cg.target_cpu {
780Some(ref s) if s == NATIVE_CPU => {
781// We have already figured out the actual CPU name with `LLVMRustGetHostCPUName` and set
782 // that for LLVM, so the features implied by that CPU name will be available everywhere.
783 // However, that is not sufficient: e.g. `skylake` alone is not sufficient to tell if
784 // some of the instructions are available or not. So we have to also explicitly ask for
785 // the exact set of features available on the host, and enable all of them.
786let features_string = unsafe {
787let ptr = llvm::LLVMGetHostCPUFeatures();
788let features_string = if !ptr.is_null() {
789CStr::from_ptr(ptr)
790 .to_str()
791 .unwrap_or_else(|e| {
792::rustc_span::macros::bug_impl(None,
format_args!("LLVM returned a non-utf8 features string: {0}", e),
Location::caller());bug!("LLVM returned a non-utf8 features string: {}", e);
793 })
794 .to_owned()
795 } else {
796::rustc_span::macros::bug_impl(None,
format_args!("could not allocate host CPU features, LLVM returned a `null` string"),
Location::caller());bug!("could not allocate host CPU features, LLVM returned a `null` string");
797 };
798799 llvm::LLVMDisposeMessage(ptr);
800801features_string802 };
803if !features_string.is_empty() {
804features.extend(features_string.split(',').map(String::from));
805 }
806 }
807Some(_) | None => {}
808 };
809810// Features implied by an implicit or explicit `--target`.
811target_features::target_spec_to_backend_features(
812sess,
813extend_with_llvm_features_for_rust_feature(sess, &mut features),
814 );
815816// `-C` flags that map to LLVM target features.
817 // We need to include them even with `only_base_features` as this is used to populate
818 // `sess.rust_target_features` where we very much want them to be present (e.g. the inline
819 // asm logic uses that to check which registers may be used).
820llvm_features_by_flags(sess, &mut features);
821822// `-Zllvm-target-feature`, all the way at the end to overwrite everything.
823 // Should be picked up by `cfg` (e.g. if someone enables AVX this way).
824for feature in sess.opts.unstable_opts.llvm_target_feature.split(',') {
825if feature.is_empty() {
826continue;
827 }
828if feature.starts_with('+') || feature.starts_with('-') {
829 features.push(feature.to_owned());
830 } else {
831// LLVM seems to silently ignore entries without leading `+`/`-`. Let's emit a warning
832 // to avoid confusion.
833sess.dcx().emit_warn(diagnostics::UnknownLlvmTargetFeaturePrefix { feature });
834 }
835 }
836837features838}
839840pub(crate) fn tune_cpu(sess: &Session) -> Option<&str> {
841let name = sess.opts.unstable_opts.tune_cpu.as_ref()?;
842Some(handle_native(name))
843}
844845pub(crate) fn target_has_mnemonic(sess: &Session, mnemonic: &str) -> bool {
846require_inited();
847let tm = create_informational_target_machine(sess);
848let cstr = SmallCStr::new(mnemonic);
849unsafe { llvm::LLVMRustTargetHasMnemonic(tm.raw(), cstr.as_ptr()) }
850}