Skip to content

Commit be8a05b

Browse files
GeorgeWortJamesbarford
authored andcommitted
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 5572759 commit be8a05b

File tree

24 files changed

+462
-30
lines changed

24 files changed

+462
-30
lines changed

Cargo.lock

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3689,6 +3689,7 @@ dependencies = [
36893689
"either",
36903690
"itertools",
36913691
"polonius-engine",
3692+
"rustc_ast",
36923693
"rustc_data_structures",
36933694
"rustc_errors",
36943695
"rustc_fluent_macro",

compiler/rustc_borrowck/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ edition = "2021"
88
either = "1.5.0"
99
itertools = "0.12"
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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,8 @@ borrowck_higher_ranked_lifetime_error =
7474
borrowck_higher_ranked_subtype_error =
7575
higher-ranked subtype error
7676
77+
borrowck_intrinsic_const_vector_arg_non_const = argument at index {$index} must be a constant
78+
7779
borrowck_lifetime_constraints_error =
7880
lifetime may not live long enough
7981

compiler/rustc_borrowck/src/session_diagnostics.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -479,3 +479,11 @@ pub(crate) struct SimdIntrinsicArgConst {
479479
pub arg: usize,
480480
pub intrinsic: String,
481481
}
482+
483+
#[derive(Diagnostic)]
484+
#[diag(borrowck_intrinsic_const_vector_arg_non_const)]
485+
pub(crate) struct IntrinsicConstVectorArgNonConst {
486+
#[primary_span]
487+
pub span: Span,
488+
pub index: u128,
489+
}

compiler/rustc_borrowck/src/type_check/mod.rs

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,9 @@ use rustc_mir_dataflow::move_paths::MoveData;
5151
use rustc_mir_dataflow::ResultsCursor;
5252

5353
use crate::renumber::RegionCtxt;
54-
use crate::session_diagnostics::{MoveUnsized, SimdIntrinsicArgConst};
54+
use crate::session_diagnostics::{
55+
IntrinsicConstVectorArgNonConst, MoveUnsized, SimdShuffleLastConst,
56+
};
5557
use crate::{
5658
borrow_set::BorrowSet,
5759
constraints::{OutlivesConstraint, OutlivesConstraintSet},
@@ -1630,6 +1632,35 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
16301632
intrinsic: name.to_string(),
16311633
});
16321634
}
1635+
} else if let Some(attr) =
1636+
self.tcx().get_attr(def_id, sym::rustc_intrinsic_const_vector_arg)
1637+
{
1638+
match attr.meta_item_list() {
1639+
Some(items) => {
1640+
items.into_iter().for_each(|item: rustc_ast::NestedMetaItem| match item {
1641+
rustc_ast::NestedMetaItem::Lit(rustc_ast::MetaItemLit {
1642+
kind: rustc_ast::LitKind::Int(index, _),
1643+
..
1644+
}) => {
1645+
if index >= args.len() as u128 {
1646+
span_mirbug!(self, term, "index out of bounds");
1647+
} else {
1648+
if !matches!(args[index as usize], Operand::Constant(_)) {
1649+
self.tcx().sess.emit_err(IntrinsicConstVectorArgNonConst {
1650+
span: term.source_info.span,
1651+
index,
1652+
});
1653+
}
1654+
}
1655+
}
1656+
_ => {
1657+
span_mirbug!(self, term, "invalid index");
1658+
}
1659+
});
1660+
}
1661+
// Error is reported by `rustc_attr!`
1662+
None => (),
1663+
}
16331664
}
16341665
}
16351666
debug!(?func_ty);

compiler/rustc_codegen_gcc/src/common.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,11 @@ impl<'gcc, 'tcx> ConstMethods<'tcx> for CodegenCx<'gcc, 'tcx> {
165165
self.context.new_struct_constructor(None, struct_type.as_type(), None, values)
166166
}
167167

