Skip to content

Commit 77b7310

Browse files
committed
Add #[rustc_intrinsic_const_vector_arg] to allow vectors to be passed as constants
This allows constant vectors using a repr(simd) type to be propagated through to the backend by reusing the functionality used to do a similar thing for the simd_shuffle intrinsic. fix rust-lang#118209
1 parent 96df494 commit 77b7310

File tree

24 files changed

+460
-33
lines changed

24 files changed

+460
-33
lines changed

Cargo.lock

+1
Original file line numberDiff line numberDiff line change
@@ -3496,6 +3496,7 @@ dependencies = [
34963496
"either",
34973497
"itertools",
34983498
"polonius-engine",
3499+
"rustc_ast",
34993500
"rustc_data_structures",
35003501
"rustc_errors",
35013502
"rustc_fluent_macro",

compiler/rustc_borrowck/Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ edition = "2021"
88
either = "1.5.0"
99
itertools = "0.11"
1010
polonius-engine = "0.13.0"
11+
rustc_ast = { path = "../rustc_ast" }
1112
rustc_data_structures = { path = "../rustc_data_structures" }
1213
rustc_errors = { path = "../rustc_errors" }
1314
rustc_fluent_macro = { path = "../rustc_fluent_macro" }

compiler/rustc_borrowck/messages.ftl

+2
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,8 @@ borrowck_higher_ranked_lifetime_error =
7171
borrowck_higher_ranked_subtype_error =
7272
higher-ranked subtype error
7373
74+
borrowck_intrinsic_const_vector_arg_non_const = argument at index {$index} must be a constant
75+
7476
borrowck_lifetime_constraints_error =
7577
lifetime may not live long enough
7678

compiler/rustc_borrowck/src/session_diagnostics.rs

+8
Original file line numberDiff line numberDiff line change
@@ -459,3 +459,11 @@ pub(crate) struct SimdShuffleLastConst {
459459
#[primary_span]
460460
pub span: Span,
461461
}
462+
463+
#[derive(Diagnostic)]
464+
#[diag(borrowck_intrinsic_const_vector_arg_non_const)]
465+
pub(crate) struct IntrinsicConstVectorArgNonConst {
466+
#[primary_span]
467+
pub span: Span,
468+
pub index: u128,
469+
}

compiler/rustc_borrowck/src/type_check/mod.rs

+32-1
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,9 @@ use rustc_mir_dataflow::impls::MaybeInitializedPlaces;
4949
use rustc_mir_dataflow::move_paths::MoveData;
5050
use rustc_mir_dataflow::ResultsCursor;
5151

52-
use crate::session_diagnostics::{MoveUnsized, SimdShuffleLastConst};
52+
use crate::session_diagnostics::{
53+
IntrinsicConstVectorArgNonConst, MoveUnsized, SimdShuffleLastConst,
54+
};
5355
use crate::{
5456
borrow_set::BorrowSet,
5557
constraints::{OutlivesConstraint, OutlivesConstraintSet},
@@ -1579,6 +1581,35 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
15791581
}
15801582
_ => {}
15811583
}
1584+
} else if let Some(attr) =
1585+
self.tcx().get_attr(def_id, sym::rustc_intrinsic_const_vector_arg)
1586+
{
1587+
match attr.meta_item_list() {
1588+
Some(items) => {
1589+
items.into_iter().for_each(|item: rustc_ast::NestedMetaItem| match item {
1590+
rustc_ast::NestedMetaItem::Lit(rustc_ast::MetaItemLit {
1591+
kind: rustc_ast::LitKind::Int(index, _),
1592+
..
1593+
}) => {
1594+
if index >= args.len() as u128 {
1595+
span_mirbug!(self, term, "index out of bounds");
1596+
} else {
1597+
if !matches!(args[index as usize], Operand::Constant(_)) {
1598+
self.tcx().sess.emit_err(IntrinsicConstVectorArgNonConst {
1599+
span: term.source_info.span,
1600+
index,
1601+
});
1602+
}
1603+
}
1604+
}
1605+
_ => {
1606+
span_mirbug!(self, term, "invalid index");
1607+
}
1608+
});
1609+
}
1610+
// Error is reported by `rustc_attr!`
1611+
None => (),
1612+
}
15821613
}
15831614
}
15841615
debug!(?func_ty);

