Skip to content

Commit 7e763db

Browse files
committed
Implement struct_target_features for non-generic functions.
1 parent 38e3a57 commit 7e763db

File tree

27 files changed

+627
-31
lines changed

27 files changed

+627
-31
lines changed

compiler/rustc_codegen_ssa/src/codegen_attrs.rs

+78-11
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,11 @@ use rustc_hir::def_id::{DefId, LocalDefId, LOCAL_CRATE};
88
use rustc_hir::weak_lang_items::WEAK_LANG_ITEMS;
99
use rustc_hir::{lang_items, LangItem};
1010
use rustc_middle::middle::codegen_fn_attrs::{
11-
CodegenFnAttrFlags, CodegenFnAttrs, PatchableFunctionEntry,
11+
CodegenFnAttrFlags, CodegenFnAttrs, PatchableFunctionEntry, TargetFeature,
1212
};
1313
use rustc_middle::mir::mono::Linkage;
1414
use rustc_middle::query::Providers;
15-
use rustc_middle::ty::{self as ty, TyCtxt};
15+
use rustc_middle::ty::{self as ty, Ty, TyCtxt};
1616
use rustc_session::lint;
1717
use rustc_session::parse::feature_err;
1818
use rustc_span::symbol::Ident;
@@ -78,23 +78,26 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
7878
let mut link_ordinal_span = None;
7979
let mut no_sanitize_span = None;
8080

81+
let fn_sig_outer = || {
82+
use DefKind::*;
83+
84+
let def_kind = tcx.def_kind(did);
85+
if let Fn | AssocFn | Variant | Ctor(..) = def_kind { Some(tcx.fn_sig(did)) } else { None }
86+
};
87+
8188
for attr in attrs.iter() {
8289
// In some cases, attribute are only valid on functions, but it's the `check_attr`
8390
// pass that check that they aren't used anywhere else, rather this module.
8491
// In these cases, we bail from performing further checks that are only meaningful for
8592
// functions (such as calling `fn_sig`, which ICEs if given a non-function). We also
8693
// report a delayed bug, just in case `check_attr` isn't doing its job.
8794
let fn_sig = || {
88-
use DefKind::*;
89-
90-
let def_kind = tcx.def_kind(did);
91-
if let Fn | AssocFn | Variant | Ctor(..) = def_kind {
92-
Some(tcx.fn_sig(did))
93-
} else {
95+
let sig = fn_sig_outer();
96+
if sig.is_none() {
9497
tcx.dcx()
9598
.span_delayed_bug(attr.span, "this attribute can only be applied to functions");
96-
None
9799
}
100+
sig
98101
};
99102

100103
let Some(Ident { name, .. }) = attr.ident() else {
@@ -613,7 +616,30 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
613616
}
614617
}
615618

616-
// If a function uses #[target_feature] it can't be inlined into general
619+
if let Some(sig) = fn_sig_outer() {
620+
for ty in sig.skip_binder().inputs().skip_binder() {
621+
let additional_tf =
622+
tcx.struct_reachable_target_features(tcx.param_env(did.to_def_id()).and(*ty));
623+
// FIXME(struct_target_features): is this really necessary?
624+
if !additional_tf.is_empty() && sig.skip_binder().abi() != abi::Abi::Rust {
625+
tcx.dcx().span_err(
626+
tcx.hir().span(tcx.local_def_id_to_hir_id(did)),
627+
"cannot use a struct with target features in a function with non-Rust ABI",
628+
);
629+
}
630+
if !additional_tf.is_empty() && codegen_fn_attrs.inline == InlineAttr::Always {
631+
tcx.dcx().span_err(
632+
tcx.hir().span(tcx.local_def_id_to_hir_id(did)),
633+
"cannot use a struct with target features in a #[inline(always)] function",
634+
);
635+
}
636+
codegen_fn_attrs
637+
.target_features
638+
.extend(additional_tf.iter().map(|tf| TargetFeature { implied: true, ..*tf }));
639+
}
640+
}
641+
642+
// If a function uses non-default target_features it can't be inlined into general
617643
// purpose functions as they wouldn't have the right target features
618644
// enabled. For that reason we also forbid #[inline(always)] as it can't be
619645
// respected.
@@ -758,6 +784,47 @@ fn check_link_name_xor_ordinal(
758784
}
759785
}
760786