168+
fn const_vector(&self, values: &[RValue<'gcc>]) -> RValue<'gcc> {
169+
let typ = self.type_vector(values[0].get_type(), values.len() as u64);
170+
self.context.new_rvalue_from_vector(None, typ, values)
171+
}
172+
168173
fn const_to_opt_uint(&self, _v: RValue<'gcc>) -> Option<u64> {
169174
// TODO(antoyo)
170175
None

compiler/rustc_codegen_llvm/src/common.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,10 @@ impl<'ll, 'tcx> ConstMethods<'tcx> for CodegenCx<'ll, 'tcx> {
224224
struct_in_context(self.llcx, elts, packed)
225225
}
226226

227+
fn const_vector(&self, elts: &[&'ll Value]) -> &'ll Value {
228+
unsafe { llvm::LLVMConstVector(elts.as_ptr(), elts.len() as c_uint) }
229+
}
230+
227231
fn const_to_opt_uint(&self, v: &'ll Value) -> Option<u64> {
228232
try_as_const_integral(v).and_then(|v| unsafe {
229233
let mut i = 0u64;

compiler/rustc_codegen_ssa/messages.ftl

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ codegen_ssa_check_installed_visual_studio = please ensure that Visual Studio 201
1919
codegen_ssa_compiler_builtins_cannot_call =
2020
`compiler_builtins` cannot call functions through upstream monomorphizations; encountered invalid call from `{$caller}` to `{$callee}`
2121
22+
codegen_ssa_const_vector_evaluation = could not evaluate constant vector at compile time
23+
2224
codegen_ssa_copy_path = could not copy {$from} to {$to}: {$error}
2325
2426
codegen_ssa_copy_path_buf = unable to copy {$source_file} to {$output_path}: {$error}

compiler/rustc_codegen_ssa/src/errors.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -598,6 +598,13 @@ pub struct ShuffleIndicesEvaluation {
598598
pub span: Span,
599599
}
600600

601+
#[derive(Diagnostic)]
602+
#[diag(codegen_ssa_const_vector_evaluation)]
603+
pub struct ConstVectorEvaluation {
604+
#[primary_span]
605+
pub span: Span,
606+
}
607+
601608
#[derive(Diagnostic)]
602609
#[diag(codegen_ssa_missing_memory_ordering)]
603610
pub struct MissingMemoryOrdering;

compiler/rustc_codegen_ssa/src/mir/block.rs

Lines changed: 52 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,13 @@ use super::{CachedLlbb, FunctionCx, LocalRef};
55

66
use crate::base;
77
use crate::common::{self, IntPredicate};
8-
use crate::errors::CompilerBuiltinsCannotCall;
8+
use crate::errors;
99
use crate::meth;
1010
use crate::traits::*;
1111
use crate::MemFlags;
1212

1313
use rustc_ast as ast;
14-
use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
14+
use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece, LitKind, MetaItemLit, NestedMetaItem};
1515
use rustc_hir::lang_items::LangItem;
1616
use rustc_middle::mir::{self, AssertKind, BasicBlock, SwitchTargets, UnwindTerminateReason};
1717
use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf, ValidityRequirement};
@@ -926,7 +926,15 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
926926
// checked by the type-checker.
927927
if i == 2 && intrinsic.name == sym::simd_shuffle {
928928
if let mir::Operand::Constant(constant) = &arg.node {
929-
let (llval, ty) = self.simd_shuffle_indices(bx, constant);
929+
let (llval, ty) = self.early_evaluate_const_vector(bx, constant);
930+
let llval = llval.unwrap_or_else(|| {
931+
bx.tcx().sess.emit_err(errors::ShuffleIndicesEvaluation {
932+
span: constant.span,
933+
});
934+
// We've errored, so we don't have to produce working code.
935+
let llty = bx.backend_type(bx.layout_of(ty));
936+
bx.const_undef(llty)
937+
});
930938
return OperandRef {
931939
val: Immediate(llval),
932940
layout: bx.layout_of(ty),
@@ -1004,9 +1012,49 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
10041012
(args, None)
10051013
};
10061014

1015+
let const_vec_arg_indexes = (|| {
1016+
if let Some(def) = def
1017+
&& let Some(attr) =
1018+
bx.tcx().get_attr(def.def_id(), sym::rustc_intrinsic_const_vector_arg)
1019+
{
1020+
attr.meta_item_list()
1021+
.iter()
1022+
.flatten()
1023+
.map(|item: &NestedMetaItem| match item {
1024+
NestedMetaItem::Lit(MetaItemLit {
1025+
kind: LitKind::Int(index, _), ..
1026+
}) => *index as usize,
1027+
_ => span_bug!(item.span(), "attribute argument must be an integer"),
1028+
})
1029+
.collect()
1030+
} else {
1031+
Vec::<usize>::new()
1032+
}
1033+
})();
1034+
10071035
let mut copied_constant_arguments = vec![];
10081036
'make_args: for (i, arg) in first_args.iter().enumerate() {
1009-
let mut op = self.codegen_operand(bx, &arg.node);
1037+
let mut op = if const_vec_arg_indexes.contains(&i) {
1038+
// Force the specified argument to be constant by using const-qualification to promote any complex rvalues to constant.
1039+
if let mir::Operand::Constant(constant) = &arg.node
1040+
&& constant.ty().is_simd()
1041+
{
1042+
let (llval, ty) = self.early_evaluate_const_vector(bx, &constant);
1043+
let llval = llval.unwrap_or_else(|| {
1044+
bx.tcx()
1045+
.sess
1046+
.emit_err(errors::ConstVectorEvaluation { span: constant.span });
1047+
// We've errored, so we don't have to produce working code.
1048+
let llty = bx.backend_type(bx.layout_of(ty));
1049+
bx.const_undef(llty)
1050+
});
1051+
OperandRef { val: Immediate(llval), layout: bx.layout_of(ty) }
1052+
} else {
1053+
span_bug!(span, "argument at {i} must be a constant vector");
1054+
}
1055+
} else {
1056+
self.codegen_operand(bx, &arg.node)
1057+
};
10101058

10111059
if let (0, Some(ty::InstanceKind::Virtual(_, idx))) = (i, def) {
10121060
match op.val {

0 commit comments

Comments
 (0)