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};
8
9use 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::internal_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::{
22 Arch, CfgAbi, Env, MergeFunctions, Os, PanicStrategy, SmallDataThresholdSupport, Target,
23};
24use smallvec::{SmallVec, smallvec};
25
26use crate::back::owned_mc_subtarget_info::OwnedMCSubtargetInfo;
27use crate::back::write::{create_informational_target_machine, llvm_err};
28use crate::{diagnostics, llvm};
29
30static INIT: Once = Once::new();
31
32pub(crate) fn init(sess: &EarlySession) {
33 unsafe {
34 if !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 }
38 INIT.call_once(|| {
39 configure_llvm(sess);
40 });
41 }
42}
43
44fn require_inited() {
45 if !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}
49
50unsafe fn configure_llvm(sess: &EarlySession) {
51 let n_args = sess.opts.cg.llvm_args.len() + sess.target.llvm_args.len();
52 let mut llvm_c_strs = Vec::with_capacity(n_args + 1);
53 let mut llvm_args = Vec::with_capacity(n_args + 1);
54
55 unsafe {
57 let (llvm_major, llvm_minor, llvm_patch) = get_version();
58 let expected_version = llvm::LLVMRustVersionMajor();
59 if llvm_major != expected_version {
60 sess.dcx().emit_fatal(diagnostics::LlvmVersionMismatch {
61 expected_version,
62 llvm_major,
63 llvm_minor,
64 llvm_patch,
65 dll_loc: &match rustc_session::filesearch::dll_path(llvm::LLVMGetVersion as *mut _)
66 {
67 Ok(path) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" at {0}", path.display()))
})format!(" at {}", path.display()),
68 Err(_) => String::new(),
69 },
70 })
71 }
72 }
73
74 unsafe {
75 llvm::LLVMRustInstallErrorHandlers();
76 }
77 if std::env::var_os("CI").is_some() {
81 unsafe {
82 llvm::LLVMRustDisableSystemDialogsOnCrash();
83 }
84 }
85
86 fn llvm_arg_to_arg_name(full_arg: &str) -> &str {
87 full_arg.trim().split(|c: char| c == '=' || c.is_whitespace()).next().unwrap_or("")
88 }
89
90 let cg_opts = sess.opts.cg.llvm_args.iter().map(AsRef::as_ref);
91 let tg_opts = sess.target.llvm_args.iter().map(AsRef::as_ref);
92 let sess_args = tg_opts.chain(cg_opts);
96
97 let user_specified_args: FxHashSet<_> =
98 sess_args.clone().map(llvm_arg_to_arg_name).filter(|s| !s.is_empty()).collect();
99
100 {
101 let mut add = |arg: &str, force: bool| {
104 if force || !user_specified_args.contains(llvm_arg_to_arg_name(arg)) {
105 let s = CString::new(arg).unwrap();
106 llvm_args.push(s.as_ptr());
107 llvm_c_strs.push(s);
108 }
109 };
110 add("rustc -Cllvm-args=\"...\" with", true);
112 if sess.opts.unstable_opts.time_llvm_passes {
113 add("-time-passes", false);
114 }
115 if sess.opts.unstable_opts.print_llvm_passes {
116 add("-debug-pass=Structure", false);
117 }
118 if sess.target.generate_arange_section
119 && !sess.opts.unstable_opts.no_generate_arange_section
120 {
121 add("-generate-arange-section", false);
122 }
123
124 match sess.merge_functions() {
125 MergeFunctions::Disabled | MergeFunctions::Trampolines => {}
126 MergeFunctions::Aliases => {
127 add("-mergefunc-use-aliases", false);
128 }
129 }
130
131 if get_version() < (24, 0, 0) && wants_wasm_eh(&sess.target) {
132 add("-wasm-enable-eh", false);
133 }
134
135 add("-preserve-alignment-assumptions-during-inlining=false", false);
138
139 add("-import-cold-multiplier=0.1", false);
141
142 if sess.print_llvm_stats() || sess.print_llvm_stats_json().is_some() {
143 add("-stats", false);
144 }
145
146 for arg in sess_args {
147 add(arg, true);
148 }
149
150 if let Some(threshold) = sess.opts.unstable_opts.small_data_threshold
153 && let SmallDataThresholdSupport::LlvmArg(arg) =
154 sess.target.small_data_threshold_support()
155 {
156 add(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("--{0}={1}", arg, threshold))
})format!("--{arg}={threshold}"), false);
157 }
158 }
159
160 if sess.opts.unstable_opts.llvm_time_trace {
161 unsafe { llvm::LLVMRustTimeTraceProfilerInitialize() };
162 }
163
164 rustc_llvm::initialize_available_targets();
165
166 unsafe { llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int, llvm_args.as_ptr()) };
167}
168
169pub(crate) fn time_trace_profiler_finish(file_name: &Path) {
170 unsafe {
171 let file_name = path_to_c_string(file_name);
172 llvm::LLVMRustTimeTraceProfilerFinish(file_name.as_ptr());
173 }
174}
175
176enum TargetFeatureFoldStrength<'a> {
177 EnableOnly(&'a str),
180 Both(&'a str),
182}
183
184impl<'a> TargetFeatureFoldStrength<'a> {
185 fn as_str(&self) -> &'a str {
186 match self {
187 TargetFeatureFoldStrength::EnableOnly(feat) => feat,
188 TargetFeatureFoldStrength::Both(feat) => feat,
189 }
190 }
191}
192
193pub(crate) struct LLVMFeature<'a> {
194 llvm_feature_name: &'a str,
195 dependencies: SmallVec<[TargetFeatureFoldStrength<'a>; 1]>,
196}
197
198impl<'a> LLVMFeature<'a> {
199 fn new(llvm_feature_name: &'a str) -> Self {
200 Self { llvm_feature_name, dependencies: SmallVec::new() }
201 }
202
203 fn with_dependencies(
204 llvm_feature_name: &'a str,
205 dependencies: SmallVec<[TargetFeatureFoldStrength<'a>; 1]>,
206 ) -> Self {
207 Self { llvm_feature_name, dependencies }
208 }
209}
210
211impl<'a> IntoIterator for LLVMFeature<'a> {
212 type Item = &'a str;
213 type IntoIter = impl Iterator<Item = &'a str>;
214
215 fn into_iter(self) -> Self::IntoIter {
216 let dependencies = self.dependencies.into_iter().map(|feat| feat.as_str());
217 std::iter::once(self.llvm_feature_name).chain(dependencies)
218 }
219}
220
221pub(crate) fn to_llvm_features<'a>(target: &Target, s: &'a str) -> Option<LLVMFeature<'a>> {
238 let (major, _, _) = get_version();
239 match target.arch {
240 Arch::AArch64 | Arch::Arm64EC => {
241 match s {
242 "rcpc2" => Some(LLVMFeature::new("rcpc-immo")),
243 "dpb" => Some(LLVMFeature::new("ccpp")),
244 "dpb2" => Some(LLVMFeature::new("ccdp")),
245 "frintts" => Some(LLVMFeature::new("fptoint")),
246 "fcma" => Some(LLVMFeature::new("complxnum")),
247 "pmuv3" => Some(LLVMFeature::new("perfmon")),
248 "paca" => Some(LLVMFeature::new("pauth")),
249 "pacg" => Some(LLVMFeature::new("pauth")),
250 "flagm2" => Some(LLVMFeature::new("altnzcv")),
251 "neon" => Some(LLVMFeature::with_dependencies(
253 "neon",
254 {
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")],
255 )),
256 "fhm" => Some(LLVMFeature::new("fp16fml")),
259 "fp16" => Some(LLVMFeature::new("fullfp16")),
260 "fpmr" => None, "tme" => None,
264 s => Some(LLVMFeature::new(s)),
265 }
266 }
267 Arch::Arm => match s {
268 "fp16" => Some(LLVMFeature::new("fullfp16")),
269 s => Some(LLVMFeature::new(s)),
270 },
271 Arch::Nvptx64 => match s {
272 "sm_101" if major >= 24 => Some(LLVMFeature::new("sm_110")),
273 "sm_101a" if major >= 24 => Some(LLVMFeature::new("sm_110a")),
274 "sm_101f" if major >= 24 => Some(LLVMFeature::new("sm_110f")),
275 s => Some(LLVMFeature::new(s)),
276 },
277 Arch::PowerPC | Arch::PowerPC64 => match s {
279 "power8-crypto" => Some(LLVMFeature::new("crypto")),
280 s => Some(LLVMFeature::new(s)),
281 },
282 Arch::RiscV32 | Arch::RiscV64 => match s {
283 "zkne_or_zknd" => None,
285 s => Some(LLVMFeature::new(s)),
286 },
287 Arch::Sparc | Arch::Sparc64 => match s {
288 "leoncasa" => Some(LLVMFeature::new("hasleoncasa")),
289 s => Some(LLVMFeature::new(s)),
290 },
291 Arch::X86 | Arch::X86_64 => match s {
292 "sse4.2" => Some(LLVMFeature::with_dependencies(
293 "sse4.2",
294 {
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")],
295 )),
296 "pclmulqdq" => Some(LLVMFeature::new("pclmul")),
297 "rdrand" => Some(LLVMFeature::new("rdrnd")),
298 "bmi1" => Some(LLVMFeature::new("bmi")),
299 "cmpxchg16b" => Some(LLVMFeature::new("cx16")),
300 "lahfsahf" => Some(LLVMFeature::new("sahf")),
301 "apxf" => Some(LLVMFeature::with_dependencies(
302 "egpr",
303 {
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![
304 TargetFeatureFoldStrength::Both("push2pop2"),
305 TargetFeatureFoldStrength::Both("ppx"),
306 TargetFeatureFoldStrength::Both("ndd"),
307 TargetFeatureFoldStrength::Both("ccmp"),
308 TargetFeatureFoldStrength::Both("cf"),
309 TargetFeatureFoldStrength::Both("nf"),
310 TargetFeatureFoldStrength::Both("zu"),
311 ],
312 )),
313 s => Some(LLVMFeature::new(s)),
314 },
315 _ => Some(LLVMFeature::new(s)),
316 }
317}
318
319pub(crate) fn target_config(sess: &EarlySession) -> TargetConfig {
324 require_inited();
325 let target_features = global_llvm_features(sess, true);
326
327 let triple = SmallCStr::new(&llvm_target(sess));
328 let cpu = SmallCStr::new(target_cpu(sess));
329 let features = CString::new(target_features.join(",")).unwrap();
330 let mc_subtarget_info = OwnedMCSubtargetInfo::new(&triple, &cpu, &features)
331 .unwrap_or_else(|err| llvm_err(sess.dcx(), err));
332
333 let internal_target_features = internal_target_features(
334 sess,
335 |feature| {
336 to_llvm_features(&sess.target, feature)
337 .map(SmallVec::<[&str; 2]>::from_iter)
338 .unwrap_or_default()
339 },
340 |feature| {
341 to_llvm_features(&sess.target, feature)
346 .is_some_and(|feat| mc_subtarget_info.has_features(feat))
347 },
348 );
349
350 let mut cfg = TargetConfig {
351 internal_target_features,
352 has_reliable_f16: true,
353 has_reliable_f16_math: true,
354 has_reliable_f16b: true,
355 has_reliable_f128: true,
356 has_reliable_f128_math: true,
357 };
358
359 update_target_reliable_float_cfg(&sess.target, &mut cfg);
360 cfg
361}
362
363fn update_target_reliable_float_cfg(target: &Target, cfg: &mut TargetConfig) {
365 let target_arch = &target.arch;
366 let target_os = &target.options.os;
367 let target_endian = &target.options.endian;
368 let target_env = &target.options.env;
369 let target_abi = &target.options.cfg_abi;
370 let target_pointer_width = target.pointer_width;
371 let version = get_version();
372 let (major, _, _) = version;
373
374 cfg.has_reliable_f16 = match (target_arch, target_os) {
375 (Arch::X86_64, Os::Windows) if *target_env == Env::Gnu && *target_abi != CfgAbi::Llvm => {
378 false
379 }
380 _ => true,
384 };
385
386 cfg.has_reliable_f16b = match (target_arch, target_os) {
392 (Arch::Arm64EC, _) => major >= 23,
395 (Arch::AArch64 | Arch::Arm, _) => true,
396 (Arch::X86_64 | Arch::RiscV64 | Arch::LoongArch64, _) => false,
401 _ => false,
402 };
403
404 cfg.has_reliable_f128 = match (target_arch, target_os) {
405 (Arch::AmdGpu, _) => false,
407 (Arch::Arm64EC, _) if major < 23 => false, (Arch::Nvptx64, _) => false,
411 (Arch::PowerPC, _) => false,
415 (Arch::PowerPC64, Os::Aix) => false,
417 (Arch::PowerPC64, _) => cfg.internal_target_features.contains(&sym::vsx),
419 (Arch::X86_64, Os::Windows)
421 if *target_env == Env::Gnu && *target_abi != CfgAbi::Llvm && major < 23 =>
422 {
423 false
424 }
425 _ => true,
429 };
430
431 cfg.has_reliable_f16_math = cfg.has_reliable_f16;
434
435 cfg.has_reliable_f128_math = match (target_arch, target_os) {
436 _ if target_pointer_width <= 32 => false,
445 _ if *target_os != Os::Linux => false,
446 _ if *target_env != Env::Gnu => false,
447 (Arch::PowerPC | Arch::PowerPC64, _) if *target_endian == Endian::Big => false,
450 _ => true,
452 } && cfg.has_reliable_f128;
453}
454
455pub(crate) fn print_version() {
456 let (major, minor, patch) = get_version();
457 {
::std::io::_print(format_args!("LLVM version: {0}.{1}.{2}\n", major,
minor, patch));
};println!("LLVM version: {major}.{minor}.{patch}");
458}
459
460pub(crate) fn get_version() -> (u32, u32, u32) {
462 let mut llvm_major = 0;
463 let mut llvm_minor = 0;
464 let mut llvm_patch = 0;
465 llvm::LLVMGetVersion(&mut llvm_major, &mut llvm_minor, &mut llvm_patch);
466 (llvm_major, llvm_minor, llvm_patch)
467}
468
469pub(crate) fn llvm_target(sess: &EarlySession) -> Cow<'_, str> {
474 let triple = versioned_llvm_target(sess);
475 if sess.target.os == Os::Uefi && get_version() < (24, 0, 0) {
476 return triple.replace("-unknown-uefi", "-unknown-windows").into();
477 }
478 triple
479}
480
481pub(crate) fn print_passes() {
482 unsafe {
484 llvm::LLVMRustPrintPasses();
485 }
486}
487
488fn llvm_target_features(tm: &llvm::TargetMachine) -> Vec<(&str, &str)> {
489 let len = unsafe { llvm::LLVMRustGetTargetFeaturesCount(tm) };
490 let mut ret = Vec::with_capacity(len);
491 for i in 0..len {
492 unsafe {
493 let mut feature = ptr::null();
494 let mut desc = ptr::null();
495 llvm::LLVMRustGetTargetFeature(tm, i, &mut feature, &mut desc);
496 if feature.is_null() || desc.is_null() {
497 ::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");
498 }
499 let feature = CStr::from_ptr(feature).to_str().unwrap_or_else(|e| {
500 ::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);
501 });
502 let desc = CStr::from_ptr(desc).to_str().unwrap_or_else(|e| {
503 ::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);
504 });
505 ret.push((feature, desc));
506 }
507 }
508 ret
509}
510
511pub(crate) fn print(req: &PrintRequest, out: &mut String, sess: &Session) {
512 require_inited();
513 let tm = create_informational_target_machine(sess);
514 match req.kind {
515 PrintKind::TargetCPUs => print_target_cpus(sess, tm.raw(), out),
516 PrintKind::TargetFeatures => print_target_features(sess, tm.raw(), out),
517 _ => ::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),
518 }
519}
520
521fn print_target_cpus(sess: &Session, tm: &llvm::TargetMachine, out: &mut String) {
522 let cpu_names = llvm::build_string(|s| unsafe {
523 llvm::LLVMRustPrintTargetCPUs(tm, s);
524 })
525 .unwrap();
526
527 struct Cpu<'a> {
528 cpu_name: &'a str,
529 remark: String,
530 }
531 let target_cpu = handle_native(&sess.target.cpu);
534 let make_remark = |cpu_name| {
535 if cpu_name == target_cpu && !sess.target.need_explicit_cpu {
536 let target = &sess.target.llvm_target;
539 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" - This is the default target CPU for the current build target (currently {0}).",
target))
})format!(
540 " - This is the default target CPU for the current build target (currently {target})."
541 )
542 } else {
543 "".to_owned()
544 }
545 };
546 let mut cpus = cpu_names
547 .lines()
548 .filter(|cpu_name| {
549 !sess.target.unsupported_cpus.contains(&std::borrow::Cow::Borrowed(*cpu_name))
550 })
551 .map(|cpu_name| Cpu { cpu_name, remark: make_remark(cpu_name) })
552 .collect::<VecDeque<_>>();
553
554 if sess.host.arch == sess.target.arch && !sess.target.requires_consistent_cpu {
559 let host = get_host_cpu_name();
560 cpus.push_front(Cpu {
561 cpu_name: NATIVE_CPU,
562 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})."),
563 });
564 }
565
566 let max_name_width = cpus.iter().map(|cpu| cpu.cpu_name.len()).max().unwrap_or(0);
567 out.write_fmt(format_args!("Available CPUs for this target:\n"))writeln!(out, "Available CPUs for this target:").unwrap();
568 for Cpu { cpu_name, remark } in cpus {
569 let width = if remark.is_empty() { 0 } else { max_name_width };
571 out.write_fmt(format_args!(" {0:<1$}{2}\n", cpu_name, width, remark))writeln!(out, " {cpu_name:<width$}{remark}").unwrap();
572 }
573}
574
575fn print_target_features(sess: &Session, tm: &llvm::TargetMachine, out: &mut String) {
576 let mut llvm_target_features = llvm_target_features(tm);
577 let mut known_llvm_target_features = FxHashSet::<&'static str>::default();
578 let mut rustc_target_features = sess
579 .target
580 .rust_target_features()
581 .iter()
582 .filter_map(|(feature, gate, _implied)| {
583 if !gate.in_cfg() {
584 return None;
586 }
587 let llvm_feature = to_llvm_features(&sess.target, feature)?.llvm_feature_name;
590 let desc =
591 match llvm_target_features.binary_search_by_key(&llvm_feature, |(f, _d)| f).ok() {
592 Some(index) => {
593 known_llvm_target_features.insert(llvm_feature);
594 llvm_target_features[index].1
595 }
596 None => "",
597 };
598
599 Some((*feature, desc))
600 })
601 .collect::<Vec<_>>();
602
603 rustc_target_features.extend_from_slice(&[(
605 "crt-static",
606 "Enables C Run-time Libraries to be statically linked",
607 )]);
608 rustc_target_features.sort();
610
611 llvm_target_features.retain(|(f, _d)| !known_llvm_target_features.contains(f));
612
613 let max_feature_len = llvm_target_features
614 .iter()
615 .chain(rustc_target_features.iter())
616 .map(|(feature, _desc)| feature.len())
617 .max()
618 .unwrap_or(0);
619
620 out.write_fmt(format_args!("Features supported by rustc for this target:\n"))writeln!(out, "Features supported by rustc for this target:").unwrap();
621 for (feature, desc) in &rustc_target_features {
622 out.write_fmt(format_args!(" {0:1$} - {2}.\n", feature, max_feature_len,
desc))writeln!(out, " {feature:max_feature_len$} - {desc}.").unwrap();
623 }
624 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();
625 for (feature, desc) in &llvm_target_features {
626 out.write_fmt(format_args!(" {0:1$} - {2}.\n", feature, max_feature_len,
desc))writeln!(out, " {feature:max_feature_len$} - {desc}.").unwrap();
627 }
628 if llvm_target_features.is_empty() {
629 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.")
630 .unwrap();
631 }
632 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();
633 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")
634 .unwrap();
635 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();
636 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();
637}
638
639fn get_host_cpu_name() -> &'static str {
641 let mut len = 0;
642 let slice: &'static [u8] = unsafe {
645 let ptr = llvm::LLVMRustGetHostCPUName(&mut len);
646 if !!ptr.is_null() {
::core::panicking::panic("assertion failed: !ptr.is_null()")
};assert!(!ptr.is_null());
647 slice::from_raw_parts(ptr, len)
648 };
649 str::from_utf8(slice).expect("host CPU name should be UTF-8")
650}
651
652fn handle_native(cpu_name: &str) -> &str {
655 match cpu_name {
656 NATIVE_CPU => get_host_cpu_name(),
657 _ => cpu_name,
658 }
659}
660
661pub(crate) fn target_cpu(sess: &EarlySession) -> &str {
662 let cpu_name = sess.opts.cg.target_cpu.as_deref().unwrap_or_else(|| &sess.target.cpu);
663 handle_native(cpu_name)
664}
665
666fn llvm_features_by_flags(sess: &EarlySession, features: &mut Vec<String>) {
668 if wants_wasm_eh(&sess.target) && sess.panic_strategy() == PanicStrategy::Unwind {
669 features.push("+exception-handling".into());
670 }
671
672 target_features::retpoline_features_by_flags(sess, features);
673 target_features::sanitizer_features_by_flags(sess, features);
674
675 if sess.opts.unstable_opts.fixed_x18 {
677 if sess.target.arch != Arch::AArch64 {
678 sess.dcx()
679 .emit_fatal(diagnostics::FixedX18InvalidArch { arch: sess.target.arch.desc() });
680 } else {
681 features.push("+reserve-x18".into());
682 }
683 }
684}
685
686pub(crate) fn global_llvm_features(sess: &EarlySession, for_cfg: bool) -> Vec<String> {
693 let mut features = ::alloc::vec::Vec::new()vec![];
712
713 match sess.opts.cg.target_cpu {
715 Some(ref s) if s == NATIVE_CPU => {
716 let features_string = unsafe {
722 let ptr = llvm::LLVMGetHostCPUFeatures();
723 let features_string = if !ptr.is_null() {
724 CStr::from_ptr(ptr)
725 .to_str()
726 .unwrap_or_else(|e| {
727 ::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);
728 })
729 .to_owned()
730 } else {
731 ::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");
732 };
733
734 llvm::LLVMDisposeMessage(ptr);
735
736 features_string
737 };
738 if !features_string.is_empty() {
739 features.extend(features_string.split(',').map(String::from));
740 }
741 }
742 Some(_) | None => {}
743 };
744
745 let mut extend_backend_features = |feature: &str, enable: bool| {
746 let enable_disable = if enable { '+' } else { '-' };
747 let Some(llvm_feature) = to_llvm_features(&sess.target, feature) else { return };
752
753 features.extend(
754 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(
755 llvm_feature.dependencies.into_iter().filter_map(move |feat| {
756 match (enable, feat) {
757 (_, TargetFeatureFoldStrength::Both(f))
758 | (true, TargetFeatureFoldStrength::EnableOnly(f)) => {
759 Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}", enable_disable, f))
})format!("{enable_disable}{f}"))
760 }
761 _ => None,
762 }
763 }),
764 ),
765 );
766 };
767
768 target_features::target_spec_to_backend_features(sess, &mut extend_backend_features);
770
771 if !for_cfg {
775 target_features::flag_to_backend_features(sess, extend_backend_features);
776 }
777
778 llvm_features_by_flags(sess, &mut features);
783
784 for feature in sess.opts.unstable_opts.llvm_target_feature.split(',') {
787 if feature.is_empty() {
788 continue;
789 }
790 if feature.starts_with('+') || feature.starts_with('-') {
791 features.push(feature.to_owned());
792 } else {
793 if for_cfg {
796 sess.dcx().emit_warn(diagnostics::UnknownLlvmTargetFeaturePrefix { feature });
797 }
798 }
799 }
800
801 features
802}
803
804pub(crate) fn tune_cpu(sess: &Session) -> Option<&str> {
805 let name = sess.opts.unstable_opts.tune_cpu.as_ref()?;
806 Some(handle_native(name))
807}
808
809pub(crate) fn target_has_mnemonic(sess: &Session, mnemonic: &str) -> bool {
810 require_inited();
811 let tm = create_informational_target_machine(sess);
812 let cstr = SmallCStr::new(mnemonic);
813 unsafe { llvm::LLVMRustTargetHasMnemonic(tm.raw(), cstr.as_ptr()) }
814}