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};
78use libc::c_int;
9use rustc_codegen_ssa::base::wants_wasm_eh;
10use rustc_codegen_ssa::target_features::cfg_target_feature;
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::{PrintKind, PrintRequest};
18use rustc_target::spec::{
19Arch, CfgAbi, Env, MergeFunctions, Os, PanicStrategy, SmallDataThresholdSupport,
20};
21use smallvec::{SmallVec, smallvec};
2223use crate::back::write::create_informational_target_machine;
24use crate::{errors, llvm};
2526static INIT: Once = Once::new();
2728pub(crate) fn init(sess: &Session) {
29unsafe {
30// Before we touch LLVM, make sure that multithreading is enabled.
31if !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 }
34INIT.call_once(|| {
35configure_llvm(sess);
36 });
37 }
38}
3940fn require_inited() {
41if !INIT.is_completed() {
42::rustc_middle::util::bug::bug_fmt(format_args!("LLVM is not initialized"));bug!("LLVM is not initialized");
43 }
44}
4546unsafe fn configure_llvm(sess: &Session) {
47let n_args = sess.opts.cg.llvm_args.len() + sess.target.llvm_args.len();
48let mut llvm_c_strs = Vec::with_capacity(n_args + 1);
49let mut llvm_args = Vec::with_capacity(n_args + 1);
5051unsafe {
52 llvm::LLVMRustInstallErrorHandlers();
53 }
54// On Windows, an LLVM assertion will open an Abort/Retry/Ignore dialog
55 // box for the purpose of launching a debugger. However, on CI this will
56 // cause it to hang until it times out, which can take several hours.
57if std::env::var_os("CI").is_some() {
58unsafe {
59 llvm::LLVMRustDisableSystemDialogsOnCrash();
60 }
61 }
6263fn llvm_arg_to_arg_name(full_arg: &str) -> &str {
64full_arg.trim().split(|c: char| c == '=' || c.is_whitespace()).next().unwrap_or("")
65 }
6667let cg_opts = sess.opts.cg.llvm_args.iter().map(AsRef::as_ref);
68let tg_opts = sess.target.llvm_args.iter().map(AsRef::as_ref);
69// Target-spec args are passed to LLVM before user `-Cllvm-args`. LLVM's
70 // `cl::opt` parser is last-wins, so this lets `-Cllvm-args=...` override
71 // a value already set in the target spec (e.g. `-wasm-use-legacy-eh`).
72let sess_args = tg_opts.chain(cg_opts);
7374let user_specified_args: FxHashSet<_> =
75sess_args.clone().map(|s| llvm_arg_to_arg_name(s)).filter(|s| !s.is_empty()).collect();
7677 {
78// This adds the given argument to LLVM. Unless `force` is true
79 // user specified arguments are *not* overridden.
80let mut add = |arg: &str, force: bool| {
81if force || !user_specified_args.contains(llvm_arg_to_arg_name(arg)) {
82let s = CString::new(arg).unwrap();
83llvm_args.push(s.as_ptr());
84llvm_c_strs.push(s);
85 }
86 };
87// Set the llvm "program name" to make usage and invalid argument messages more clear.
88add("rustc -Cllvm-args=\"...\" with", true);
89if sess.opts.unstable_opts.time_llvm_passes {
90add("-time-passes", false);
91 }
92if sess.opts.unstable_opts.print_llvm_passes {
93add("-debug-pass=Structure", false);
94 }
95if sess.target.generate_arange_section
96 && !sess.opts.unstable_opts.no_generate_arange_section
97 {
98add("-generate-arange-section", false);
99 }
100101match sess.opts.unstable_opts.merge_functions.unwrap_or(sess.target.merge_functions) {
102 MergeFunctions::Disabled | MergeFunctions::Trampolines => {}
103 MergeFunctions::Aliases => {
104add("-mergefunc-use-aliases", false);
105 }
106 }
107108if wants_wasm_eh(sess) {
109add("-wasm-enable-eh", false);
110 }
111112// HACK(eddyb) LLVM inserts `llvm.assume` calls to preserve align attributes
113 // during inlining. Unfortunately these may block other optimizations.
114add("-preserve-alignment-assumptions-during-inlining=false", false);
115116// Use non-zero `import-instr-limit` multiplier for cold callsites.
117add("-import-cold-multiplier=0.1", false);
118119if sess.print_llvm_stats() || sess.print_llvm_stats_json().is_some() {
120add("-stats", false);
121 }
122123for arg in sess_args {
124 add(&(*arg), true);
125 }
126127match (
128sess.opts.unstable_opts.small_data_threshold,
129sess.target.small_data_threshold_support(),
130 ) {
131// Set up the small-data optimization limit for architectures that use
132 // an LLVM argument to control this.
133(Some(threshold), SmallDataThresholdSupport::LlvmArg(arg)) => {
134add(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("--{0}={1}", arg, threshold))
})format!("--{arg}={threshold}"), false)
135 }
136_ => (),
137 };
138 }
139140if sess.opts.unstable_opts.llvm_time_trace {
141unsafe { llvm::LLVMRustTimeTraceProfilerInitialize() };
142 }
143144 rustc_llvm::initialize_available_targets();
145146unsafe { llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int, llvm_args.as_ptr()) };
147}
148149pub(crate) fn time_trace_profiler_finish(file_name: &Path) {
150unsafe {
151let file_name = path_to_c_string(file_name);
152 llvm::LLVMRustTimeTraceProfilerFinish(file_name.as_ptr());
153 }
154}
155156enum TargetFeatureFoldStrength<'a> {
157// The feature is only tied when enabling the feature, disabling
158 // this feature shouldn't disable the tied feature.
159EnableOnly(&'a str),
160// The feature is tied for both enabling and disabling this feature.
161Both(&'a str),
162}
163164impl<'a> TargetFeatureFoldStrength<'a> {
165fn as_str(&self) -> &'a str {
166match self {
167 TargetFeatureFoldStrength::EnableOnly(feat) => feat,
168 TargetFeatureFoldStrength::Both(feat) => feat,
169 }
170 }
171}
172173pub(crate) struct LLVMFeature<'a> {
174 llvm_feature_name: &'a str,
175 dependencies: SmallVec<[TargetFeatureFoldStrength<'a>; 1]>,
176}
177178impl<'a> LLVMFeature<'a> {
179fn new(llvm_feature_name: &'a str) -> Self {
180Self { llvm_feature_name, dependencies: SmallVec::new() }
181 }
182183fn with_dependencies(
184 llvm_feature_name: &'a str,
185 dependencies: SmallVec<[TargetFeatureFoldStrength<'a>; 1]>,
186 ) -> Self {
187Self { llvm_feature_name, dependencies }
188 }
189}
190191impl<'a> IntoIteratorfor LLVMFeature<'a> {
192type Item = &'a str;
193type IntoIter = impl Iterator<Item = &'a str>;
194195fn into_iter(self) -> Self::IntoIter {
196let dependencies = self.dependencies.into_iter().map(|feat| feat.as_str());
197 std::iter::once(self.llvm_feature_name).chain(dependencies)
198 }
199}
200201/// Convert a Rust feature name to an LLVM feature name. Returning `None` means the
202/// feature should be skipped, usually because it is not supported by the current
203/// LLVM version.
204///
205/// WARNING: the features after applying `to_llvm_features` must be known
206/// to LLVM or the feature detection code will walk past the end of the feature
207/// array, leading to crashes.
208///
209/// To find a list of LLVM's names, see llvm-project/llvm/lib/Target/{ARCH}/*.td
210/// where `{ARCH}` is the architecture name. Look for instances of `SubtargetFeature`.
211///
212/// Check the current rustc fork of LLVM in the repo at
213/// <https://github.com/rust-lang/llvm-project/>. The commit in use can be found via the
214/// `llvm-project` submodule in <https://github.com/rust-lang/rust/tree/HEAD/src> Though note that
215/// Rust can also be build with an external precompiled version of LLVM which might lead to failures
216/// if the oldest tested / supported LLVM version doesn't yet support the relevant intrinsics.
217pub(crate) fn to_llvm_features<'a>(sess: &Session, s: &'a str) -> Option<LLVMFeature<'a>> {
218let (major, _, _) = get_version();
219match sess.target.arch {
220 Arch::AArch64 | Arch::Arm64EC => {
221match s {
222"rcpc2" => Some(LLVMFeature::new("rcpc-immo")),
223"dpb" => Some(LLVMFeature::new("ccpp")),
224"dpb2" => Some(LLVMFeature::new("ccdp")),
225"frintts" => Some(LLVMFeature::new("fptoint")),
226"fcma" => Some(LLVMFeature::new("complxnum")),
227"pmuv3" => Some(LLVMFeature::new("perfmon")),
228"paca" => Some(LLVMFeature::new("pauth")),
229"pacg" => Some(LLVMFeature::new("pauth")),
230"flagm2" => Some(LLVMFeature::new("altnzcv")),
231// Rust ties fp and neon together.
232"neon" => Some(LLVMFeature::with_dependencies(
233"neon",
234{
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")],
235 )),
236// In LLVM neon implicitly enables fp, but we manually enable
237 // neon when a feature only implicitly enables fp
238"fhm" => Some(LLVMFeature::new("fp16fml")),
239"fp16" => Some(LLVMFeature::new("fullfp16")),
240// Filter out features that are not supported by the current LLVM version
241"fpmr" => None, // only existed in 18
242 // Withdrawn by ARM; removed from LLVM in 22
243"tme" if major >= 22 => None,
244 s => Some(LLVMFeature::new(s)),
245 }
246 }
247 Arch::Arm => match s {
248"fp16" => Some(LLVMFeature::new("fullfp16")),
249 s => Some(LLVMFeature::new(s)),
250 },
251 Arch::Bpf => match s {
252"allows-misaligned-mem-access" if major < 22 => None,
253 s => Some(LLVMFeature::new(s)),
254 },
255// Filter out features that are not supported by the current LLVM version
256Arch::PowerPC | Arch::PowerPC64 => match s {
257"power8-crypto" => Some(LLVMFeature::new("crypto")),
258 s => Some(LLVMFeature::new(s)),
259 },
260 Arch::RiscV32 | Arch::RiscV64 => match s {
261// Filter out Rust-specific *virtual* target feature
262"zkne_or_zknd" => None,
263 s => Some(LLVMFeature::new(s)),
264 },
265 Arch::Sparc | Arch::Sparc64 => match s {
266"leoncasa" => Some(LLVMFeature::new("hasleoncasa")),
267 s => Some(LLVMFeature::new(s)),
268 },
269 Arch::Wasm32 | Arch::Wasm64 => match s {
270"gc" if major < 22 => None,
271 s => Some(LLVMFeature::new(s)),
272 },
273 Arch::X86 | Arch::X86_64 => {
274match s {
275"sse4.2" => Some(LLVMFeature::with_dependencies(
276"sse4.2",
277{
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")],
278 )),
279"pclmulqdq" => Some(LLVMFeature::new("pclmul")),
280"rdrand" => Some(LLVMFeature::new("rdrnd")),
281"bmi1" => Some(LLVMFeature::new("bmi")),
282"cmpxchg16b" => Some(LLVMFeature::new("cx16")),
283"lahfsahf" => Some(LLVMFeature::new("sahf")),
284// Enable the evex512 target feature if an avx512 target feature is enabled.
285s if s.starts_with("avx512") && major < 22 => Some(LLVMFeature::with_dependencies(
286s,
287{
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")],
288 )),
289"avx10.1" if major < 22 => Some(LLVMFeature::new("avx10.1-512")),
290"avx10.2" if major < 22 => Some(LLVMFeature::new("avx10.2-512")),
291"apxf" => Some(LLVMFeature::with_dependencies(
292"egpr",
293{
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![
294 TargetFeatureFoldStrength::Both("push2pop2"),
295 TargetFeatureFoldStrength::Both("ppx"),
296 TargetFeatureFoldStrength::Both("ndd"),
297 TargetFeatureFoldStrength::Both("ccmp"),
298 TargetFeatureFoldStrength::Both("cf"),
299 TargetFeatureFoldStrength::Both("nf"),
300 TargetFeatureFoldStrength::Both("zu"),
301 ],
302 )),
303 s => Some(LLVMFeature::new(s)),
304 }
305 }
306_ => Some(LLVMFeature::new(s)),
307 }
308}
309310/// Used to generate cfg variables and apply features.
311/// Must express features in the way Rust understands them.
312///
313/// We do not have to worry about RUSTC_SPECIFIC_FEATURES here, those are handled outside codegen.
314pub(crate) fn target_config(sess: &Session) -> TargetConfig {
315let target_machine = create_informational_target_machine(sess, true);
316317let (unstable_target_features, target_features) = cfg_target_feature(
318sess,
319 |feature| {
320to_llvm_features(sess, feature)
321 .map(|f| SmallVec::<[&str; 2]>::from_iter(f.into_iter()))
322 .unwrap_or_default()
323 },
324 |feature| {
325// This closure determines whether the target CPU has the feature according to LLVM. We do
326 // *not* consider the `-Ctarget-feature`s here, as that will be handled later in
327 // `cfg_target_feature`.
328if let Some(feat) = to_llvm_features(sess, feature) {
329// All the LLVM features this expands to must be enabled.
330for llvm_feature in feat {
331let cstr = SmallCStr::new(llvm_feature);
332// `LLVMRustHasFeature` is moderately expensive. On targets with many
333 // features (e.g. x86) these calls take a non-trivial fraction of runtime
334 // when compiling very small programs.
335if !unsafe { llvm::LLVMRustHasFeature(target_machine.raw(), cstr.as_ptr()) } {
336return false;
337 }
338 }
339true
340} else {
341false
342}
343 },
344 );
345346let mut cfg = TargetConfig {
347target_features,
348unstable_target_features,
349 has_reliable_f16: true,
350 has_reliable_f16_math: true,
351 has_reliable_f128: true,
352 has_reliable_f128_math: true,
353 };
354355update_target_reliable_float_cfg(sess, &mut cfg);
356cfg357}
358359/// Determine whether or not experimental float types are reliable based on known bugs.
360fn update_target_reliable_float_cfg(sess: &Session, cfg: &mut TargetConfig) {
361let target_arch = &sess.target.arch;
362let target_os = &sess.target.options.os;
363let target_env = &sess.target.options.env;
364let target_abi = &sess.target.options.cfg_abi;
365let target_pointer_width = sess.target.pointer_width;
366let version = get_version();
367let (major, _, _) = version;
368369cfg.has_reliable_f16 = match (target_arch, target_os) {
370// Unsupported <https://github.com/llvm/llvm-project/issues/94434> (fixed in llvm22)
371(Arch::Arm64EC, _) if major < 22 => false,
372// MinGW ABI bugs <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=115054>
373(Arch::X86_64, Os::Windows) if *target_env == Env::Gnu && *target_abi != CfgAbi::Llvm => {
374false
375}
376// Infinite recursion <https://github.com/llvm/llvm-project/issues/97981>
377(Arch::CSky, _) if major < 22 => false, // (fixed in llvm22)
378(Arch::PowerPC | Arch::PowerPC64, _) if major < 22 => false, // (fixed in llvm22)
379(Arch::Sparc | Arch::Sparc64, _) if major < 22 => false, // (fixed in llvm22)
380(Arch::Wasm32 | Arch::Wasm64, _) if major < 22 => false, // (fixed in llvm22)
381 // `f16` support only requires that symbols converting to and from `f32` are available. We
382 // provide these in `compiler-builtins`, so `f16` should be available on all platforms that
383 // do not have other ABI issues or LLVM crashes.
384_ => true,
385 };
386387cfg.has_reliable_f128 = match (target_arch, target_os) {
388// Unsupported https://github.com/llvm/llvm-project/issues/121122
389(Arch::AmdGpu, _) => false,
390// Unsupported <https://github.com/llvm/llvm-project/issues/94434>
391(Arch::Arm64EC, _) => false,
392// Selection bug <https://github.com/llvm/llvm-project/issues/95471>. This issue is closed
393 // but basic math still does not work.
394(Arch::Nvptx64, _) => false,
395// ABI bugs <https://github.com/rust-lang/rust/issues/125109> et al. (full
396 // list at <https://github.com/rust-lang/rust/issues/116909>)
397(Arch::PowerPC | Arch::PowerPC64, _) => false,
398// ABI unsupported <https://github.com/llvm/llvm-project/issues/41838> (fixed in llvm22)
399(Arch::Sparc, _) if major < 22 => false,
400// MinGW ABI bugs <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=115054>
401(Arch::X86_64, Os::Windows) if *target_env == Env::Gnu && *target_abi != CfgAbi::Llvm => {
402false
403}
404// There are no known problems on other platforms, so the only requirement is that symbols
405 // are available. `compiler-builtins` provides all symbols required for core `f128`
406 // support, so this should work for everything else.
407_ => true,
408 };
409410// Assume that working `f16` means working `f16` math for most platforms, since
411 // operations just go through `f32`.
412cfg.has_reliable_f16_math = cfg.has_reliable_f16;
413414cfg.has_reliable_f128_math = match (target_arch, target_os) {
415// LLVM lowers `fp128` math to `long double` symbols even on platforms where
416 // `long double` is not IEEE binary128. See
417 // <https://github.com/llvm/llvm-project/issues/44744>.
418 //
419 // This rules out anything that doesn't have `long double` = `binary128`; <= 32 bits
420 // (ld is `f64`), anything other than Linux (Windows and MacOS use `f64`), and `x86`
421 // (ld is 80-bit extended precision).
422 //
423 // musl does not implement the symbols required for f128 math at all.
424_ if *target_env == Env::Musl => false,
425 (Arch::X86_64, _) => false,
426 (_, Os::Linux) if target_pointer_width == 64 => true,
427_ => false,
428 } && cfg.has_reliable_f128;
429}
430431pub(crate) fn print_version() {
432let (major, minor, patch) = get_version();
433{
::std::io::_print(format_args!("LLVM version: {0}.{1}.{2}\n", major,
minor, patch));
};println!("LLVM version: {major}.{minor}.{patch}");
434}
435436pub(crate) fn get_version() -> (u32, u32, u32) {
437// Can be called without initializing LLVM
438unsafe {
439 (llvm::LLVMRustVersionMajor(), llvm::LLVMRustVersionMinor(), llvm::LLVMRustVersionPatch())
440 }
441}
442443pub(crate) fn print_passes() {
444// Can be called without initializing LLVM
445unsafe {
446 llvm::LLVMRustPrintPasses();
447 }
448}
449450fn llvm_target_features(tm: &llvm::TargetMachine) -> Vec<(&str, &str)> {
451let len = unsafe { llvm::LLVMRustGetTargetFeaturesCount(tm) };
452let mut ret = Vec::with_capacity(len);
453for i in 0..len {
454unsafe {
455let mut feature = ptr::null();
456let mut desc = ptr::null();
457 llvm::LLVMRustGetTargetFeature(tm, i, &mut feature, &mut desc);
458if feature.is_null() || desc.is_null() {
459::rustc_middle::util::bug::bug_fmt(format_args!("LLVM returned a `null` target feature string"));bug!("LLVM returned a `null` target feature string");
460 }
461let feature = CStr::from_ptr(feature).to_str().unwrap_or_else(|e| {
462::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);
463 });
464let desc = CStr::from_ptr(desc).to_str().unwrap_or_else(|e| {
465::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);
466 });
467 ret.push((feature, desc));
468 }
469 }
470ret471}
472473pub(crate) fn print(req: &PrintRequest, out: &mut String, sess: &Session) {
474require_inited();
475let tm = create_informational_target_machine(sess, false);
476match req.kind {
477 PrintKind::TargetCPUs => print_target_cpus(sess, tm.raw(), out),
478 PrintKind::TargetFeatures => print_target_features(sess, tm.raw(), out),
479_ => ::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),
480 }
481}
482483fn print_target_cpus(sess: &Session, tm: &llvm::TargetMachine, out: &mut String) {
484let cpu_names = llvm::build_string(|s| unsafe {
485 llvm::LLVMRustPrintTargetCPUs(&tm, s);
486 })
487 .unwrap();
488489struct Cpu<'a> {
490 cpu_name: &'a str,
491 remark: String,
492 }
493// Compare CPU against current target to label the default.
494let target_cpu = handle_native(&sess.target.cpu);
495let make_remark = |cpu_name| {
496if cpu_name == target_cpu {
497// FIXME(#132514): This prints the LLVM target string, which can be
498 // different from the Rust target string. Is that intended?
499let target = &sess.target.llvm_target;
500::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" - This is the default target CPU for the current build target (currently {0}).",
target))
})format!(
501" - This is the default target CPU for the current build target (currently {target})."
502)503 } else {
504"".to_owned()
505 }
506 };
507let mut cpus = cpu_names508 .lines()
509 .filter(|cpu_name| {
510 !sess.target.unsupported_cpus.contains(&std::borrow::Cow::Borrowed(*cpu_name))
511 })
512 .map(|cpu_name| Cpu { cpu_name, remark: make_remark(cpu_name) })
513 .collect::<VecDeque<_>>();
514515// Only print the "native" entry when host and target are the same arch,
516 // since otherwise it could be wrong or misleading.
517if sess.host.arch == sess.target.arch {
518let host = get_host_cpu_name();
519cpus.push_front(Cpu {
520 cpu_name: "native",
521 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})."),
522 });
523 }
524525let max_name_width = cpus.iter().map(|cpu| cpu.cpu_name.len()).max().unwrap_or(0);
526out.write_fmt(format_args!("Available CPUs for this target:\n"))writeln!(out, "Available CPUs for this target:").unwrap();
527for Cpu { cpu_name, remark } in cpus {
528// Only pad the CPU name if there's a remark to print after it.
529let width = if remark.is_empty() { 0 } else { max_name_width };
530out.write_fmt(format_args!(" {0:<1$}{2}\n", cpu_name, width, remark))writeln!(out, " {cpu_name:<width$}{remark}").unwrap();
531 }
532}
533534fn print_target_features(sess: &Session, tm: &llvm::TargetMachine, out: &mut String) {
535let mut llvm_target_features = llvm_target_features(tm);
536let mut known_llvm_target_features = FxHashSet::<&'static str>::default();
537let mut rustc_target_features = sess538 .target
539 .rust_target_features()
540 .iter()
541 .filter_map(|(feature, gate, _implied)| {
542if !gate.in_cfg() {
543// Only list (experimentally) supported features.
544return None;
545 }
546// LLVM asserts that these are sorted. LLVM and Rust both use byte comparison for these
547 // strings.
548let llvm_feature = to_llvm_features(sess, *feature)?.llvm_feature_name;
549let desc =
550match llvm_target_features.binary_search_by_key(&llvm_feature, |(f, _d)| f).ok() {
551Some(index) => {
552known_llvm_target_features.insert(llvm_feature);
553llvm_target_features[index].1
554}
555None => "",
556 };
557558Some((*feature, desc))
559 })
560 .collect::<Vec<_>>();
561562// Since we add this at the end ...
563rustc_target_features.extend_from_slice(&[(
564"crt-static",
565"Enables C Run-time Libraries to be statically linked",
566 )]);
567// ... we need to sort the list again.
568rustc_target_features.sort();
569570llvm_target_features.retain(|(f, _d)| !known_llvm_target_features.contains(f));
571572let max_feature_len = llvm_target_features573 .iter()
574 .chain(rustc_target_features.iter())
575 .map(|(feature, _desc)| feature.len())
576 .max()
577 .unwrap_or(0);
578579out.write_fmt(format_args!("Features supported by rustc for this target:\n"))writeln!(out, "Features supported by rustc for this target:").unwrap();
580for (feature, desc) in &rustc_target_features {
581out.write_fmt(format_args!(" {0:1$} - {2}.\n", feature, max_feature_len,
desc))writeln!(out, " {feature:max_feature_len$} - {desc}.").unwrap();
582 }
583out.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();
584for (feature, desc) in &llvm_target_features {
585out.write_fmt(format_args!(" {0:1$} - {2}.\n", feature, max_feature_len,
desc))writeln!(out, " {feature:max_feature_len$} - {desc}.").unwrap();
586 }
587if llvm_target_features.is_empty() {
588out.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.")589 .unwrap();
590 }
591out.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();
592out.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")593 .unwrap();
594out.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();
595out.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();
596}
597598/// Returns the host CPU name, according to LLVM.
599fn get_host_cpu_name() -> &'static str {
600let mut len = 0;
601// SAFETY: The underlying C++ global function returns a `StringRef` that
602 // isn't tied to any particular backing buffer, so it must be 'static.
603let slice: &'static [u8] = unsafe {
604let ptr = llvm::LLVMRustGetHostCPUName(&mut len);
605if !!ptr.is_null() {
::core::panicking::panic("assertion failed: !ptr.is_null()")
};assert!(!ptr.is_null());
606 slice::from_raw_parts(ptr, len)
607 };
608 str::from_utf8(slice).expect("host CPU name should be UTF-8")
609}
610611/// If the given string is `"native"`, returns the host CPU name according to
612/// LLVM. Otherwise, the string is returned as-is.
613fn handle_native(cpu_name: &str) -> &str {
614match cpu_name {
615"native" => get_host_cpu_name(),
616_ => cpu_name,
617 }
618}
619620pub(crate) fn target_cpu(sess: &Session) -> &str {
621let cpu_name = sess.opts.cg.target_cpu.as_deref().unwrap_or_else(|| &sess.target.cpu);
622handle_native(cpu_name)
623}
624625/// The target features for compiler flags other than `-Ctarget-features`.
626fn llvm_features_by_flags(sess: &Session, features: &mut Vec<String>) {
627if wants_wasm_eh(sess) && sess.panic_strategy() == PanicStrategy::Unwind {
628features.push("+exception-handling".into());
629 }
630631 target_features::retpoline_features_by_flags(sess, features);
632 target_features::sanitizer_features_by_flags(sess, features);
633634// -Zfixed-x18
635if sess.opts.unstable_opts.fixed_x18 {
636if sess.target.arch != Arch::AArch64 {
637sess.dcx().emit_fatal(errors::FixedX18InvalidArch { arch: sess.target.arch.desc() });
638 } else {
639features.push("+reserve-x18".into());
640 }
641 }
642}
643644/// The list of LLVM features computed from CLI flags (`-Ctarget-cpu`, `-Ctarget-feature`,
645/// `--target` and similar).
646pub(crate) fn global_llvm_features(sess: &Session, only_base_features: bool) -> Vec<String> {
647// Features that come earlier are overridden by conflicting features later in the string.
648 // Typically we'll want more explicit settings to override the implicit ones, so:
649 //
650 // * Features from -Ctarget-cpu=*; are overridden by [^1]
651 // * Features implied by --target; are overridden by
652 // * Features from -Ctarget-feature; are overridden by
653 // * function specific features.
654 //
655 // [^1]: target-cpu=native is handled here, other target-cpu values are handled implicitly
656 // through LLVM TargetMachine implementation.
657 //
658 // FIXME(nagisa): it isn't clear what's the best interaction between features implied by
659 // `-Ctarget-cpu` and `--target` are. On one hand, you'd expect CLI arguments to always
660 // override anything that's implicit, so e.g. when there's no `--target` flag, features implied
661 // the host target are overridden by `-Ctarget-cpu=*`. On the other hand, what about when both
662 // `--target` and `-Ctarget-cpu=*` are specified? Both then imply some target features and both
663 // flags are specified by the user on the CLI. It isn't as clear-cut which order of precedence
664 // should be taken in cases like these.
665let mut features = ::alloc::vec::Vec::new()vec![];
666667// -Ctarget-cpu=native
668match sess.opts.cg.target_cpu {
669Some(ref s) if s == "native" => {
670// We have already figured out the actual CPU name with `LLVMRustGetHostCPUName` and set
671 // that for LLVM, so the features implied by that CPU name will be available everywhere.
672 // However, that is not sufficient: e.g. `skylake` alone is not sufficient to tell if
673 // some of the instructions are available or not. So we have to also explicitly ask for
674 // the exact set of features available on the host, and enable all of them.
675let features_string = unsafe {
676let ptr = llvm::LLVMGetHostCPUFeatures();
677let features_string = if !ptr.is_null() {
678CStr::from_ptr(ptr)
679 .to_str()
680 .unwrap_or_else(|e| {
681::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);
682 })
683 .to_owned()
684 } else {
685::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");
686 };
687688 llvm::LLVMDisposeMessage(ptr);
689690features_string691 };
692if !features_string.is_empty() {
693features.extend(features_string.split(',').map(String::from));
694 }
695 }
696Some(_) | None => {}
697 };
698699let mut extend_backend_features = |feature: &str, enable: bool| {
700let enable_disable = if enable { '+' } else { '-' };
701// We run through `to_llvm_features` when
702 // passing requests down to LLVM. This means that all in-language
703 // features also work on the command line instead of having two
704 // different names when the LLVM name and the Rust name differ.
705let Some(llvm_feature) = to_llvm_features(sess, feature) else { return };
706707features.extend(
708 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(
709llvm_feature.dependencies.into_iter().filter_map(move |feat| {
710match (enable, feat) {
711 (_, TargetFeatureFoldStrength::Both(f))
712 | (true, TargetFeatureFoldStrength::EnableOnly(f)) => {
713Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}", enable_disable, f))
})format!("{enable_disable}{f}"))
714 }
715_ => None,
716 }
717 }),
718 ),
719 );
720 };
721722// Features implied by an implicit or explicit `--target`.
723target_features::target_spec_to_backend_features(sess, &mut extend_backend_features);
724725// -Ctarget-features
726if !only_base_features {
727 target_features::flag_to_backend_features(sess, extend_backend_features);
728 }
729730// We add this in the "base target" so that these show up in `sess.unstable_target_features`.
731llvm_features_by_flags(sess, &mut features);
732733features734}
735736pub(crate) fn tune_cpu(sess: &Session) -> Option<&str> {
737let name = sess.opts.unstable_opts.tune_cpu.as_ref()?;
738Some(handle_native(name))
739}
740741pub(crate) fn target_has_mnemonic(sess: &Session, mnemonic: &str) -> bool {
742require_inited();
743let tm = create_informational_target_machine(sess, false);
744let cstr = SmallCStr::new(mnemonic);
745unsafe { llvm::LLVMRustTargetHasMnemonic(tm.raw(), cstr.as_ptr()) }
746}