Skip to main content

rustc_codegen_ssa/
target_features.rs

1use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};
2use rustc_data_structures::unord::{UnordMap, UnordSet};
3use rustc_hir::attrs::InstructionSetAttr;
4use rustc_hir::def::DefKind;
5use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId};
6use rustc_middle::middle::codegen_fn_attrs::{TargetFeature, TargetFeatureKind};
7use rustc_middle::query::Providers;
8use rustc_middle::ty::TyCtxt;
9use rustc_session::Session;
10use rustc_session::errors::feature_err;
11use rustc_session::lint::builtin::AARCH64_SOFTFLOAT_NEON;
12use rustc_span::{Span, Symbol, edit_distance, sym};
13use rustc_target::spec::{Arch, SanitizerSet};
14use rustc_target::target_features::{RUSTC_SPECIFIC_FEATURES, Stability};
15use smallvec::SmallVec;
16
17use crate::errors::{FeatureNotValid, FeatureNotValidHint};
18use crate::{errors, target_features};
19
20/// Compute the enabled target features from the `#[target_feature]` function attribute.
21/// Enabled target features are added to `target_features`.
22pub(crate) fn from_target_feature_attr(
23    tcx: TyCtxt<'_>,
24    did: LocalDefId,
25    features: &[(Symbol, Span)],
26    was_forced: bool,
27    rust_target_features: &UnordMap<String, target_features::Stability>,
28    target_features: &mut Vec<TargetFeature>,
29) {
30    let rust_features = tcx.features();
31    let abi_feature_constraints = tcx.sess.target.abi_required_features();
32    for &(feature, feature_span) in features {
33        let feature_str = feature.as_str();
34        let Some(stability) = rust_target_features.get(feature_str) else {
35            let hint = if let Some(stripped) = feature_str.strip_prefix('+')
36                && rust_target_features.contains_key(stripped)
37            {
38                FeatureNotValidHint::RemovePlusFromFeatureName { span: feature_span, stripped }
39            } else {
40                // Show the 5 feature names that are most similar to the input.
41                let mut valid_names: Vec<_> =
42                    rust_target_features.keys().map(|name| name.as_str()).into_sorted_stable_ord();
43                valid_names.sort_by_key(|name| {
44                    edit_distance::edit_distance(name, feature.as_str(), 5).unwrap_or(usize::MAX)
45                });
46                valid_names.truncate(5);
47
48                FeatureNotValidHint::ValidFeatureNames {
49                    possibilities: valid_names.into(),
50                    and_more: rust_target_features.len().saturating_sub(5),
51                }
52            };
53            tcx.dcx().emit_err(FeatureNotValid { feature: feature_str, span: feature_span, hint });
54            continue;
55        };
56
57        // Only allow target features whose feature gates have been enabled
58        // and which are permitted to be toggled.
59        if let Err(reason) = stability.toggle_allowed() {
60            tcx.dcx().emit_err(errors::ForbiddenTargetFeatureAttr {
61                span: feature_span,
62                feature: feature_str,
63                reason,
64            });
65        } else if let Some(nightly_feature) = stability.requires_nightly(/* in_cfg */ false)
66            && !rust_features.enabled(nightly_feature)
67        {
68            let explain = if stability.is_cfg_stable_toggle_unstable() {
69                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the target feature `{0}` is allowed in cfg but unstable otherwise",
                feature))
    })format!("the target feature `{feature}` is allowed in cfg but unstable otherwise")
70            } else {
71                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("the target feature `{0}` is currently unstable",
                feature))
    })format!("the target feature `{feature}` is currently unstable")