787+
fn struct_target_features(tcx: TyCtxt<'_>, def_id: LocalDefId) -> &[TargetFeature] {
788+
let mut features = vec![];
789+
let supported_features = tcx.supported_target_features(LOCAL_CRATE);
790+
for attr in tcx.get_attrs(def_id, sym::target_feature) {
791+
from_target_feature(tcx, attr, supported_features, &mut features);
792+
}
793+
tcx.arena.alloc_slice(&features)
794+
}
795+
796+
fn struct_reachable_target_features<'tcx>(
797+
tcx: TyCtxt<'tcx>,
798+
env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>,
799+
) -> &'tcx [TargetFeature] {
800+
// Collect target features from types reachable from `env.value` by dereferencing a certain
801+
// number of references and resolving aliases.
802+
803+
let mut ty = env.value;
804+
if matches!(ty.kind(), ty::Alias(..)) {
805+
ty = match tcx.try_normalize_erasing_regions(env.param_env, ty) {
806+
Ok(ty) => ty,
807+
Err(_) => return tcx.arena.alloc_slice(&[]),
808+
};
809+
}
810+
while let ty::Ref(_, inner, _) = ty.kind() {
811+
ty = *inner;
812+
}
813+
814+
let tf = if let ty::Adt(adt_def, ..) = ty.kind() {
815+
tcx.struct_target_features(adt_def.did())
816+
} else {
817+
&[]
818+
};
819+
tcx.arena.alloc_slice(tf)
820+
}
821+
761822
pub fn provide(providers: &mut Providers) {
762-
*providers = Providers { codegen_fn_attrs, should_inherit_track_caller, ..*providers };
823+
*providers = Providers {
824+
codegen_fn_attrs,
825+
should_inherit_track_caller,
826+
struct_target_features,
827+
struct_reachable_target_features,
828+
..*providers
829+
};
763830
}

compiler/rustc_feature/src/unstable.rs

+2
Original file line numberDiff line numberDiff line change
@@ -599,6 +599,8 @@ declare_features! (
599599
(unstable, strict_provenance, "1.61.0", Some(95228)),
600600
/// Allows string patterns to dereference values to match them.
601601
(unstable, string_deref_patterns, "1.67.0", Some(87121)),
602+
/// Allows structs to carry target_feature information.
603+
(incomplete, struct_target_features, "CURRENT_RUSTC_VERSION", Some(129107)),
602604
/// Allows the use of `#[target_feature]` on safe functions.
603605
(unstable, target_feature_11, "1.45.0", Some(69098)),
604606
/// Allows using `#[thread_local]` on `static` items.

compiler/rustc_hir/src/def.rs

+37
Original file line numberDiff line numberDiff line change
@@ -326,6 +326,43 @@ impl DefKind {
326326
| DefKind::ExternCrate => false,
327327
}
328328
}
329+
330+
/// Whether `query struct_target_features` should be used with this definition.
331+
pub fn has_struct_target_features(self) -> bool {
332+
match self {
333+
DefKind::Struct => true,
334+
DefKind::Fn
335+
| DefKind::Union
336+
| DefKind::Enum
337+
| DefKind::AssocFn
338+
| DefKind::Ctor(..)
339+
| DefKind::Closure
340+
| DefKind::Static { .. }
341+
| DefKind::Mod
342+
| DefKind::Variant
343+
| DefKind::Trait
344+
| DefKind::TyAlias
345+
| DefKind::ForeignTy
346+
| DefKind::TraitAlias
347+
| DefKind::AssocTy
348+
| DefKind::Const
349+
| DefKind::AssocConst
350+
| DefKind::Macro(..)
351+
| DefKind::Use
352+
| DefKind::ForeignMod
353+
| DefKind::OpaqueTy
354+
| DefKind::Impl { .. }
355+
| DefKind::Field
356+
| DefKind::TyParam
357+
| DefKind::ConstParam
358+
| DefKind::LifetimeParam
359+
| DefKind::AnonConst
360+
| DefKind::InlineConst
361+
| DefKind::SyntheticCoroutineBody
362+
| DefKind::GlobalAsm
363+
| DefKind::ExternCrate => false,
364+
}
365+
}
329366
}
330367

331368
/// The resolution of a path or export.

compiler/rustc_hir_typeck/src/coercion.rs

+2
Original file line numberDiff line numberDiff line change
@@ -851,6 +851,8 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> {
851851
}
852852

853853
// Safe `#[target_feature]` functions are not assignable to safe fn pointers (RFC 2396).
854+
// FIXME(struct_target_features): should this be true also for functions that inherit
855+
// target features from structs?
854856

855857
if b_hdr.safety == hir::Safety::Safe
856858
&& !self.tcx.codegen_fn_attrs(def_id).target_features.is_empty()

compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs

