1use std::collections::VecDeque;
2use std::ffi::{CStr, CString};
3use std::fmt::Write;
4use std::path::Path;
5use std::sync::Once;
6use std::{ptr, slice, str};
7
8use libc::c_int;
9use rustc_codegen_ssa::base::wants_wasm_eh;
10use rustc_codegen_ssa::target_features::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::{Arch, MergeFunctions, PanicStrategy, SmallDataThresholdSupport};
19use smallvec::{SmallVec, smallvec};
20
21use crate::back::write::create_informational_target_machine;
22use crate::{errors, llvm};
23
24static INIT: Once = Once::new();
25
26pub(crate) fn init(sess: &Session) {
27 unsafe {
28 if !llvm::LLVMIsMultithreaded().is_true() {
30 bug!("LLVM compiled without support for threads");
31 }
32 INIT.call_once(|| {
33 configure_llvm(sess);
34 });
35 }
36}
37
38fn require_inited() {
39 if !INIT.is_completed() {
40 bug!("LLVM is not initialized");
41 }
42}
43
44unsafe fn configure_llvm(sess: &Session) {
45 let n_args = sess.opts.cg.llvm_args.len() + sess.target.llvm_args.len();
46 let mut llvm_c_strs = Vec::with_capacity(n_args + 1);
47 let mut llvm_args = Vec::with_capacity(n_args + 1);
48
49 unsafe {
50 llvm::LLVMRustInstallErrorHandlers();
51 }
52 if std::env::var_os("CI").is_some() {
56 unsafe {
57 llvm::LLVMRustDisableSystemDialogsOnCrash();
58 }
59 }
60
61 fn llvm_arg_to_arg_name(full_arg: &str) -> &str {
62 full_arg.trim().split(|c: char| c == '=' || c.is_whitespace()).next().unwrap_or("")
63 }
64
65 let cg_opts = sess.opts.cg.llvm_args.iter().map(AsRef::as_ref);
66 let tg_opts = sess.target.llvm_args.iter().map(AsRef::as_ref);
67 let sess_args = cg_opts.chain(tg_opts);
68
69 let user_specified_args: FxHashSet<_> =
70 sess_args.clone().map(|s| llvm_arg_to_arg_name(s)).filter(|s| !s.is_empty()).collect();
71
72 {
73 let mut add = |arg: &str, force: bool| {
76 if force || !user_specified_args.contains(llvm_arg_to_arg_name(arg)) {
77 let s = CString::new(arg).unwrap();
78 llvm_args.push(s.as_ptr());
79 llvm_c_strs.push(s);
80 }
81 };
82 add("rustc -Cllvm-args=\"...\" with", true);
84 if sess.opts.unstable_opts.time_llvm_passes {
85 add("-time-passes", false);
86 }
87 if sess.opts.unstable_opts.print_llvm_passes {
88 add("-debug-pass=Structure", false);
89 }
90 if sess.target.generate_arange_section
91 && !sess.opts.unstable_opts.no_generate_arange_section
92 {
93 add("-generate-arange-section", false);
94 }
95
96 match sess.opts.unstable_opts.merge_functions.unwrap_or(sess.target.merge_functions) {
97 MergeFunctions::Disabled | MergeFunctions::Trampolines => {}
98 MergeFunctions::Aliases => {
99 add("-mergefunc-use-aliases", false);
100 }
101 }
102
103 if wants_wasm_eh(sess) {
104 add("-wasm-enable-eh", false);
105 }
106
107 if sess.target.os == "emscripten"
108 && !sess.opts.unstable_opts.emscripten_wasm_eh
109 && sess.panic_strategy().unwinds()
110 {
111 add("-enable-emscripten-cxx-exceptions", false);
112 }
113
114 add("-preserve-alignment-assumptions-during-inlining=false", false);
117
118 add("-import-cold-multiplier=0.1", false);
120
121 if sess.print_llvm_stats() {
122 add("-stats", false);
123 }
124
125 for arg in sess_args {
126 add(&(*arg), true);
127 }
128
129 match (
130 sess.opts.unstable_opts.small_data_threshold,
131 sess.target.small_data_threshold_support(),
132 ) {
133 (Some(threshold), SmallDataThresholdSupport::LlvmArg(arg)) => {
136 add(&format!("--{arg}={threshold}"), false)
137 }
138 _ => (),
139 };
140 }
141
142 if sess.opts.unstable_opts.llvm_time_trace {
143 unsafe { llvm::LLVMRustTimeTraceProfilerInitialize() };
144 }
145
146 rustc_llvm::initialize_available_targets();
147
148 unsafe { llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int, llvm_args.as_ptr()) };
149}
150
151pub(crate) fn time_trace_profiler_finish(file_name: &Path) {
152 unsafe {
153 let file_name = path_to_c_string(file_name);
154 llvm::LLVMRustTimeTraceProfilerFinish(file_name.as_ptr());
155 }
156}
157
158enum TargetFeatureFoldStrength<'a> {
159 EnableOnly(&'a str),
162 Both(&'a str),
164}
165
166impl<'a> TargetFeatureFoldStrength<'a> {
167 fn as_str(&self) -> &'a str {
168 match self {
169 TargetFeatureFoldStrength::EnableOnly(feat) => feat,
170 TargetFeatureFoldStrength::Both(feat) => feat,
171 }
172 }
173}
174
175pub(crate) struct LLVMFeature<'a> {
176 llvm_feature_name: &'a str,
177 dependencies: SmallVec<[TargetFeatureFoldStrength<'a>; 1]>,
178}
179
180impl<'a> LLVMFeature<'a> {
181 fn new(llvm_feature_name: &'a str) -> Self {
182 Self { llvm_feature_name, dependencies: SmallVec::new() }
183 }
184
185 fn with_dependencies(
186 llvm_feature_name: &'a str,
187 dependencies: SmallVec<[TargetFeatureFoldStrength<'a>; 1]>,
188 ) -> Self {
189 Self { llvm_feature_name, dependencies }
190 }
191}
192
193impl<'a> IntoIterator for LLVMFeature<'a> {
194 type Item = &'a str;
195 type IntoIter = impl Iterator<Item = &'a str>;
196
197 fn into_iter(self) -> Self::IntoIter {
198 let dependencies = self.dependencies.into_iter().map(|feat| feat.as_str());
199 std::iter::once(self.llvm_feature_name).chain(dependencies)
200 }
201}
202
203pub(crate) fn to_llvm_features<'a>(sess: &Session, s: &'a str) -> Option<LLVMFeature<'a>> {
220 let (major, _, _) = get_version();
221 match sess.target.arch {
222 Arch::AArch64 | Arch::Arm64EC => {
223 match s {
224 "rcpc2" => Some(LLVMFeature::new("rcpc-immo")),
225 "dpb" => Some(LLVMFeature::new("ccpp")),
226 "dpb2" => Some(LLVMFeature::new("ccdp")),
227 "frintts" => Some(LLVMFeature::new("fptoint")),
228 "fcma" => Some(LLVMFeature::new("complxnum")),
229 "pmuv3" => Some(LLVMFeature::new("perfmon")),
230 "paca" => Some(LLVMFeature::new("pauth")),
231 "pacg" => Some(LLVMFeature::new("pauth")),
232 "flagm2" => Some(LLVMFeature::new("altnzcv")),
233 "neon" => Some(LLVMFeature::with_dependencies(
235 "neon",
236 smallvec![TargetFeatureFoldStrength::Both("fp-armv8")],
237 )),
238 "fhm" => Some(LLVMFeature::new("fp16fml")),
241 "fp16" => Some(LLVMFeature::new("fullfp16")),
242 "fpmr" => None, 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
252 Arch::LoongArch32 | Arch::LoongArch64 => match s {
254 "32s" if major < 21 => None,
255 s => Some(LLVMFeature::new(s)),
256 },
257 Arch::PowerPC | Arch::PowerPC64 => match s {
258 "power8-crypto" => Some(LLVMFeature::new("crypto")),
259 s => Some(LLVMFeature::new(s)),
260 },
261 Arch::Sparc | Arch::Sparc64 => match s {
262 "leoncasa" => Some(LLVMFeature::new("hasleoncasa")),
263 s => Some(LLVMFeature::new(s)),
264 },
265 Arch::X86 | Arch::X86_64 => {
266 match s {
267 "sse4.2" => Some(LLVMFeature::with_dependencies(
268 "sse4.2",
269 smallvec![TargetFeatureFoldStrength::EnableOnly("crc32")],
270 )),
271 "pclmulqdq" => Some(LLVMFeature::new("pclmul")),
272 "rdrand" => Some(LLVMFeature::new("rdrnd")),
273 "bmi1" => Some(LLVMFeature::new("bmi")),
274 "cmpxchg16b" => Some(LLVMFeature::new("cx16")),
275 "lahfsahf" => Some(LLVMFeature::new("sahf")),
276 s if s.starts_with("avx512") => Some(LLVMFeature::with_dependencies(
278 s,
279 smallvec![TargetFeatureFoldStrength::EnableOnly("evex512")],
280 )),
281 "avx10.1" => Some(LLVMFeature::new("avx10.1-512")),
282 "avx10.2" => Some(LLVMFeature::new("avx10.2-512")),
283 "apxf" => Some(LLVMFeature::with_dependencies(
284 "egpr",
285 smallvec![
286 TargetFeatureFoldStrength::Both("push2pop2"),
287 TargetFeatureFoldStrength::Both("ppx"),
288 TargetFeatureFoldStrength::Both("ndd"),
289 TargetFeatureFoldStrength::Both("ccmp"),
290 TargetFeatureFoldStrength::Both("cf"),
291 TargetFeatureFoldStrength::Both("nf"),
292 TargetFeatureFoldStrength::Both("zu"),
293 ],
294 )),
295 s => Some(LLVMFeature::new(s)),
296 }
297 }
298 _ => Some(LLVMFeature::new(s)),
299 }
300}
301
302pub(crate) fn target_config(sess: &Session) -> TargetConfig {
307 let target_machine = create_informational_target_machine(sess, true);
308
309 let (unstable_target_features, target_features) = cfg_target_feature(
310 sess,
311 |feature| {
312 to_llvm_features(sess, feature)
313 .map(|f| SmallVec::<[&str; 2]>::from_iter(f.into_iter()))
314 .unwrap_or_default()
315 },
316 |feature| {
317 if let Some(feat) = to_llvm_features(sess, feature) {
321 for llvm_feature in feat {
323 let cstr = SmallCStr::new(llvm_feature);
324 if !unsafe { llvm::LLVMRustHasFeature(target_machine.raw(), cstr.as_ptr()) } {
328 return false;
329 }
330 }
331 true
332 } else {
333 false
334 }
335 },
336 );
337
338 let mut cfg = TargetConfig {
339 target_features,
340 unstable_target_features,
341 has_reliable_f16: true,
342 has_reliable_f16_math: true,
343 has_reliable_f128: true,
344 has_reliable_f128_math: true,
345 };
346
347 update_target_reliable_float_cfg(sess, &mut cfg);
348 cfg
349}
350
351fn update_target_reliable_float_cfg(sess: &Session, cfg: &mut TargetConfig) {
353 let target_arch = &sess.target.arch;
354 let target_os = sess.target.options.os.as_ref();
355 let target_env = sess.target.options.env.as_ref();
356 let target_abi = sess.target.options.abi.as_ref();
357 let target_pointer_width = sess.target.pointer_width;
358 let version = get_version();
359 let lt_20_1_1 = version < (20, 1, 1);
360 let lt_21_0_0 = version < (21, 0, 0);
361
362 cfg.has_reliable_f16 = match (target_arch, target_os) {
363 (Arch::AArch64, _)
365 if !cfg.target_features.iter().any(|f| f.as_str() == "neon") && lt_20_1_1 =>
366 {
367 false
368 }
369 (Arch::Arm64EC, _) => false,
371 (Arch::S390x, _) if lt_21_0_0 => false,
373 (Arch::X86_64, "windows") if target_env == "gnu" && target_abi != "llvm" => false,
375 (Arch::CSky, _) => false,
377 (Arch::Hexagon, _) if lt_21_0_0 => false, (Arch::PowerPC | Arch::PowerPC64, _) => false,
379 (Arch::Sparc | Arch::Sparc64, _) => false,
380 (Arch::Wasm32 | Arch::Wasm64, _) => false,
381 _ => true,
385 };
386
387 cfg.has_reliable_f128 = match (target_arch, target_os) {
388 (Arch::Arm64EC, _) => false,
390 (Arch::Mips64 | Arch::Mips64r6, _) if lt_20_1_1 => false,
392 (Arch::Nvptx64, _) => false,
395 (Arch::AmdGpu, _) => false,
397 (Arch::PowerPC | Arch::PowerPC64, _) => false,
400 (Arch::Sparc, _) => false,
402 (Arch::X86, _) if lt_21_0_0 => false,
405 (Arch::X86_64, "windows") if target_env == "gnu" && target_abi != "llvm" => false,
407 _ => true,
411 };
412
413 cfg.has_reliable_f16_math = cfg.has_reliable_f16;
416
417 cfg.has_reliable_f128_math = match (target_arch, target_os) {
418 _ if target_env == "musl" => false,
428 (Arch::X86_64, _) => false,
429 (_, "linux") if target_pointer_width == 64 => true,
430 _ => false,
431 } && cfg.has_reliable_f128;
432}
433
434pub(crate) fn print_version() {
435 let (major, minor, patch) = get_version();
436 println!("LLVM version: {major}.{minor}.{patch}");
437}
438
439pub(crate) fn get_version() -> (u32, u32, u32) {
440 unsafe {
442 (llvm::LLVMRustVersionMajor(), llvm::LLVMRustVersionMinor(), llvm::LLVMRustVersionPatch())
443 }
444}
445
446pub(crate) fn print_passes() {
447 unsafe {
449 llvm::LLVMRustPrintPasses();
450 }
451}
452
453fn llvm_target_features(tm: &llvm::TargetMachine) -> Vec<(&str, &str)> {
454 let len = unsafe { llvm::LLVMRustGetTargetFeaturesCount(tm) };
455 let mut ret = Vec::with_capacity(len);
456 for i in 0..len {
457 unsafe {
458 let mut feature = ptr::null();
459 let mut desc = ptr::null();
460 llvm::LLVMRustGetTargetFeature(tm, i, &mut feature, &mut desc);
461 if feature.is_null() || desc.is_null() {
462 bug!("LLVM returned a `null` target feature string");
463 }
464 let feature = CStr::from_ptr(feature).to_str().unwrap_or_else(|e| {
465 bug!("LLVM returned a non-utf8 feature string: {}", e);
466 });
467 let desc = CStr::from_ptr(desc).to_str().unwrap_or_else(|e| {
468 bug!("LLVM returned a non-utf8 feature string: {}", e);
469 });
470 ret.push((feature, desc));
471 }
472 }
473 ret
474}
475
476pub(crate) fn print(req: &PrintRequest, out: &mut String, sess: &Session) {
477 require_inited();
478 let tm = create_informational_target_machine(sess, false);
479 match req.kind {
480 PrintKind::TargetCPUs => print_target_cpus(sess, tm.raw(), out),
481 PrintKind::TargetFeatures => print_target_features(sess, tm.raw(), out),
482 _ => bug!("rustc_codegen_llvm can't handle print request: {:?}", req),
483 }
484}
485
486fn print_target_cpus(sess: &Session, tm: &llvm::TargetMachine, out: &mut String) {
487 let cpu_names = llvm::build_string(|s| unsafe {
488 llvm::LLVMRustPrintTargetCPUs(&tm, s);
489 })
490 .unwrap();
491
492 struct Cpu<'a> {
493 cpu_name: &'a str,
494 remark: String,
495 }
496 let target_cpu = handle_native(&sess.target.cpu);
498 let make_remark = |cpu_name| {
499 if cpu_name == target_cpu {
500 let target = &sess.target.llvm_target;
503 format!(
504 " - This is the default target CPU for the current build target (currently {target})."
505 )
506 } else {
507 "".to_owned()
508 }
509 };
510 let mut cpus = cpu_names
511 .lines()
512 .map(|cpu_name| Cpu { cpu_name, remark: make_remark(cpu_name) })
513 .collect::<VecDeque<_>>();
514
515 if sess.host.arch == sess.target.arch {
518 let host = get_host_cpu_name();
519 cpus.push_front(Cpu {
520 cpu_name: "native",
521 remark: format!(" - Select the CPU of the current host (currently {host})."),
522 });
523 }
524
525 let max_name_width = cpus.iter().map(|cpu| cpu.cpu_name.len()).max().unwrap_or(0);
526 writeln!(out, "Available CPUs for this target:").unwrap();
527 for Cpu { cpu_name, remark } in cpus {
528 let width = if remark.is_empty() { 0 } else { max_name_width };
530 writeln!(out, " {cpu_name:<width$}{remark}").unwrap();
531 }
532}
533
534fn print_target_features(sess: &Session, tm: &llvm::TargetMachine, out: &mut String) {
535 let mut llvm_target_features = llvm_target_features(tm);
536 let mut known_llvm_target_features = FxHashSet::<&'static str>::default();
537 let mut rustc_target_features = sess
538 .target
539 .rust_target_features()
540 .iter()
541 .filter_map(|(feature, gate, _implied)| {
542 if !gate.in_cfg() {
543 return None;
545 }
546 let llvm_feature = to_llvm_features(sess, *feature)?.llvm_feature_name;
549 let desc =
550 match llvm_target_features.binary_search_by_key(&llvm_feature, |(f, _d)| f).ok() {
551 Some(index) => {
552 known_llvm_target_features.insert(llvm_feature);
553 llvm_target_features[index].1
554 }
555 None => "",
556 };
557
558 Some((*feature, desc))
559 })
560 .collect::<Vec<_>>();
561
562 rustc_target_features.extend_from_slice(&[(
564 "crt-static",
565 "Enables C Run-time Libraries to be statically linked",
566 )]);
567 rustc_target_features.sort();
569
570 llvm_target_features.retain(|(f, _d)| !known_llvm_target_features.contains(f));
571
572 let max_feature_len = llvm_target_features
573 .iter()
574 .chain(rustc_target_features.iter())
575 .map(|(feature, _desc)| feature.len())
576 .max()
577 .unwrap_or(0);
578
579 writeln!(out, "Features supported by rustc for this target:").unwrap();
580 for (feature, desc) in &rustc_target_features {
581 writeln!(out, " {feature:max_feature_len$} - {desc}.").unwrap();
582 }
583 writeln!(out, "\nCode-generation features supported by LLVM for this target:").unwrap();
584 for (feature, desc) in &llvm_target_features {
585 writeln!(out, " {feature:max_feature_len$} - {desc}.").unwrap();
586 }
587 if llvm_target_features.is_empty() {
588 writeln!(out, " Target features listing is not supported by this LLVM version.")
589 .unwrap();
590 }
591 writeln!(out, "\nUse +feature to enable a feature, or -feature to disable it.").unwrap();
592 writeln!(out, "For example, rustc -C target-cpu=mycpu -C target-feature=+feature1,-feature2\n")
593 .unwrap();
594 writeln!(out, "Code-generation features cannot be used in cfg or #[target_feature],").unwrap();
595 writeln!(out, "and may be renamed or removed in a future version of LLVM or rustc.\n").unwrap();
596}
597
598fn get_host_cpu_name() -> &'static str {
600 let mut len = 0;
601 let slice: &'static [u8] = unsafe {
604 let ptr = llvm::LLVMRustGetHostCPUName(&mut len);
605 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}
610
611fn handle_native(cpu_name: &str) -> &str {
614 match cpu_name {
615 "native" => get_host_cpu_name(),
616 _ => cpu_name,
617 }
618}
619
620pub(crate) fn target_cpu(sess: &Session) -> &str {
621 let cpu_name = sess.opts.cg.target_cpu.as_deref().unwrap_or_else(|| &sess.target.cpu);
622 handle_native(cpu_name)
623}
624
625fn llvm_features_by_flags(sess: &Session, features: &mut Vec<String>) {
627 target_features::retpoline_features_by_flags(sess, features);
628
629 if sess.opts.unstable_opts.fixed_x18 {
631 if sess.target.arch != Arch::AArch64 {
632 sess.dcx().emit_fatal(errors::FixedX18InvalidArch { arch: sess.target.arch.desc() });
633 } else {
634 features.push("+reserve-x18".into());
635 }
636 }
637}
638
639pub(crate) fn global_llvm_features(sess: &Session, only_base_features: bool) -> Vec<String> {
642 let mut features = vec![];
661
662 match sess.opts.cg.target_cpu {
664 Some(ref s) if s == "native" => {
665 let features_string = unsafe {
671 let ptr = llvm::LLVMGetHostCPUFeatures();
672 let features_string = if !ptr.is_null() {
673 CStr::from_ptr(ptr)
674 .to_str()
675 .unwrap_or_else(|e| {
676 bug!("LLVM returned a non-utf8 features string: {}", e);
677 })
678 .to_owned()
679 } else {
680 bug!("could not allocate host CPU features, LLVM returned a `null` string");
681 };
682
683 llvm::LLVMDisposeMessage(ptr);
684
685 features_string
686 };
687 features.extend(features_string.split(',').map(String::from));
688 }
689 Some(_) | None => {}
690 };
691
692 features.extend(sess.target.features.split(',').filter(|v| !v.is_empty()).map(String::from));
694
695 if wants_wasm_eh(sess) && sess.panic_strategy() == PanicStrategy::Unwind {
696 features.push("+exception-handling".into());
697 }
698
699 if !only_base_features {
701 target_features::flag_to_backend_features(sess, |feature, enable| {
702 let enable_disable = if enable { '+' } else { '-' };
703 let Some(llvm_feature) = to_llvm_features(sess, feature) else { return };
708
709 features.extend(
710 std::iter::once(format!("{}{}", enable_disable, llvm_feature.llvm_feature_name))
711 .chain(llvm_feature.dependencies.into_iter().filter_map(move |feat| {
712 match (enable, feat) {
713 (_, TargetFeatureFoldStrength::Both(f))
714 | (true, TargetFeatureFoldStrength::EnableOnly(f)) => {
715 Some(format!("{enable_disable}{f}"))
716 }
717 _ => None,
718 }
719 })),
720 )
721 });
722 }
723
724 llvm_features_by_flags(sess, &mut features);
726
727 features
728}
729
730pub(crate) fn tune_cpu(sess: &Session) -> Option<&str> {
731 let name = sess.opts.unstable_opts.tune_cpu.as_ref()?;
732 Some(handle_native(name))
733}