72            };
73            feature_err(&tcx.sess, nightly_feature, feature_span, explain).emit();
74        } else {
75            // Add this and the implied features.
76            for &name in tcx.implied_target_features(feature) {
77                // But ensure the ABI does not forbid enabling this.
78                // Here we do assume that the backend doesn't add even more implied features
79                // we don't know about, at least no features that would have ABI effects!
80                // We skip this logic in rustdoc, where we want to allow all target features of
81                // all targets, so we can't check their ABI compatibility and anyway we are not
82                // generating code so "it's fine".
83                if !tcx.sess.opts.actually_rustdoc {
84                    if abi_feature_constraints.incompatible.contains(&name.as_str()) {
85                        // For "neon" specifically, we emit an FCW instead of a hard error.
86                        // See <https://github.com/rust-lang/rust/issues/134375>.
87                        if tcx.sess.target.arch == Arch::AArch64 && name.as_str() == "neon" {
88                            tcx.emit_node_span_lint(
89                                AARCH64_SOFTFLOAT_NEON,
90                                tcx.local_def_id_to_hir_id(did),
91                                feature_span,
92                                errors::Aarch64SoftfloatNeon,
93                            );
94                        } else {
95                            tcx.dcx().emit_err(errors::ForbiddenTargetFeatureAttr {
96                                span: feature_span,
97                                feature: name.as_str(),
98                                reason: "this feature is incompatible with the target ABI",
99                            });
100                        }
101                    }
102                }
103                let kind = if name != feature {
104                    TargetFeatureKind::Implied
105                } else if was_forced {
106                    TargetFeatureKind::Forced
107                } else {
108                    TargetFeatureKind::Enabled
109                };
110                target_features.push(TargetFeature { name, kind })
111            }
112        }
113    }
114}
115
116/// Computes the set of target features used in a function for the purposes of
117/// inline assembly.
118fn asm_target_features(tcx: TyCtxt<'_>, did: DefId) -> &FxIndexSet<Symbol> {
119    let mut target_features = tcx.sess.unstable_target_features.clone();
120    if tcx.def_kind(did).has_codegen_attrs() {
121        let attrs = tcx.codegen_fn_attrs(did);
122        target_features.extend(attrs.target_features.iter().map(|feature| feature.name));
123        match attrs.instruction_set {
124            None => {}
125            Some(InstructionSetAttr::ArmA32) => {
126                // FIXME(#120456) - is `swap_remove` correct?
127                target_features.swap_remove(&sym::thumb_mode);
128            }
129            Some(InstructionSetAttr::ArmT32) => {
130                target_features.insert(sym::thumb_mode);
131            }
132        }
133    }
134
135    tcx.arena.alloc(target_features)
136}
137
138/// Checks the function annotated with `#[target_feature]` is not a safe
139/// trait method implementation, reporting an error if it is.
140pub(crate) fn check_target_feature_trait_unsafe(tcx: TyCtxt<'_>, id: LocalDefId, attr_span: Span) {
141    if let DefKind::AssocFn = tcx.def_kind(id) {
142        let parent_id = tcx.local_parent(id);
143        if let DefKind::Trait | DefKind::Impl { of_trait: true } = tcx.def_kind(parent_id) {
144            tcx.dcx().emit_err(errors::TargetFeatureSafeTrait {
145                span: attr_span,
146                def: tcx.def_span(id),
147            });
148        }
149    }
150}
151
152/// Parse the value of the target spec `features` field or `-Ctarget-feature`, also expanding
153/// implied features, and call the closure for each (expanded) Rust feature. If the list contains
154/// a syntactically invalid item (not starting with `+`/`-`), the error callback is invoked.
155fn parse_rust_feature_list<'a>(
156    sess: &'a Session,
157    features: &'a str,
158    err_callback: impl Fn(&'a str),
159    mut callback: impl FnMut(
160        /* base_feature */ &'a str,
161        /* with_implied */ FxHashSet<&'a str>,
162        /* enable */ bool,
163    ),
164) {
165    // A cache for the backwards implication map.
166    let mut inverse_implied_features: Option<FxHashMap<&str, FxHashSet<&str>>> = None;
167
168    for feature in features.split(',') {
169        if let Some(base_feature) = feature.strip_prefix('+') {
170            // Skip features that are not target features, but rustc features.
171            if RUSTC_SPECIFIC_FEATURES.contains(&base_feature) {
172                continue;
173            }
174
175            callback(base_feature, sess.target.implied_target_features(base_feature), true)
176        } else if let Some(base_feature) = feature.strip_prefix('-') {
177            // Skip features that are not target features, but rustc features.
178            if RUSTC_SPECIFIC_FEATURES.contains(&base_feature) {
179                continue;
180            }
181
182            // If `f1` implies `f2`, then `!f2` implies `!f1` -- this is standard logical
183            // contraposition. So we have to find all the reverse implications of `base_feature` and
184            // disable them, too.
185
186            let inverse_implied_features = inverse_implied_features.get_or_insert_with(|| {
187                let mut set: FxHashMap<&str, FxHashSet<&str>> = FxHashMap::default();
188                for (f, _, is) in sess.target.rust_target_features() {
189                    for i in is.iter() {
190                        set.entry(i).or_default().insert(f);
191                    }
192                }
193                set
194            });
195
196            // Inverse implied target features have their own inverse implied target features, so we
197            // traverse the map until there are no more features to add.
198            let mut features = FxHashSet::default();
199            let mut new_features = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [base_feature]))vec![base_feature];
200            while let Some(new_feature) = new_features.pop() {
201                if features.insert(new_feature) {
202                    if let Some(implied_features) = inverse_implied_features.get(&new_feature) {
203                        #[allow(rustc::potential_query_instability)]
204                        new_features.extend(implied_features)
205                    }
206                }
207            }
208
209            callback(base_feature, features, false)
210        } else if !feature.is_empty() {
211            err_callback(feature)
212        }
213    }
214}
215
216/// Utility function for a codegen backend to compute `cfg(target_feature)`, or more specifically,
217/// to populate `sess.unstable_target_features` and `sess.target_features` (these are the first and
218/// 2nd component of the return value, respectively).
219///
220/// `to_backend_features` converts a Rust feature name into a list of backend feature names; this is
221/// used for diagnostic purposes only.
222///
223/// `target_base_has_feature` should check whether the given feature (a Rust feature name!) is
224/// enabled in the "base" target machine, i.e., without applying `-Ctarget-feature`. Note that LLVM
225/// may consider features to be implied that we do not and vice-versa. We want `cfg` to be entirely
226/// consistent with Rust feature implications, and thus only consult LLVM to expand the target CPU
227/// to target features.
228///
229/// We do not have to worry about RUSTC_SPECIFIC_FEATURES here, those are handled elsewhere.
230pub fn cfg_target_feature<'a, const N: usize>(
231    sess: &Session,
232    to_backend_features: impl Fn(&'a str) -> SmallVec<[&'a str; N]>,
233    mut target_base_has_feature: impl FnMut(&str) -> bool,
234) -> (Vec<Symbol>, Vec<Symbol>) {
235    let known_features = sess.target.rust_target_features();
236
237    // Compute which of the known target features are enabled in the 'base' target machine. We only
238    // consider "supported" features; "forbidden" features are not reflected in `cfg` as of now.
239    let mut features: UnordSet<Symbol> = sess
240        .target
241        .rust_target_features()
242        .iter()
243        .filter(|(feature, _, _)| target_base_has_feature(feature))
244        .flat_map(|(base_feature, _, _)| {
245            // Expand the direct base feature into all transitively-implied features. Note that we
246            // cannot simply use the `implied` field of the tuple since that only contains
247            // directly-implied features.
248            //
249            // Iteration order is irrelevant because we're collecting into an `UnordSet`.
250            #[allow(rustc::potential_query_instability)]
251            sess.target.implied_target_features(base_feature).into_iter().map(|f| Symbol::intern(f))
252        })
253        .collect();
254
255    let mut enabled_disabled_features = FxHashMap::default();
256
257    // Add enabled and remove disabled features.
258    parse_rust_feature_list(
259        sess,
260        &sess.opts.cg.target_feature,
261        /* err_callback */
262        |feature| {
263            sess.dcx().emit_warn(errors::UnknownCTargetFeaturePrefix { feature });
264        },
265        |base_feature, new_features, enable| {
266            // Iteration order is irrelevant since this only influences an `FxHashMap`.
267            #[allow(rustc::potential_query_instability)]
268            enabled_disabled_features.extend(new_features.iter().map(|&s| (s, enable)));
269
270            // Iteration order is irrelevant since this only influences an `UnordSet`.
271            #[allow(rustc::potential_query_instability)]
272            if enable {
273                features.extend(new_features.into_iter().map(|f| Symbol::intern(f)));
274            } else {
275                // Remove `new_features` from `features`.
276                for new in new_features {
277                    features.remove(&Symbol::intern(new));
278                }
279            }
280
281            // Check feature validity.
282            let feature_state = known_features.iter().find(|&&(v, _, _)| v == base_feature);
283            match feature_state {
284                None => {
285                    // This is definitely not a valid Rust feature name. Maybe it is a backend
286                    // feature name? If so, give a better error message.
287                    let rust_feature = known_features.iter().find_map(|&(rust_feature, _, _)| {
288                        let backend_features = to_backend_features(rust_feature);
289                        if backend_features.contains(&base_feature)
290                            && !backend_features.contains(&rust_feature)
291                        {
292                            Some(rust_feature)
293                        } else {
294                            None
295                        }
296                    });
297                    let unknown_feature = if let Some(rust_feature) = rust_feature {
298                        errors::UnknownCTargetFeature {
299                            feature: base_feature,
300                            rust_feature: errors::PossibleFeature::Some { rust_feature },
301                        }
302                    } else {
303                        errors::UnknownCTargetFeature {
304                            feature: base_feature,
305                            rust_feature: errors::PossibleFeature::None,
306                        }
307                    };
308                    sess.dcx().emit_warn(unknown_feature);
309                }
310                Some((_, stability, _)) => {
311                    if let Stability::Forbidden { reason, hard_error } = stability {
312                        let diag = errors::ForbiddenCTargetFeature {
313                            feature: base_feature,
314                            enabled: if enable { "enabled" } else { "disabled" },
315                            reason,
316                            future_compat_note: !hard_error,
317                        };
318
319                        if *hard_error {
320                            sess.dcx().emit_err(diag);
321                        } else {
322                            sess.dcx().emit_warn(diag);
323                        }
324                    } else if stability.requires_nightly(/* in_cfg */ false).is_some() {
325                        // An unstable feature. Warn about using it. It makes little sense
326                        // to hard-error here since we just warn about fully unknown
327                        // features above.
328                        let note = if stability.is_cfg_stable_toggle_unstable() {
329                            "this feature is allowed in cfg but unstable otherwise"
330                        } else {
331                            "this feature is not stably supported"
332                        };
333                        sess.dcx().emit_warn(errors::UnstableCTargetFeature {
334                            feature: base_feature,
335                            note,
336                        });
337                    }
338                }
339            }
340        },
341    );
342
343    if let Some(f) = check_tied_features(sess, &enabled_disabled_features) {
344        sess.dcx().emit_err(errors::TargetFeatureDisableOrEnable {
345            features: f,
346            span: None,
347            missing_features: None,
348        });
349    }
350
351    // Filter enabled features based on feature gates.
352    let f = |allow_unstable| {
353        sess.target
354            .rust_target_features()
355            .iter()
356            .filter_map(|(feature, gate, _)| {
357                // The `allow_unstable` set is used by rustc internally to determine which target
358                // features are truly available, so we want to return even perma-unstable
359                // "forbidden" features.
360                if allow_unstable
361                    || (gate.in_cfg()
362                        && (sess.is_nightly_build()
363                            || gate.requires_nightly(/* in_cfg */ true).is_none()))
364                {
365                    Some(Symbol::intern(feature))
366                } else {
367                    None
368                }
369            })
370            .filter(|feature| features.contains(&feature))
371            .collect()
372    };
373
374    (f(true), f(false))
375}
376
377/// Given a map from target_features to whether they are enabled or disabled, ensure only valid
378/// combinations are allowed.
379pub fn check_tied_features(
380    sess: &Session,
381    features: &FxHashMap<&str, bool>,
382) -> Option<&'static [&'static str]> {
383    if !features.is_empty() {
384        for tied in sess.target.tied_target_features() {
385            // Tied features must be set to the same value, or not set at all
386            let mut tied_iter = tied.iter();
387            let enabled = features.get(tied_iter.next().unwrap());
388            if tied_iter.any(|f| enabled != features.get(f)) {
389                return Some(tied);
390            }
391        }
392    }
393    None
394}
395
396/// Translates the target spec `features` field into a backend target feature list.
397///
398/// `extend_backend_features` extends the set of backend features (assumed to be in mutable state
399/// accessible by that closure) to enable/disable the given Rust feature name.
400pub fn target_spec_to_backend_features<'a>(
401    sess: &'a Session,
402    mut extend_backend_features: impl FnMut(&'a str, /* enable */ bool),
403) {
404    let mut rust_features = ::alloc::vec::Vec::new()vec![];
405
406    // This check handles SM versions that defaults (by LLVM) to unsupported (by Rust) PTX ISA versions.
407    // sm_70, sm_72 and sm_75 defaults to PTX ISA versions with major version 6, while sm_80 default to 7.0
408    if sess.target.arch == Arch::Nvptx64
409        && #[allow(non_exhaustive_omitted_patterns)] match sess.opts.cg.target_cpu.as_deref()
    {
    None | Some("sm_70") | Some("sm_72") | Some("sm_75") => true,
    _ => false,
}matches!(
410            sess.opts.cg.target_cpu.as_deref(),
411            None | Some("sm_70") | Some("sm_72") | Some("sm_75")
412        )
413    {
414        rust_features.push((true, "ptx70"));
415    }
416
417    // Compute implied features
418    parse_rust_feature_list(
419        sess,
420        &sess.target.features,
421        /* err_callback */
422        |feature| {
423            {
    ::core::panicking::panic_fmt(format_args!("Target spec contains invalid feature {0}",
            feature));
};panic!("Target spec contains invalid feature {feature}");
424        },
425        |_base_feature, new_features, enable| {
426            // FIXME emit an error for unknown features like cfg_target_feature would for -Ctarget-feature
427            rust_features.extend(
428                UnordSet::from(new_features).to_sorted_stable_ord().iter().map(|&&s| (enable, s)),
429            );
430        },
431    );
432
433    // Add this to the backend features.
434    for (enable, feature) in rust_features {
435        extend_backend_features(feature, enable);
436    }
437}
438
439/// Translates the `-Ctarget-feature` flag into a backend target feature list.
440///
441/// `extend_backend_features` extends the set of backend features (assumed to be in mutable state
442/// accessible by that closure) to enable/disable the given Rust feature name.
443pub fn flag_to_backend_features<'a>(
444    sess: &'a Session,
445    mut extend_backend_features: impl FnMut(&'a str, /* enable */ bool),
446) {
447    // Compute implied features
448    let mut rust_features = ::alloc::vec::Vec::new()vec![];
449    parse_rust_feature_list(
450        sess,
451        &sess.opts.cg.target_feature,
452        /* err_callback */
453        |_feature| {
454            // Errors are already emitted in `cfg_target_feature`; avoid duplicates.
455        },
456        |_base_feature, new_features, enable| {
457            rust_features.extend(
458                UnordSet::from(new_features).to_sorted_stable_ord().iter().map(|&&s| (enable, s)),
459            );
460        },
461    );
462
463    // Add this to the backend features.
464    for (enable, feature) in rust_features {
465        extend_backend_features(feature, enable);
466    }
467}
468
469/// Computes the backend target features to be added to account for retpoline flags.
470/// Used by both LLVM and GCC since their target features are, conveniently, the same.
471pub fn retpoline_features_by_flags(sess: &Session, features: &mut Vec<String>) {
472    // -Zretpoline without -Zretpoline-external-thunk enables
473    // retpoline-indirect-branches and retpoline-indirect-calls target features
474    let unstable_opts = &sess.opts.unstable_opts;
475    if unstable_opts.retpoline && !unstable_opts.retpoline_external_thunk {
476        features.push("+retpoline-indirect-branches".into());
477        features.push("+retpoline-indirect-calls".into());
478    }
479    // -Zretpoline-external-thunk (maybe, with -Zretpoline too) enables
480    // retpoline-external-thunk, retpoline-indirect-branches and
481    // retpoline-indirect-calls target features
482    if unstable_opts.retpoline_external_thunk {
483        features.push("+retpoline-external-thunk".into());
484        features.push("+retpoline-indirect-branches".into());
485        features.push("+retpoline-indirect-calls".into());
486    }
487}
488
489/// Computes the backend target features to be added to account for sanitizer flags.
490pub fn sanitizer_features_by_flags(sess: &Session, features: &mut Vec<String>) {
491    // It's intentional that this is done only for non-kernel version of hwaddress. This matches
492    // clang behavior.
493    if sess.sanitizers().contains(SanitizerSet::HWADDRESS) {
494        features.push("+tagged-globals".into());
495    }
496}
497
498pub(crate) fn provide(providers: &mut Providers) {
499    *providers = Providers {
500        rust_target_features: |tcx, cnum| {
501            match (&cnum, &LOCAL_CRATE) {
    (left_val, right_val) => {
        if !(*left_val == *right_val) {
            let kind = ::core::panicking::AssertKind::Eq;
            ::core::panicking::assert_failed(kind, &*left_val, &*right_val,
                ::core::option::Option::None);
        }
    }
};assert_eq!(cnum, LOCAL_CRATE);
502            if tcx.sess.opts.actually_rustdoc {
503                // HACK: rustdoc would like to pretend that we have all the target features, so we
504                // have to merge all the lists into one. To ensure an unstable target never prevents
505                // a stable one from working, we merge the stability info of all instances of the
506                // same target feature name, with the "most stable" taking precedence. And then we
507                // hope that this doesn't cause issues anywhere else in the compiler...
508                let mut result: UnordMap<String, Stability> = Default::default();
509                for (name, stability) in rustc_target::target_features::all_rust_features() {
510                    use std::collections::hash_map::Entry;
511                    match result.entry(name.to_owned()) {
512                        Entry::Vacant(vacant_entry) => {
513                            vacant_entry.insert(stability);
514                        }
515                        Entry::Occupied(mut occupied_entry) => {
516                            // Merge the two stabilities, "more stable" taking precedence.
517                            match (occupied_entry.get(), stability) {
518                                (Stability::Stable, _)
519                                | (
520                                    Stability::Unstable { .. },
521                                    Stability::Unstable { .. } | Stability::Forbidden { .. },
522                                )
523                                | (Stability::Forbidden { .. }, Stability::Forbidden { .. }) => {
524                                    // The stability in the entry is at least as good as the new
525                                    // one, just keep it.
526                                }
527                                _ => {
528                                    // Overwrite stability.
529                                    occupied_entry.insert(stability);
530                                }
531                            }
532                        }
533                    }
534                }
535                result
536            } else {
537                tcx.sess
538                    .target
539                    .rust_target_features()
540                    .iter()
541                    .map(|(a, b, _)| (a.to_string(), *b))
542                    .collect()
543            }
544        },
545        implied_target_features: |tcx, feature: Symbol| {
546            let feature = feature.as_str();
547            UnordSet::from(tcx.sess.target.implied_target_features(feature))
548                .into_sorted_stable_ord()
549                .into_iter()
550                .map(|s| Symbol::intern(s))
551                .collect()
552        },
553        asm_target_features,
554        ..*providers
555    }
556}