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