compiler/rustc_codegen_gcc/src/common.rs

+5
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,11 @@ impl<'gcc, 'tcx> ConstMethods<'tcx> for CodegenCx<'gcc, 'tcx> {
159159
self.context.new_struct_constructor(None, struct_type.as_type(), None, values)
160160
}
161161

162+
fn const_vector(&self, values: &[RValue<'gcc>]) -> RValue<'gcc> {
163+
let typ = self.type_vector(values[0].get_type(), values.len() as u64);
164+
self.context.new_rvalue_from_vector(None, typ, values)
165+
}
166+
162167
fn const_to_opt_uint(&self, _v: RValue<'gcc>) -> Option<u64> {
163168
// TODO(antoyo)
164169
None

compiler/rustc_codegen_llvm/src/common.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -98,10 +98,6 @@ impl<'ll> CodegenCx<'ll, '_> {
9898
unsafe { llvm::LLVMConstArray(ty, elts.as_ptr(), elts.len() as c_uint) }
9999
}
100100

101-
pub fn const_vector(&self, elts: &[&'ll Value]) -> &'ll Value {
102-
unsafe { llvm::LLVMConstVector(elts.as_ptr(), elts.len() as c_uint) }
103-
}
104-
105101
pub fn const_bytes(&self, bytes: &[u8]) -> &'ll Value {
106102
bytes_in_context(self.llcx, bytes)
107103
}
@@ -217,6 +213,10 @@ impl<'ll, 'tcx> ConstMethods<'tcx> for CodegenCx<'ll, 'tcx> {
217213
struct_in_context(self.llcx, elts, packed)
218214
}
219215

216+
fn const_vector(&self, elts: &[&'ll Value]) -> &'ll Value {
217+
unsafe { llvm::LLVMConstVector(elts.as_ptr(), elts.len() as c_uint) }
218+
}
219+
220220
fn const_to_opt_uint(&self, v: &'ll Value) -> Option<u64> {
221221
try_as_const_integral(v).and_then(|v| unsafe {
222222
let mut i = 0u64;

compiler/rustc_codegen_ssa/messages.ftl

+2
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ codegen_ssa_cgu_not_recorded =
1616
1717
codegen_ssa_check_installed_visual_studio = please ensure that Visual Studio 2017 or later, or Build Tools for Visual Studio were installed with the Visual C++ option.
1818
19+
codegen_ssa_const_vector_evaluation = could not evaluate constant vector at compile time
20+
1921
codegen_ssa_copy_path = could not copy {$from} to {$to}: {$error}
2022
2123
codegen_ssa_copy_path_buf = unable to copy {$source_file} to {$output_path}: {$error}

compiler/rustc_codegen_ssa/src/errors.rs

+7
Original file line numberDiff line numberDiff line change
@@ -663,6 +663,13 @@ pub struct ShuffleIndicesEvaluation {
663663
pub span: Span,
664664
}
665665

666+
#[derive(Diagnostic)]
667+
#[diag(codegen_ssa_const_vector_evaluation)]
668+
pub struct ConstVectorEvaluation {
669+
#[primary_span]
670+
pub span: Span,
671+
}
672+
666673
#[derive(Diagnostic)]
667674
#[diag(codegen_ssa_missing_memory_ordering)]
668675
pub struct MissingMemoryOrdering;

compiler/rustc_codegen_ssa/src/mir/block.rs

+52-3
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,13 @@ use super::{CachedLlbb, FunctionCx, LocalRef};
55

66
use crate::base;
77
use crate::common::{self, IntPredicate};
8+
use crate::errors;
89
use crate::meth;
910
use crate::traits::*;
1011
use crate::MemFlags;
1112

1213
use rustc_ast as ast;
13-
use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
14+
use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece, LitKind, MetaItemLit, NestedMetaItem};
1415
use rustc_hir::lang_items::LangItem;
1516
use rustc_middle::mir::{self, AssertKind, SwitchTargets, UnwindTerminateReason};
1617
use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf, ValidityRequirement};
@@ -864,7 +865,15 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
864865
// promotes any complex rvalues to constants.
865866
if i == 2 && intrinsic == sym::simd_shuffle {
866867
if let mir::Operand::Constant(constant) = arg {
867-
let (llval, ty) = self.simd_shuffle_indices(bx, constant);
868+
let (llval, ty) = self.early_evaluate_const_vector(bx, constant);
869+
let llval = llval.unwrap_or_else(|| {
870+
bx.tcx().sess.emit_err(errors::ShuffleIndicesEvaluation {
871+
span: constant.span,
872+
});
873+
// We've errored, so we don't have to produce working code.
874+
let llty = bx.backend_type(bx.layout_of(ty));
875+
bx.const_undef(llty)
876+
});
868877
return OperandRef {
869878
val: Immediate(llval),
870879
layout: bx.layout_of(ty),
@@ -908,9 +917,49 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
908917
(args, None)
909918
};
910919

920+
let const_vec_arg_indexes = (|| {
921+
if let Some(def) = def
922+
&& let Some(attr) =
923+
bx.tcx().get_attr(def.def_id(), sym::rustc_intrinsic_const_vector_arg)
924+
{
925+
attr.meta_item_list()
926+
.iter()
927+
.flatten()
928+
.map(|item: &NestedMetaItem| match item {
929+
NestedMetaItem::Lit(MetaItemLit {
930+
kind: LitKind::Int(index, _), ..
931+
}) => *index as usize,
932+
_ => span_bug!(item.span(), "attribute argument must be an integer"),
933+
})
934+
.collect()
935+
} else {
936+
Vec::<usize>::new()
937+
}
938+
})();
939+
911940
let mut copied_constant_arguments = vec![];
912941
'make_args: for (i, arg) in first_args.iter().enumerate() {
913-
let mut op = self.codegen_operand(bx, arg);
942+
let mut op = if const_vec_arg_indexes.contains(&i) {
943+
// Force the specified argument to be constant by using const-qualification to promote any complex rvalues to constant.
944+
if let mir::Operand::Constant(constant) = arg
945+
&& constant.ty().is_simd()
946+
{
947+
let (llval, ty) = self.early_evaluate_const_vector(bx, &constant);
948+
let llval = llval.unwrap_or_else(|| {
949+
bx.tcx()
950+
.sess
951+
.emit_err(errors::ConstVectorEvaluation { span: constant.span });
952+
// We've errored, so we don't have to produce working code.
953+
let llty = bx.backend_type(bx.layout_of(ty));
954+
bx.const_undef(llty)
955+
});
956+
OperandRef { val: Immediate(llval), layout: bx.layout_of(ty) }
957+
} else {
958+
span_bug!(span, "argument at {i} must be a constant vector");
959+
}
960+
} else {
961+
self.codegen_operand(bx, arg)
962+
};
914963

915964
if let (0, Some(ty::InstanceDef::Virtual(_, idx))) = (i, def) {
916965
match op.val {

compiler/rustc_codegen_ssa/src/mir/constant.rs

+17-19
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
use crate::errors;
21
use crate::mir::operand::OperandRef;
32
use crate::traits::*;
43
use rustc_middle::mir;
@@ -28,7 +27,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
2827
.expect("erroneous constant not captured by required_consts")
2928
}
3029

31-
/// This is a convenience helper for `simd_shuffle_indices`. It has the precondition
30+
/// This is a convenience helper for `early_evaluate_const_vector`. It has the precondition
3231
/// that the given `constant` is an `Const::Unevaluated` and must be convertible to
3332
/// a `ValTree`. If you want a more general version of this, talk to `wg-const-eval` on zulip.
3433
///
@@ -63,19 +62,20 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
6362
)
6463
}
6564

66-
/// process constant containing SIMD shuffle indices
67-
pub fn simd_shuffle_indices(
65+
/// process constant SIMD vector or constant containing SIMD shuffle indices
66+
pub fn early_evaluate_const_vector(
6867
&mut self,
6968
bx: &Bx,
7069
constant: &mir::ConstOperand<'tcx>,
71-
) -> (Bx::Value, Ty<'tcx>) {
70+
) -> (Option<Bx::Value>, Ty<'tcx>) {
7271
let ty = self.monomorphize(constant.ty());
73-
let val = self
74-
.eval_unevaluated_mir_constant_to_valtree(constant)
75-
.ok()
76-
.flatten()
77-
.map(|val| {
78-
let field_ty = ty.builtin_index().unwrap();
72+
let field_ty = if ty.is_simd() {
73+
ty.simd_size_and_type(bx.tcx()).1
74+
} else {
75+
ty.builtin_index().unwrap()
76+
};
77+
let val =
78+
self.eval_unevaluated_mir_constant_to_valtree(constant).ok().flatten().map(|val| {
7979
let values: Vec<_> = val
8080
.unwrap_branch()
8181
.iter()
@@ -87,17 +87,15 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
8787
};
8888
bx.scalar_to_backend(prim, scalar, bx.immediate_backend_type(layout))
8989
} else {
90-
bug!("simd shuffle field {:?}", field)
90+
bug!("field is not a scalar {:?}", field)
9191
}
9292
})
9393
.collect();
94-
bx.const_struct(&values, false)
95-
})
96-
.unwrap_or_else(|| {
97-
bx.tcx().sess.emit_err(errors::ShuffleIndicesEvaluation { span: constant.span });
98-
// We've errored, so we don't have to produce working code.
99-
let llty = bx.backend_type(bx.layout_of(ty));
100-
bx.const_undef(llty)
94+
if ty.is_simd() {
95+
bx.const_vector(&values)
96+
} else {
97+
bx.const_struct(&values, false)
98+
}
10199
});
102100
(val, ty)
103101
}

compiler/rustc_codegen_ssa/src/traits/consts.rs

+1
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ pub trait ConstMethods<'tcx>: BackendTypes {
2828

2929
fn const_str(&self, s: &str) -> (Self::Value, Self::Value);
3030
fn const_struct(&self, elts: &[Self::Value], packed: bool) -> Self::Value;
31+
fn const_vector(&self, elts: &[Self::Value]) -> Self::Value;
3132

3233
fn const_to_opt_uint(&self, v: Self::Value) -> Option<u64>;
3334
fn const_to_opt_u128(&self, v: Self::Value, sign_ext: bool) -> Option<u128>;

compiler/rustc_feature/src/builtin_attrs.rs

+3
Original file line numberDiff line numberDiff line change
@@ -652,6 +652,9 @@ pub const BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[
652652
rustc_attr!(
653653
rustc_const_panic_str, Normal, template!(Word), WarnFollowing, INTERNAL_UNSTABLE
654654
),
655+
rustc_attr!(
656+
rustc_intrinsic_const_vector_arg, Normal, template!(List: "arg1_index, arg2_index, ..."), ErrorFollowing, INTERNAL_UNSTABLE
657+
),
655658

656659
// ==========================================================================
657660
// Internal attributes, Layout related:

compiler/rustc_passes/messages.ftl

+12
Original file line numberDiff line numberDiff line change
@@ -604,6 +604,18 @@ passes_rustc_allow_const_fn_unstable =
604604
passes_rustc_dirty_clean =
605605
attribute requires -Z query-dep-graph to be enabled
606606
607+
passes_rustc_intrinsic_const_vector_arg =
608+
attribute should be applied to functions in `extern "unadjusted"` modules
609+
.label = not a function in an `extern "unadjusted"` module
610+
611+
passes_rustc_intrinsic_const_vector_arg_invalid = attribute requires a parameter index
612+
613+
passes_rustc_intrinsic_const_vector_arg_non_vector = parameter at index {$index} must be a simd type
614+
.label = parameter is a non-simd type
615+
616+
passes_rustc_intrinsic_const_vector_arg_out_of_bounds = function does not have a parameter at index {$index}
617+
.label = function has {$arg_count} arguments
618+
607619
passes_rustc_layout_scalar_valid_range_arg =
608620
expected exactly one integer literal argument
609621

0 commit comments

Comments
 (0)