• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 use crate::back::write::create_informational_target_machine;
2 use crate::errors::{
3     PossibleFeature, TargetFeatureDisableOrEnable, UnknownCTargetFeature,
4     UnknownCTargetFeaturePrefix,
5 };
6 use crate::llvm;
7 use libc::c_int;
8 use rustc_codegen_ssa::target_features::{
9     supported_target_features, tied_target_features, RUSTC_SPECIFIC_FEATURES,
10 };
11 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
12 use rustc_data_structures::small_c_str::SmallCStr;
13 use rustc_fs_util::path_to_c_string;
14 use rustc_middle::bug;
15 use rustc_session::config::PrintRequest;
16 use rustc_session::Session;
17 use rustc_span::symbol::Symbol;
18 use rustc_target::spec::{MergeFunctions, PanicStrategy};
19 use std::ffi::{CStr, CString};
20 
21 use std::path::Path;
22 use std::ptr;
23 use std::slice;
24 use std::str;
25 use std::sync::Once;
26 
27 static INIT: Once = Once::new();
28 
init(sess: &Session)29 pub(crate) fn init(sess: &Session) {
30     unsafe {
31         // Before we touch LLVM, make sure that multithreading is enabled.
32         if llvm::LLVMIsMultithreaded() != 1 {
33             bug!("LLVM compiled without support for threads");
34         }
35         INIT.call_once(|| {
36             configure_llvm(sess);
37         });
38     }
39 }
40 
require_inited()41 fn require_inited() {
42     if !INIT.is_completed() {
43         bug!("LLVM is not initialized");
44     }
45 }
46 
configure_llvm(sess: &Session)47 unsafe fn configure_llvm(sess: &Session) {
48     let n_args = sess.opts.cg.llvm_args.len() + sess.target.llvm_args.len();
49     let mut llvm_c_strs = Vec::with_capacity(n_args + 1);
50     let mut llvm_args = Vec::with_capacity(n_args + 1);
51 
52     llvm::LLVMRustInstallFatalErrorHandler();
53     // On Windows, an LLVM assertion will open an Abort/Retry/Ignore dialog
54     // box for the purpose of launching a debugger. However, on CI this will
55     // cause it to hang until it times out, which can take several hours.
56     if std::env::var_os("CI").is_some() {
57         llvm::LLVMRustDisableSystemDialogsOnCrash();
58     }
59 
60     fn llvm_arg_to_arg_name(full_arg: &str) -> &str {
61         full_arg.trim().split(|c: char| c == '=' || c.is_whitespace()).next().unwrap_or("")
62     }
63 
64     let cg_opts = sess.opts.cg.llvm_args.iter().map(AsRef::as_ref);
65     let tg_opts = sess.target.llvm_args.iter().map(AsRef::as_ref);
66     let sess_args = cg_opts.chain(tg_opts);
67 
68     let user_specified_args: FxHashSet<_> =
69         sess_args.clone().map(|s| llvm_arg_to_arg_name(s)).filter(|s| !s.is_empty()).collect();
70 
71     {
72         // This adds the given argument to LLVM. Unless `force` is true
73         // user specified arguments are *not* overridden.
74         let mut add = |arg: &str, force: bool| {
75             if force || !user_specified_args.contains(llvm_arg_to_arg_name(arg)) {
76                 let s = CString::new(arg).unwrap();
77                 llvm_args.push(s.as_ptr());
78                 llvm_c_strs.push(s);
79             }
80         };
81         // Set the llvm "program name" to make usage and invalid argument messages more clear.
82         add("rustc -Cllvm-args=\"...\" with", true);
83         if sess.opts.unstable_opts.time_llvm_passes {
84             add("-time-passes", false);
85         }
86         if sess.opts.unstable_opts.print_llvm_passes {
87             add("-debug-pass=Structure", false);
88         }
89         if sess.target.generate_arange_section
90             && !sess.opts.unstable_opts.no_generate_arange_section
91         {
92             add("-generate-arange-section", false);
93         }
94 
95         match sess.opts.unstable_opts.merge_functions.unwrap_or(sess.target.merge_functions) {
96             MergeFunctions::Disabled | MergeFunctions::Trampolines => {}
97             MergeFunctions::Aliases => {
98                 add("-mergefunc-use-aliases", false);
99             }
100         }
101 
102         if sess.target.os == "emscripten" && sess.panic_strategy() == PanicStrategy::Unwind {
103             add("-enable-emscripten-cxx-exceptions", false);
104         }
105 
106         // HACK(eddyb) LLVM inserts `llvm.assume` calls to preserve align attributes
107         // during inlining. Unfortunately these may block other optimizations.
108         add("-preserve-alignment-assumptions-during-inlining=false", false);
109 
110         // Use non-zero `import-instr-limit` multiplier for cold callsites.
111         add("-import-cold-multiplier=0.1", false);
112 
113         for arg in sess_args {
114             add(&(*arg), true);
115         }
116     }
117 
118     if sess.opts.unstable_opts.llvm_time_trace {
119         llvm::LLVMTimeTraceProfilerInitialize();
120     }
121 
122     rustc_llvm::initialize_available_targets();
123 
124     llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int, llvm_args.as_ptr());
125 }
126 
time_trace_profiler_finish(file_name: &Path)127 pub fn time_trace_profiler_finish(file_name: &Path) {
128     unsafe {
129         let file_name = path_to_c_string(file_name);
130         llvm::LLVMTimeTraceProfilerFinish(file_name.as_ptr());
131     }
132 }
133 
134 pub enum TargetFeatureFoldStrength<'a> {
135     // The feature is only tied when enabling the feature, disabling
136     // this feature shouldn't disable the tied feature.
137     EnableOnly(&'a str),
138     // The feature is tied for both enabling and disabling this feature.
139     Both(&'a str),
140 }
141 
142 impl<'a> TargetFeatureFoldStrength<'a> {
as_str(&self) -> &'a str143     fn as_str(&self) -> &'a str {
144         match self {
145             TargetFeatureFoldStrength::EnableOnly(feat) => feat,
146             TargetFeatureFoldStrength::Both(feat) => feat,
147         }
148     }
149 }
150 
151 pub struct LLVMFeature<'a> {
152     pub llvm_feature_name: &'a str,
153     pub dependency: Option<TargetFeatureFoldStrength<'a>>,
154 }
155 
156 impl<'a> LLVMFeature<'a> {
new(llvm_feature_name: &'a str) -> Self157     pub fn new(llvm_feature_name: &'a str) -> Self {
158         Self { llvm_feature_name, dependency: None }
159     }
160 
with_dependency( llvm_feature_name: &'a str, dependency: TargetFeatureFoldStrength<'a>, ) -> Self161     pub fn with_dependency(
162         llvm_feature_name: &'a str,
163         dependency: TargetFeatureFoldStrength<'a>,
164     ) -> Self {
165         Self { llvm_feature_name, dependency: Some(dependency) }
166     }
167 
contains(&self, feat: &str) -> bool168     pub fn contains(&self, feat: &str) -> bool {
169         self.iter().any(|dep| dep == feat)
170     }
171 
iter(&'a self) -> impl Iterator<Item = &'a str>172     pub fn iter(&'a self) -> impl Iterator<Item = &'a str> {
173         let dependencies = self.dependency.iter().map(|feat| feat.as_str());
174         std::iter::once(self.llvm_feature_name).chain(dependencies)
175     }
176 }
177 
178 impl<'a> IntoIterator for LLVMFeature<'a> {
179     type Item = &'a str;
180     type IntoIter = impl Iterator<Item = &'a str>;
181 
into_iter(self) -> Self::IntoIter182     fn into_iter(self) -> Self::IntoIter {
183         let dependencies = self.dependency.into_iter().map(|feat| feat.as_str());
184         std::iter::once(self.llvm_feature_name).chain(dependencies)
185     }
186 }
187 
188 // WARNING: the features after applying `to_llvm_features` must be known
189 // to LLVM or the feature detection code will walk past the end of the feature
190 // array, leading to crashes.
191 //
192 // To find a list of LLVM's names, check llvm-project/llvm/include/llvm/Support/*TargetParser.def
193 // where the * matches the architecture's name
194 //
195 // For targets not present in the above location, see llvm-project/llvm/lib/Target/{ARCH}/*.td
196 // where `{ARCH}` is the architecture name. Look for instances of `SubtargetFeature`.
197 //
198 // Beware to not use the llvm github project for this, but check the git submodule
199 // found in src/llvm-project
200 // Though note that Rust can also be build with an external precompiled version of LLVM
201 // which might lead to failures if the oldest tested / supported LLVM version
202 // doesn't yet support the relevant intrinsics
to_llvm_features<'a>(sess: &Session, s: &'a str) -> LLVMFeature<'a>203 pub fn to_llvm_features<'a>(sess: &Session, s: &'a str) -> LLVMFeature<'a> {
204     let arch = if sess.target.arch == "x86_64" { "x86" } else { &*sess.target.arch };
205     match (arch, s) {
206         ("x86", "sse4.2") => {
207             LLVMFeature::with_dependency("sse4.2", TargetFeatureFoldStrength::EnableOnly("crc32"))
208         }
209         ("x86", "pclmulqdq") => LLVMFeature::new("pclmul"),
210         ("x86", "rdrand") => LLVMFeature::new("rdrnd"),
211         ("x86", "bmi1") => LLVMFeature::new("bmi"),
212         ("x86", "cmpxchg16b") => LLVMFeature::new("cx16"),
213         ("aarch64", "rcpc2") => LLVMFeature::new("rcpc-immo"),
214         ("aarch64", "dpb") => LLVMFeature::new("ccpp"),
215         ("aarch64", "dpb2") => LLVMFeature::new("ccdp"),
216         ("aarch64", "frintts") => LLVMFeature::new("fptoint"),
217         ("aarch64", "fcma") => LLVMFeature::new("complxnum"),
218         ("aarch64", "pmuv3") => LLVMFeature::new("perfmon"),
219         ("aarch64", "paca") => LLVMFeature::new("pauth"),
220         ("aarch64", "pacg") => LLVMFeature::new("pauth"),
221         // Rust ties fp and neon together.
222         ("aarch64", "neon") => {
223             LLVMFeature::with_dependency("neon", TargetFeatureFoldStrength::Both("fp-armv8"))
224         }
225         // In LLVM neon implicitly enables fp, but we manually enable
226         // neon when a feature only implicitly enables fp
227         ("aarch64", "f32mm") => {
228             LLVMFeature::with_dependency("f32mm", TargetFeatureFoldStrength::EnableOnly("neon"))
229         }
230         ("aarch64", "f64mm") => {
231             LLVMFeature::with_dependency("f64mm", TargetFeatureFoldStrength::EnableOnly("neon"))
232         }
233         ("aarch64", "fhm") => {
234             LLVMFeature::with_dependency("fp16fml", TargetFeatureFoldStrength::EnableOnly("neon"))
235         }
236         ("aarch64", "fp16") => {
237             LLVMFeature::with_dependency("fullfp16", TargetFeatureFoldStrength::EnableOnly("neon"))
238         }
239         ("aarch64", "jsconv") => {
240             LLVMFeature::with_dependency("jsconv", TargetFeatureFoldStrength::EnableOnly("neon"))
241         }
242         ("aarch64", "sve") => {
243             LLVMFeature::with_dependency("sve", TargetFeatureFoldStrength::EnableOnly("neon"))
244         }
245         ("aarch64", "sve2") => {
246             LLVMFeature::with_dependency("sve2", TargetFeatureFoldStrength::EnableOnly("neon"))
247         }
248         ("aarch64", "sve2-aes") => {
249             LLVMFeature::with_dependency("sve2-aes", TargetFeatureFoldStrength::EnableOnly("neon"))
250         }
251         ("aarch64", "sve2-sm4") => {
252             LLVMFeature::with_dependency("sve2-sm4", TargetFeatureFoldStrength::EnableOnly("neon"))
253         }
254         ("aarch64", "sve2-sha3") => {
255             LLVMFeature::with_dependency("sve2-sha3", TargetFeatureFoldStrength::EnableOnly("neon"))
256         }
257         ("aarch64", "sve2-bitperm") => LLVMFeature::with_dependency(
258             "sve2-bitperm",
259             TargetFeatureFoldStrength::EnableOnly("neon"),
260         ),
261         (_, s) => LLVMFeature::new(s),
262     }
263 }
264 
265 /// Given a map from target_features to whether they are enabled or disabled,
266 /// ensure only valid combinations are allowed.
check_tied_features( sess: &Session, features: &FxHashMap<&str, bool>, ) -> Option<&'static [&'static str]>267 pub fn check_tied_features(
268     sess: &Session,
269     features: &FxHashMap<&str, bool>,
270 ) -> Option<&'static [&'static str]> {
271     if !features.is_empty() {
272         for tied in tied_target_features(sess) {
273             // Tied features must be set to the same value, or not set at all
274             let mut tied_iter = tied.iter();
275             let enabled = features.get(tied_iter.next().unwrap());
276             if tied_iter.any(|f| enabled != features.get(f)) {
277                 return Some(tied);
278             }
279         }
280     }
281     return None;
282 }
283 
284 /// Used to generate cfg variables and apply features
285 /// Must express features in the way Rust understands them
target_features(sess: &Session, allow_unstable: bool) -> Vec<Symbol>286 pub fn target_features(sess: &Session, allow_unstable: bool) -> Vec<Symbol> {
287     let target_machine = create_informational_target_machine(sess);
288     supported_target_features(sess)
289         .iter()
290         .filter_map(|&(feature, gate)| {
291             if sess.is_nightly_build() || allow_unstable || gate.is_none() {
292                 Some(feature)
293             } else {
294                 None
295             }
296         })
297         .filter(|feature| {
298             // check that all features in a given smallvec are enabled
299             for llvm_feature in to_llvm_features(sess, feature) {
300                 let cstr = SmallCStr::new(llvm_feature);
301                 if !unsafe { llvm::LLVMRustHasFeature(target_machine, cstr.as_ptr()) } {
302                     return false;
303                 }
304             }
305             true
306         })
307         .map(|feature| Symbol::intern(feature))
308         .collect()
309 }
310 
print_version()311 pub fn print_version() {
312     let (major, minor, patch) = get_version();
313     println!("LLVM version: {}.{}.{}", major, minor, patch);
314 }
315 
get_version() -> (u32, u32, u32)316 pub fn get_version() -> (u32, u32, u32) {
317     // Can be called without initializing LLVM
318     unsafe {
319         (llvm::LLVMRustVersionMajor(), llvm::LLVMRustVersionMinor(), llvm::LLVMRustVersionPatch())
320     }
321 }
322 
print_passes()323 pub fn print_passes() {
324     // Can be called without initializing LLVM
325     unsafe {
326         llvm::LLVMRustPrintPasses();
327     }
328 }
329 
llvm_target_features(tm: &llvm::TargetMachine) -> Vec<(&str, &str)>330 fn llvm_target_features(tm: &llvm::TargetMachine) -> Vec<(&str, &str)> {
331     let len = unsafe { llvm::LLVMRustGetTargetFeaturesCount(tm) };
332     let mut ret = Vec::with_capacity(len);
333     for i in 0..len {
334         unsafe {
335             let mut feature = ptr::null();
336             let mut desc = ptr::null();
337             llvm::LLVMRustGetTargetFeature(tm, i, &mut feature, &mut desc);
338             if feature.is_null() || desc.is_null() {
339                 bug!("LLVM returned a `null` target feature string");
340             }
341             let feature = CStr::from_ptr(feature).to_str().unwrap_or_else(|e| {
342                 bug!("LLVM returned a non-utf8 feature string: {}", e);
343             });
344             let desc = CStr::from_ptr(desc).to_str().unwrap_or_else(|e| {
345                 bug!("LLVM returned a non-utf8 feature string: {}", e);
346             });
347             ret.push((feature, desc));
348         }
349     }
350     ret
351 }
352 
print_target_features(sess: &Session, tm: &llvm::TargetMachine)353 fn print_target_features(sess: &Session, tm: &llvm::TargetMachine) {
354     let mut llvm_target_features = llvm_target_features(tm);
355     let mut known_llvm_target_features = FxHashSet::<&'static str>::default();
356     let mut rustc_target_features = supported_target_features(sess)
357         .iter()
358         .map(|(feature, _gate)| {
359             // LLVM asserts that these are sorted. LLVM and Rust both use byte comparison for these strings.
360             let llvm_feature = to_llvm_features(sess, *feature).llvm_feature_name;
361             let desc =
362                 match llvm_target_features.binary_search_by_key(&llvm_feature, |(f, _d)| f).ok() {
363                     Some(index) => {
364                         known_llvm_target_features.insert(llvm_feature);
365                         llvm_target_features[index].1
366                     }
367                     None => "",
368                 };
369 
370             (*feature, desc)
371         })
372         .collect::<Vec<_>>();
373     rustc_target_features.extend_from_slice(&[(
374         "crt-static",
375         "Enables C Run-time Libraries to be statically linked",
376     )]);
377     llvm_target_features.retain(|(f, _d)| !known_llvm_target_features.contains(f));
378 
379     let max_feature_len = llvm_target_features
380         .iter()
381         .chain(rustc_target_features.iter())
382         .map(|(feature, _desc)| feature.len())
383         .max()
384         .unwrap_or(0);
385 
386     println!("Features supported by rustc for this target:");
387     for (feature, desc) in &rustc_target_features {
388         println!("    {1:0$} - {2}.", max_feature_len, feature, desc);
389     }
390     println!("\nCode-generation features supported by LLVM for this target:");
391     for (feature, desc) in &llvm_target_features {
392         println!("    {1:0$} - {2}.", max_feature_len, feature, desc);
393     }
394     if llvm_target_features.is_empty() {
395         println!("    Target features listing is not supported by this LLVM version.");
396     }
397     println!("\nUse +feature to enable a feature, or -feature to disable it.");
398     println!("For example, rustc -C target-cpu=mycpu -C target-feature=+feature1,-feature2\n");
399     println!("Code-generation features cannot be used in cfg or #[target_feature],");
400     println!("and may be renamed or removed in a future version of LLVM or rustc.\n");
401 }
402 
print(req: PrintRequest, sess: &Session)403 pub(crate) fn print(req: PrintRequest, sess: &Session) {
404     require_inited();
405     let tm = create_informational_target_machine(sess);
406     match req {
407         PrintRequest::TargetCPUs => {
408             // SAFETY generate a C compatible string from a byte slice to pass
409             // the target CPU name into LLVM, the lifetime of the reference is
410             // at least as long as the C function
411             let cpu_cstring = CString::new(handle_native(sess.target.cpu.as_ref()))
412                 .unwrap_or_else(|e| bug!("failed to convert to cstring: {}", e));
413             unsafe { llvm::LLVMRustPrintTargetCPUs(tm, cpu_cstring.as_ptr()) };
414         }
415         PrintRequest::TargetFeatures => print_target_features(sess, tm),
416         _ => bug!("rustc_codegen_llvm can't handle print request: {:?}", req),
417     }
418 }
419 
handle_native(name: &str) -> &str420 fn handle_native(name: &str) -> &str {
421     if name != "native" {
422         return name;
423     }
424 
425     unsafe {
426         let mut len = 0;
427         let ptr = llvm::LLVMRustGetHostCPUName(&mut len);
428         str::from_utf8(slice::from_raw_parts(ptr as *const u8, len)).unwrap()
429     }
430 }
431 
target_cpu(sess: &Session) -> &str432 pub fn target_cpu(sess: &Session) -> &str {
433     match sess.opts.cg.target_cpu {
434         Some(ref name) => handle_native(name),
435         None => handle_native(sess.target.cpu.as_ref()),
436     }
437 }
438 
439 /// The list of LLVM features computed from CLI flags (`-Ctarget-cpu`, `-Ctarget-feature`,
440 /// `--target` and similar).
global_llvm_features(sess: &Session, diagnostics: bool) -> Vec<String>441 pub(crate) fn global_llvm_features(sess: &Session, diagnostics: bool) -> Vec<String> {
442     // Features that come earlier are overridden by conflicting features later in the string.
443     // Typically we'll want more explicit settings to override the implicit ones, so:
444     //
445     // * Features from -Ctarget-cpu=*; are overridden by [^1]
446     // * Features implied by --target; are overridden by
447     // * Features from -Ctarget-feature; are overridden by
448     // * function specific features.
449     //
450     // [^1]: target-cpu=native is handled here, other target-cpu values are handled implicitly
451     // through LLVM TargetMachine implementation.
452     //
453     // FIXME(nagisa): it isn't clear what's the best interaction between features implied by
454     // `-Ctarget-cpu` and `--target` are. On one hand, you'd expect CLI arguments to always
455     // override anything that's implicit, so e.g. when there's no `--target` flag, features implied
456     // the host target are overridden by `-Ctarget-cpu=*`. On the other hand, what about when both
457     // `--target` and `-Ctarget-cpu=*` are specified? Both then imply some target features and both
458     // flags are specified by the user on the CLI. It isn't as clear-cut which order of precedence
459     // should be taken in cases like these.
460     let mut features = vec![];
461 
462     // -Ctarget-cpu=native
463     match sess.opts.cg.target_cpu {
464         Some(ref s) if s == "native" => {
465             let features_string = unsafe {
466                 let ptr = llvm::LLVMGetHostCPUFeatures();
467                 let features_string = if !ptr.is_null() {
468                     CStr::from_ptr(ptr)
469                         .to_str()
470                         .unwrap_or_else(|e| {
471                             bug!("LLVM returned a non-utf8 features string: {}", e);
472                         })
473                         .to_owned()
474                 } else {
475                     bug!("could not allocate host CPU features, LLVM returned a `null` string");
476                 };
477 
478                 llvm::LLVMDisposeMessage(ptr);
479 
480                 features_string
481             };
482             features.extend(features_string.split(',').map(String::from));
483         }
484         Some(_) | None => {}
485     };
486 
487     // Features implied by an implicit or explicit `--target`.
488     features.extend(
489         sess.target
490             .features
491             .split(',')
492             .filter(|v| !v.is_empty() && backend_feature_name(v).is_some())
493             // Drop +atomics-32 feature introduced in LLVM 15.
494             .filter(|v| *v != "+atomics-32" || get_version() >= (15, 0, 0))
495             .map(String::from),
496     );
497 
498     // -Ctarget-features
499     let supported_features = supported_target_features(sess);
500     let mut featsmap = FxHashMap::default();
501     let feats = sess
502         .opts
503         .cg
504         .target_feature
505         .split(',')
506         .filter_map(|s| {
507             let enable_disable = match s.chars().next() {
508                 None => return None,
509                 Some(c @ ('+' | '-')) => c,
510                 Some(_) => {
511                     if diagnostics {
512                         sess.emit_warning(UnknownCTargetFeaturePrefix { feature: s });
513                     }
514                     return None;
515                 }
516             };
517 
518             let feature = backend_feature_name(s)?;
519             // Warn against use of LLVM specific feature names on the CLI.
520             if diagnostics && !supported_features.iter().any(|&(v, _)| v == feature) {
521                 let rust_feature = supported_features.iter().find_map(|&(rust_feature, _)| {
522                     let llvm_features = to_llvm_features(sess, rust_feature);
523                     if llvm_features.contains(&feature) && !llvm_features.contains(&rust_feature) {
524                         Some(rust_feature)
525                     } else {
526                         None
527                     }
528                 });
529                 let unknown_feature = if let Some(rust_feature) = rust_feature {
530                     UnknownCTargetFeature {
531                         feature,
532                         rust_feature: PossibleFeature::Some { rust_feature },
533                     }
534                 } else {
535                     UnknownCTargetFeature { feature, rust_feature: PossibleFeature::None }
536                 };
537                 sess.emit_warning(unknown_feature);
538             }
539 
540             if diagnostics {
541                 // FIXME(nagisa): figure out how to not allocate a full hashset here.
542                 featsmap.insert(feature, enable_disable == '+');
543             }
544 
545             // rustc-specific features do not get passed down to LLVM…
546             if RUSTC_SPECIFIC_FEATURES.contains(&feature) {
547                 return None;
548             }
549             // ... otherwise though we run through `to_llvm_features` when
550             // passing requests down to LLVM. This means that all in-language
551             // features also work on the command line instead of having two
552             // different names when the LLVM name and the Rust name differ.
553             let llvm_feature = to_llvm_features(sess, feature);
554 
555             Some(
556                 std::iter::once(format!("{}{}", enable_disable, llvm_feature.llvm_feature_name))
557                     .chain(llvm_feature.dependency.into_iter().filter_map(move |feat| {
558                         match (enable_disable, feat) {
559                             ('-' | '+', TargetFeatureFoldStrength::Both(f))
560                             | ('+', TargetFeatureFoldStrength::EnableOnly(f)) => {
561                                 Some(format!("{}{}", enable_disable, f))
562                             }
563                             _ => None,
564                         }
565                     })),
566             )
567         })
568         .flatten();
569     features.extend(feats);
570 
571     if diagnostics && let Some(f) = check_tied_features(sess, &featsmap) {
572         sess.emit_err(TargetFeatureDisableOrEnable {
573             features: f,
574             span: None,
575             missing_features: None,
576         });
577     }
578 
579     features
580 }
581 
582 /// Returns a feature name for the given `+feature` or `-feature` string.
583 ///
584 /// Only allows features that are backend specific (i.e. not [`RUSTC_SPECIFIC_FEATURES`].)
backend_feature_name(s: &str) -> Option<&str>585 fn backend_feature_name(s: &str) -> Option<&str> {
586     // features must start with a `+` or `-`.
587     let feature = s.strip_prefix(&['+', '-'][..]).unwrap_or_else(|| {
588         bug!("target feature `{}` must begin with a `+` or `-`", s);
589     });
590     // Rustc-specific feature requests like `+crt-static` or `-crt-static`
591     // are not passed down to LLVM.
592     if RUSTC_SPECIFIC_FEATURES.contains(&feature) {
593         return None;
594     }
595     Some(feature)
596 }
597 
tune_cpu(sess: &Session) -> Option<&str>598 pub fn tune_cpu(sess: &Session) -> Option<&str> {
599     let name = sess.opts.unstable_opts.tune_cpu.as_ref()?;
600     Some(handle_native(name))
601 }
602