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 Err(reason) = stability.toggle_allowed() {
312sess.dcx().emit_warn(errors::ForbiddenCTargetFeature {
313 feature: base_feature,
314 enabled: if enable { "enabled" } else { "disabled" },
315reason,
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.
321let 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};
326sess.dcx().emit_warn(errors::UnstableCTargetFeature {
327 feature: base_feature,
328note,
329 });
330 }
331 }
332 }
333 },
334 );
335336if let Some(f) = check_tied_features(sess, &enabled_disabled_features) {
337sess.dcx().emit_err(errors::TargetFeatureDisableOrEnable {
338 features: f,
339 span: None,
340 missing_features: None,
341 });
342 }
343344// Filter enabled features based on feature gates.
345let f = |allow_unstable| {
346sess.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.
353if allow_unstable354 || (gate.in_cfg()
355 && (sess.is_nightly_build()
356 || gate.requires_nightly(/* in_cfg */ true).is_none()))
357 {
358Some(Symbol::intern(feature))
359 } else {
360None361 }
362 })
363 .filter(|feature| features.contains(&feature))
364 .collect()
365 };
366367 (f(true), f(false))
368}
369370/// 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]> {
376if !features.is_empty() {
377for tied in sess.target.tied_target_features() {
378// Tied features must be set to the same value, or not set at all
379let mut tied_iter = tied.iter();
380let enabled = features.get(tied_iter.next().unwrap());
381if tied_iter.any(|f| enabled != features.get(f)) {
382return Some(tied);
383 }
384 }
385 }
386None387}
388389/// 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,
395mut extend_backend_features: impl FnMut(&'a str, /* enable */ bool),
396) {
397let mut rust_features = ::alloc::vec::Vec::new()vec![];
398399// 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
401if sess.target.arch == Arch::Nvptx64402 && #[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(),
404None | Some("sm_70") | Some("sm_72") | Some("sm_75")
405 )406 {
407rust_features.push((true, "ptx70"));
408 }
409410// Compute implied features
411parse_rust_feature_list(
412sess,
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
420rust_features.extend(
421UnordSet::from(new_features).to_sorted_stable_ord().iter().map(|&&s| (enable, s)),
422 );
423 },
424 );
425426// Add this to the backend features.
427for (enable, feature) in rust_features {
428 extend_backend_features(feature, enable);
429 }
430}
431432/// 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,
438mut extend_backend_features: impl FnMut(&'a str, /* enable */ bool),
439) {
440// Compute implied features
441let mut rust_features = ::alloc::vec::Vec::new()vec![];
442parse_rust_feature_list(
443sess,
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| {
450rust_features.extend(
451UnordSet::from(new_features).to_sorted_stable_ord().iter().map(|&&s| (enable, s)),
452 );
453 },
454 );
455456// Add this to the backend features.
457for (enable, feature) in rust_features {
458 extend_backend_features(feature, enable);
459 }
460}
461462/// 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
467let unstable_opts = &sess.opts.unstable_opts;
468if unstable_opts.retpoline && !unstable_opts.retpoline_external_thunk {
469features.push("+retpoline-indirect-branches".into());
470features.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
475if unstable_opts.retpoline_external_thunk {
476features.push("+retpoline-external-thunk".into());
477features.push("+retpoline-indirect-branches".into());
478features.push("+retpoline-indirect-calls".into());
479 }
480}
481482/// 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.
486if sess.sanitizers().contains(SanitizerSet::HWADDRESS) {
487features.push("+tagged-globals".into());
488 }
489}
490491pub(crate) fn provide(providers: &mut Providers) {
492*providers = Providers {
493 rust_target_features: |tcx, cnum| {
494match (&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);
495if 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...
501let mut result: UnordMap<String, Stability> = Default::default();
502for (name, stability) in rustc_target::target_features::all_rust_features() {
503use std::collections::hash_map::Entry;
504match 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.
510match (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.
522occupied_entry.insert(stability);
523 }
524 }
525 }
526 }
527 }
528result529 } else {
530tcx.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| {
539let feature = feature.as_str();
540UnordSet::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 },
546asm_target_features,
547 ..*providers548 }
549}