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 Err(reason) = stability.toggle_allowed() {
312                        sess.dcx().emit_warn(errors::ForbiddenCTargetFeature {
313                            feature: base_feature,
314                            enabled: if enable { "enabled" } else { "disabled" },
315                            reason,
316                        });
317                    } else if stability.requires_nightly(/* in_cfg */ false).is_some() {
318                        // An unstable feature. Warn about using it. It makes little sense
319                        // to hard-error here since we just warn about fully unknown
320                        // features above.
321                        let note = if stability.is_cfg_stable_toggle_unstable() {
322                            "this feature is allowed in cfg but unstable otherwise"
323                        } else {
324                            "this feature is not stably supported"
325                        };
326                        sess.dcx().emit_warn(errors::UnstableCTargetFeature {
327                            feature: base_feature,
328                            note,
329                        });
330                    }
331                }
332            }
333        },
334    );
335
336    if let Some(f) = check_tied_features(sess, &enabled_disabled_features) {
337        sess.dcx().emit_err(errors::TargetFeatureDisableOrEnable {
338            features: f,
339            span: None,
340            missing_features: None,
341        });
342    }
343
344    // Filter enabled features based on feature gates.
345    let f = |allow_unstable| {
346        sess.target
347            .rust_target_features()
348            .iter()
349            .filter_map(|(feature, gate, _)| {
350                // The `allow_unstable` set is used by rustc internally to determine which target
351                // features are truly available, so we want to return even perma-unstable
352                // "forbidden" features.
353                if allow_unstable
354                    || (gate.in_cfg()
355                        && (sess.is_nightly_build()
356                            || gate.requires_nightly(/* in_cfg */ true).is_none()))
357                {
358                    Some(Symbol::intern(feature))
359                } else {
360                    None
361                }
362            })
363            .filter(|feature| features.contains(&feature))
364            .collect()
365    };
366
367    (f(true), f(false))
368}
369
370/// Given a map from target_features to whether they are enabled or disabled, ensure only valid
371/// combinations are allowed.
372pub fn check_tied_features(
373    sess: &Session,
374    features: &FxHashMap<&str, bool>,
375) -> Option<&'static [&'static str]> {
376    if !features.is_empty() {
377        for tied in sess.target.tied_target_features() {
378            // Tied features must be set to the same value, or not set at all
379            let mut tied_iter = tied.iter();
380            let enabled = features.get(tied_iter.next().unwrap());
381            if tied_iter.any(|f| enabled != features.get(f)) {
382                return Some(tied);
383            }
384        }
385    }
386    None
387}
388
389/// Translates the target spec `features` field into a backend target feature list.
390///
391/// `extend_backend_features` extends the set of backend features (assumed to be in mutable state
392/// accessible by that closure) to enable/disable the given Rust feature name.
393pub fn target_spec_to_backend_features<'a>(
394    sess: &'a Session,
395    mut extend_backend_features: impl FnMut(&'a str, /* enable */ bool),
396) {
397    let mut rust_features = ::alloc::vec::Vec::new()vec![];
398
399    // This check handles SM versions that defaults (by LLVM) to unsupported (by Rust) PTX ISA versions.
400    // sm_70, sm_72 and sm_75 defaults to PTX ISA versions with major version 6, while sm_80 default to 7.0
401    if sess.target.arch == Arch::Nvptx64
402        && #[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!(
403            sess.opts.cg.target_cpu.as_deref(),
404            None | Some("sm_70") | Some("sm_72") | Some("sm_75")
405        )
406    {
407        rust_features.push((true, "ptx70"));
408    }
409
410    // Compute implied features
411    parse_rust_feature_list(
412        sess,
413        &sess.target.features,
414        /* err_callback */
415        |feature| {
416            {
    ::core::panicking::panic_fmt(format_args!("Target spec contains invalid feature {0}",
            feature));
};panic!("Target spec contains invalid feature {feature}");
417        },
418        |_base_feature, new_features, enable| {
419            // FIXME emit an error for unknown features like cfg_target_feature would for -Ctarget-feature
420            rust_features.extend(
421                UnordSet::from(new_features).to_sorted_stable_ord().iter().map(|&&s| (enable, s)),
422            );
423        },
424    );
425
426    // Add this to the backend features.
427    for (enable, feature) in rust_features {
428        extend_backend_features(feature, enable);
429    }
430}
431
432/// Translates the `-Ctarget-feature` flag into a backend target feature list.
433///
434/// `extend_backend_features` extends the set of backend features (assumed to be in mutable state
435/// accessible by that closure) to enable/disable the given Rust feature name.
436pub fn flag_to_backend_features<'a>(
437    sess: &'a Session,
438    mut extend_backend_features: impl FnMut(&'a str, /* enable */ bool),
439) {
440    // Compute implied features
441    let mut rust_features = ::alloc::vec::Vec::new()vec![];
442    parse_rust_feature_list(
443        sess,
444        &sess.opts.cg.target_feature,
445        /* err_callback */
446        |_feature| {
447            // Errors are already emitted in `cfg_target_feature`; avoid duplicates.
448        },
449        |_base_feature, new_features, enable| {
450            rust_features.extend(
451                UnordSet::from(new_features).to_sorted_stable_ord().iter().map(|&&s| (enable, s)),
452            );
453        },
454    );
455
456    // Add this to the backend features.
457    for (enable, feature) in rust_features {
458        extend_backend_features(feature, enable);
459    }
460}
461
462/// Computes the backend target features to be added to account for retpoline flags.
463/// Used by both LLVM and GCC since their target features are, conveniently, the same.
464pub fn retpoline_features_by_flags(sess: &Session, features: &mut Vec<String>) {
465    // -Zretpoline without -Zretpoline-external-thunk enables
466    // retpoline-indirect-branches and retpoline-indirect-calls target features
467    let unstable_opts = &sess.opts.unstable_opts;
468    if unstable_opts.retpoline && !unstable_opts.retpoline_external_thunk {
469        features.push("+retpoline-indirect-branches".into());
470        features.push("+retpoline-indirect-calls".into());
471    }
472    // -Zretpoline-external-thunk (maybe, with -Zretpoline too) enables
473    // retpoline-external-thunk, retpoline-indirect-branches and
474    // retpoline-indirect-calls target features
475    if unstable_opts.retpoline_external_thunk {
476        features.push("+retpoline-external-thunk".into());
477        features.push("+retpoline-indirect-branches".into());
478        features.push("+retpoline-indirect-calls".into());
479    }
480}
481
482/// Computes the backend target features to be added to account for sanitizer flags.
483pub fn sanitizer_features_by_flags(sess: &Session, features: &mut Vec<String>) {
484    // It's intentional that this is done only for non-kernel version of hwaddress. This matches
485    // clang behavior.
486    if sess.sanitizers().contains(SanitizerSet::HWADDRESS) {
487        features.push("+tagged-globals".into());
488    }
489}
490
491pub(crate) fn provide(providers: &mut Providers) {
492    *providers = Providers {
493        rust_target_features: |tcx, cnum| {
494            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);
495            if tcx.sess.opts.actually_rustdoc {
496                // HACK: rustdoc would like to pretend that we have all the target features, so we
497                // have to merge all the lists into one. To ensure an unstable target never prevents
498                // a stable one from working, we merge the stability info of all instances of the
499                // same target feature name, with the "most stable" taking precedence. And then we
500                // hope that this doesn't cause issues anywhere else in the compiler...
501                let mut result: UnordMap<String, Stability> = Default::default();
502                for (name, stability) in rustc_target::target_features::all_rust_features() {
503                    use std::collections::hash_map::Entry;
504                    match result.entry(name.to_owned()) {
505                        Entry::Vacant(vacant_entry) => {
506                            vacant_entry.insert(stability);
507                        }
508                        Entry::Occupied(mut occupied_entry) => {
509                            // Merge the two stabilities, "more stable" taking precedence.
510                            match (occupied_entry.get(), stability) {
511                                (Stability::Stable, _)
512                                | (
513                                    Stability::Unstable { .. },
514                                    Stability::Unstable { .. } | Stability::Forbidden { .. },
515                                )
516                                | (Stability::Forbidden { .. }, Stability::Forbidden { .. }) => {
517                                    // The stability in the entry is at least as good as the new
518                                    // one, just keep it.
519                                }
520                                _ => {
521                                    // Overwrite stability.
522                                    occupied_entry.insert(stability);
523                                }
524                            }
525                        }
526                    }
527                }
528                result
529            } else {
530                tcx.sess
531                    .target
532                    .rust_target_features()
533                    .iter()
534                    .map(|(a, b, _)| (a.to_string(), *b))
535                    .collect()
536            }
537        },
538        implied_target_features: |tcx, feature: Symbol| {
539            let feature = feature.as_str();
540            UnordSet::from(tcx.sess.target.implied_target_features(feature))
541                .into_sorted_stable_ord()
542                .into_iter()
543                .map(|s| Symbol::intern(s))
544                .collect()
545        },
546        asm_target_features,
547        ..*providers
548    }
549}