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;
1617use crate::errors::{FeatureNotValid, FeatureNotValidHint};
18use crate::{errors, target_features};
1920/// 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) {
30let rust_features = tcx.features();
31let abi_feature_constraints = tcx.sess.target.abi_required_features();
32for &(feature, feature_span) in features {
33let feature_str = feature.as_str();
34let Some(stability) = rust_target_features.get(feature_str) else {
35let 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.
41let 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);
4748 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 });
54continue;
55 };
5657// Only allow target features whose feature gates have been enabled
58 // and which are permitted to be toggled.
59if 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 {
68let 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.
76for &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".
83if !tcx.sess.opts.actually_rustdoc {
84if 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>.
87if 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 }
103let 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}
115116/// 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> {
119let mut target_features = tcx.sess.unstable_target_features.clone();
120if tcx.def_kind(did).has_codegen_attrs() {
121let attrs = tcx.codegen_fn_attrs(did);
122target_features.extend(attrs.target_features.iter().map(|feature| feature.name));
123match attrs.instruction_set {
124None => {}
125Some(InstructionSetAttr::ArmA32) => {
126// FIXME(#120456) - is `swap_remove` correct?
127target_features.swap_remove(&sym::thumb_mode);
128 }
129Some(InstructionSetAttr::ArmT32) => {
130target_features.insert(sym::thumb_mode);
131 }
132 }
133 }
134135tcx.arena.alloc(target_features)
136}
137138/// 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) {
141if let DefKind::AssocFn = tcx.def_kind(id) {
142let parent_id = tcx.local_parent(id);
143if let DefKind::Trait | DefKind::Impl { of_trait: true } = tcx.def_kind(parent_id) {
144tcx.dcx().emit_err(errors::TargetFeatureSafeTrait {
145 span: attr_span,
146 def: tcx.def_span(id),
147 });
148 }
149 }
150}
151152/// 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),
159mut 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.
166let mut inverse_implied_features: Option<FxHashMap<&str, FxHashSet<&str>>> = None;
167168for feature in features.split(',') {
169if let Some(base_feature) = feature.strip_prefix('+') {
170// Skip features that are not target features, but rustc features.
171if RUSTC_SPECIFIC_FEATURES.contains(&base_feature) {
172continue;
173 }
174175 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.
178if RUSTC_SPECIFIC_FEATURES.contains(&base_feature) {
179continue;
180 }
181182// 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.
185186let inverse_implied_features = inverse_implied_features.get_or_insert_with(|| {
187let mut set: FxHashMap<&str, FxHashSet<&str>> = FxHashMap::default();
188for (f, _, is) in sess.target.rust_target_features() {
189for i in is.iter() {
190 set.entry(i).or_default().insert(f);
191 }
192 }
193 set
194 });
195196// 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.
198let mut features = FxHashSet::default();
199let 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];
200while let Some(new_feature) = new_features.pop() {
201if features.insert(new_feature) {
202if let Some(implied_features) = inverse_implied_features.get(&new_feature) {
203#[allow(rustc::potential_query_instability)]
204new_features.extend(implied_features)
205 }
206 }
207 }
208209 callback(base_feature, features, false)
210 } else if !feature.is_empty() {
211 err_callback(feature)
212 }
213 }
214}
215216/// 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]>,
233mut target_base_has_feature: impl FnMut(&str) -> bool,
234) -> (Vec<Symbol>, Vec<Symbol>) {
235let known_features = sess.target.rust_target_features();
236237// 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.
239let mut features: UnordSet<Symbol> = sess240 .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)]
251sess.target.implied_target_features(base_feature).into_iter().map(|f| Symbol::intern(f))
252 })
253 .collect();
254255let mut enabled_disabled_features = FxHashMap::default();
256257// Add enabled and remove disabled features.
258parse_rust_feature_list(
259sess,
260&sess.opts.cg.target_feature,
261/* err_callback */
262|feature| {
263sess.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)]
268enabled_disabled_features.extend(new_features.iter().map(|&s| (s, enable)));
269270// Iteration order is irrelevant since this only influences an `UnordSet`.
271#[allow(rustc::potential_query_instability)]
272if enable {
273features.extend(new_features.into_iter().map(|f| Symbol::intern(f)));
274 } else {
275// Remove `new_features` from `features`.
276for new in new_features {
277 features.remove(&Symbol::intern(new));
278 }
279 }
280281// Check feature validity.
282let feature_state = known_features.iter().find(|&&(v, _, _)| v == base_feature);
283match feature_state {
284None => {
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.
287let rust_feature = known_features.iter().find_map(|&(rust_feature, _, _)| {
288let backend_features = to_backend_features(rust_feature);
289if backend_features.contains(&base_feature)
290 && !backend_features.contains(&rust_feature)
291 {
292Some(rust_feature)
293 } else {
294None295 }
296 });
297let 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 };
308sess.dcx().emit_warn(unknown_feature);
309 }
310Some((_, stability, _)) => {
311if let Stability::Forbidden { reason, hard_error } = stability {
312let diag = errors::ForbiddenCTargetFeature {
313 feature: base_feature,
314 enabled: if enable { "enabled" } else { "disabled" },
315reason,
316 future_compat_note: !hard_error,
317 };
318319if *hard_error {
320sess.dcx().emit_err(diag);
321 } else {
322sess.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.
328let 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};
333sess.dcx().emit_warn(errors::UnstableCTargetFeature {
334 feature: base_feature,
335note,
336 });
337 }
338 }
339 }
340 },
341 );
342343if let Some(f) = check_tied_features(sess, &enabled_disabled_features) {
344sess.dcx().emit_err(errors::TargetFeatureDisableOrEnable {
345 features: f,
346 span: None,
347 missing_features: None,
348 });
349 }
350351// Filter enabled features based on feature gates.
352let f = |allow_unstable| {
353sess.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.
360if allow_unstable361 || (gate.in_cfg()
362 && (sess.is_nightly_build()
363 || gate.requires_nightly(/* in_cfg */ true).is_none()))
364 {
365Some(Symbol::intern(feature))
366 } else {
367None368 }
369 })
370 .filter(|feature| features.contains(&feature))
371 .collect()
372 };
373374 (f(true), f(false))
375}
376377/// 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]> {
383if !features.is_empty() {
384for tied in sess.target.tied_target_features() {
385// Tied features must be set to the same value, or not set at all
386let mut tied_iter = tied.iter();
387let enabled = features.get(tied_iter.next().unwrap());
388if tied_iter.any(|f| enabled != features.get(f)) {
389return Some(tied);
390 }
391 }
392 }
393None394}
395396/// 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,
402mut extend_backend_features: impl FnMut(&'a str, /* enable */ bool),
403) {
404let mut rust_features = ::alloc::vec::Vec::new()vec![];
405406// 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
408if sess.target.arch == Arch::Nvptx64409 && #[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(),
411None | Some("sm_70") | Some("sm_72") | Some("sm_75")
412 )413 {
414rust_features.push((true, "ptx70"));
415 }
416417// Compute implied features
418parse_rust_feature_list(
419sess,
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
427rust_features.extend(
428UnordSet::from(new_features).to_sorted_stable_ord().iter().map(|&&s| (enable, s)),
429 );
430 },
431 );
432433// Add this to the backend features.
434for (enable, feature) in rust_features {
435 extend_backend_features(feature, enable);
436 }
437}
438439/// 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,
445mut extend_backend_features: impl FnMut(&'a str, /* enable */ bool),
446) {
447// Compute implied features
448let mut rust_features = ::alloc::vec::Vec::new()vec![];
449parse_rust_feature_list(
450sess,
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| {
457rust_features.extend(
458UnordSet::from(new_features).to_sorted_stable_ord().iter().map(|&&s| (enable, s)),
459 );
460 },
461 );
462463// Add this to the backend features.
464for (enable, feature) in rust_features {
465 extend_backend_features(feature, enable);
466 }
467}
468469/// 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
474let unstable_opts = &sess.opts.unstable_opts;
475if unstable_opts.retpoline && !unstable_opts.retpoline_external_thunk {
476features.push("+retpoline-indirect-branches".into());
477features.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
482if unstable_opts.retpoline_external_thunk {
483features.push("+retpoline-external-thunk".into());
484features.push("+retpoline-indirect-branches".into());
485features.push("+retpoline-indirect-calls".into());
486 }
487}
488489/// 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.
493if sess.sanitizers().contains(SanitizerSet::HWADDRESS) {
494features.push("+tagged-globals".into());
495 }
496}
497498pub(crate) fn provide(providers: &mut Providers) {
499*providers = Providers {
500 rust_target_features: |tcx, cnum| {
501match (&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);
502if 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...
508let mut result: UnordMap<String, Stability> = Default::default();
509for (name, stability) in rustc_target::target_features::all_rust_features() {
510use std::collections::hash_map::Entry;
511match 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.
517match (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.
529occupied_entry.insert(stability);
530 }
531 }
532 }
533 }
534 }
535result536 } else {
537tcx.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| {
546let feature = feature.as_str();
547UnordSet::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 },
553asm_target_features,
554 ..*providers555 }
556}