+1
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,7 @@ provide! { tcx, def_id, other, cdata,
254254
variances_of => { table }
255255
fn_sig => { table }
256256
codegen_fn_attrs => { table }
257+
struct_target_features => { table_defaulted_array }
257258
impl_trait_header => { table }
258259
const_param_default => { table }
259260
object_lifetime_default => { table }

compiler/rustc_metadata/src/rmeta/encoder.rs

+3
Original file line numberDiff line numberDiff line change
@@ -1398,6 +1398,9 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
13981398
if def_kind.has_codegen_attrs() {
13991399
record!(self.tables.codegen_fn_attrs[def_id] <- self.tcx.codegen_fn_attrs(def_id));
14001400
}
1401+
if def_kind.has_struct_target_features() {
1402+
record_defaulted_array!(self.tables.struct_target_features[def_id] <- self.tcx.struct_target_features(def_id));
1403+
}
14011404
if should_encode_visibility(def_kind) {
14021405
let vis =
14031406
self.tcx.local_visibility(local_id).map_id(|def_id| def_id.local_def_index);

compiler/rustc_metadata/src/rmeta/mod.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ use rustc_macros::{
1919
Decodable, Encodable, MetadataDecodable, MetadataEncodable, TyDecodable, TyEncodable,
2020
};
2121
use rustc_middle::metadata::ModChild;
22-
use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
22+
use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrs, TargetFeature};
2323
use rustc_middle::middle::debugger_visualizer::DebuggerVisualizerFile;
2424
use rustc_middle::middle::exported_symbols::{ExportedSymbol, SymbolExportInfo};
2525
use rustc_middle::middle::lib_features::FeatureStability;
@@ -404,6 +404,7 @@ define_tables! {
404404
// individually instead of `DefId`s.
405405
module_children_reexports: Table<DefIndex, LazyArray<ModChild>>,
406406
cross_crate_inlinable: Table<DefIndex, bool>,
407+
struct_target_features: Table<DefIndex, LazyArray<TargetFeature>>,
407408

408409
- optional:
409410
attributes: Table<DefIndex, LazyArray<ast::Attribute>>,

compiler/rustc_middle/src/middle/codegen_fn_attrs.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,8 @@ pub struct CodegenFnAttrs {
2626
/// be set when `link_name` is set. This is for foreign items with the
2727
/// "raw-dylib" kind.
2828
pub link_ordinal: Option<u16>,
29-
/// The `#[target_feature(enable = "...")]` attribute and the enabled
30-
/// features (only enabled features are supported right now).
29+
/// All the target features that are enabled for this function. Some features might be enabled
30+
/// implicitly.
3131
pub target_features: Vec<TargetFeature>,
3232
/// The `#[linkage = "..."]` attribute on Rust-defined items and the value we found.
3333
pub linkage: Option<Linkage>,
@@ -55,8 +55,8 @@ pub struct CodegenFnAttrs {
5555
pub struct TargetFeature {
5656
/// The name of the target feature (e.g. "avx")
5757
pub name: Symbol,
58-
/// The feature is implied by another feature, rather than explicitly added by the
59-
/// `#[target_feature]` attribute
58+
/// The feature is implied by another feature or by an argument, rather than explicitly
59+
/// added by the `#[target_feature]` attribute
6060
pub implied: bool,
6161
}
6262

compiler/rustc_middle/src/query/mod.rs

+10-1
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ use {rustc_ast as ast, rustc_attr as attr, rustc_hir as hir};
4747
use crate::infer::canonical::{self, Canonical};
4848
use crate::lint::LintExpectation;
4949
use crate::metadata::ModChild;
50-
use crate::middle::codegen_fn_attrs::CodegenFnAttrs;
50+
use crate::middle::codegen_fn_attrs::{CodegenFnAttrs, TargetFeature};
5151
use crate::middle::debugger_visualizer::DebuggerVisualizerFile;
5252
use crate::middle::exported_symbols::{ExportedSymbol, SymbolExportInfo};
5353
use crate::middle::lib_features::LibFeatures;
@@ -1249,6 +1249,15 @@ rustc_queries! {
12491249
feedable
12501250
}
12511251

1252+
query struct_target_features(def_id: DefId) -> &'tcx [TargetFeature] {
1253+
separate_provide_extern
1254+
desc { |tcx| "computing target features for struct `{}`", tcx.def_path_str(def_id) }
1255+
}
1256+
1257+
query struct_reachable_target_features(env: ty::ParamEnvAnd<'tcx, Ty<'tcx>>) -> &'tcx [TargetFeature] {
1258+
desc { |tcx| "computing target features reachable from {}", env.value }
1259+
}
1260+
12521261
query asm_target_features(def_id: DefId) -> &'tcx FxIndexSet<Symbol> {
12531262
desc { |tcx| "computing target features for inline asm of `{}`", tcx.def_path_str(def_id) }
12541263
}

compiler/rustc_middle/src/ty/parameterized.rs

+1
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ trivially_parameterized_over_tcx! {
5959
std::string::String,
6060
crate::metadata::ModChild,
6161
crate::middle::codegen_fn_attrs::CodegenFnAttrs,
62+
crate::middle::codegen_fn_attrs::TargetFeature,
6263
crate::middle::debugger_visualizer::DebuggerVisualizerFile,
6364
crate::middle::exported_symbols::SymbolExportInfo,
6465
crate::middle::lib_features::FeatureStability,

compiler/rustc_mir_build/messages.ftl

+49-3
Original file line numberDiff line numberDiff line change
@@ -116,15 +116,56 @@ mir_build_extern_static_requires_unsafe_unsafe_op_in_unsafe_fn_allowed =
116116
mir_build_inform_irrefutable = `let` bindings require an "irrefutable pattern", like a `struct` or an `enum` with only one variant
117117
118118
mir_build_initializing_type_with_requires_unsafe =
119-
initializing type with `rustc_layout_scalar_valid_range` attr is unsafe and requires unsafe block
120-
.note = initializing a layout restricted type's field with a value outside the valid range is undefined behavior
121-
.label = initializing type with `rustc_layout_scalar_valid_range` attr
119+
call to function `{$function}` with `#[target_feature]` is unsafe and requires unsafe block
120+
.help = in order for the call to be safe, the context requires the following additional target {$missing_target_features_count ->
121+
[1] feature
122+
*[count] features
123+
}: {$missing_target_features}
124+
.note = the {$build_target_features} target {$build_target_features_count ->
125+
[1] feature
126+
*[count] features
127+
} being enabled in the build configuration does not remove the requirement to list {$build_target_features_count ->
128+
[1] it
129+
*[count] them
130+
} in `#[target_feature]`
131+
.label = call to function with `#[target_feature]`
122132
123133
mir_build_initializing_type_with_requires_unsafe_unsafe_op_in_unsafe_fn_allowed =
124134
initializing type with `rustc_layout_scalar_valid_range` attr is unsafe and requires unsafe function or block
125135
.note = initializing a layout restricted type's field with a value outside the valid range is undefined behavior
126136
.label = initializing type with `rustc_layout_scalar_valid_range` attr
127137
138+
mir_build_initializing_type_with_target_feature_requires_unsafe =
139+
initializing type `{$adt}` with `#[target_feature]` is unsafe and requires unsafe block
140+
.help = in order for the call to be safe, the context requires the following additional target {$missing_target_features_count ->
141+
[1] feature
142+
*[count] features
143+
}: {$missing_target_features}
144+
.note = the {$build_target_features} target {$build_target_features_count ->
145+
[1] feature
146+
*[count] features
147+
} being enabled in the build configuration does not remove the requirement to list {$build_target_features_count ->
148+
[1] it
149+
*[count] them
150+
} in `#[target_feature]`
151+
.label = call to function with `#[target_feature]`
152+
153+
mir_build_initializing_type_with_target_feature_requires_unsafe_unsafe_op_in_unsafe_fn_allowed =
154+
initializing type `{$adt}` with `#[target_feature]` is unsafe and requires unsafe function or block
155+
.help = in order for the call to be safe, the context requires the following additional target {$missing_target_features_count ->
156+
[1] feature
157+
*[count] features
158+
}: {$missing_target_features}
159+
.note = the {$build_target_features} target {$build_target_features_count ->
160+
[1] feature
161+
*[count] features
162+
} being enabled in the build configuration does not remove the requirement to list {$build_target_features_count ->
163+
[1] it
164+
*[count] them
165+
} in `#[target_feature]`
166+
.label = call to function with `#[target_feature]`
167+
168+
128169
mir_build_inline_assembly_requires_unsafe =
129170
use of inline assembly is unsafe and requires unsafe block
130171
.note = inline assembly is entirely unchecked and can cause undefined behavior
@@ -387,6 +428,11 @@ mir_build_unsafe_op_in_unsafe_fn_initializing_type_with_requires_unsafe =
387428
.note = initializing a layout restricted type's field with a value outside the valid range is undefined behavior
388429
.label = initializing type with `rustc_layout_scalar_valid_range` attr
389430
431+
mir_build_unsafe_op_in_unsafe_fn_initializing_type_with_target_feature_requires_unsafe =
432+
initializing type with `target_feature` attr is unsafe and requires unsafe block
433+
.note = this struct can only be constructed if the corresponding `target_feature`s are available
434+
.label = initializing type with `target_feature` attr
435+
390436
mir_build_unsafe_op_in_unsafe_fn_inline_assembly_requires_unsafe =
391437
use of inline assembly is unsafe and requires unsafe block
392438
.note = inline assembly is entirely unchecked and can cause undefined behavior

0 commit comments

Comments
 (0)