Skip to content

Commit e874b9f

Browse files
committed
Let rvalue_creates_operand return true for *all* Rvalue::Aggregates
Inspired by <#138759 (comment)> where I noticed that we were nearly at this point, plus the comments I was writing in 143410 that reminded me a type-dependent `true` is fine. This PR splits the `OperandRef::builder` logic out to a separate type, with the updates needed to handle SIMD as well. In doing so, that makes the existing `Aggregate` path in `codegen_rvalue_operand` capable of handing SIMD values just fine. As a result, we no longer need to do layout calculations for aggregate result types when running the analysis to determine which things can be SSA in codegen.
1 parent 5adb489 commit e874b9f

File tree

6 files changed

+251
-84
lines changed

6 files changed

+251
-84
lines changed

compiler/rustc_codegen_ssa/src/mir/analyze.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -171,8 +171,7 @@ impl<'a, 'b, 'tcx, Bx: BuilderMethods<'b, 'tcx>> Visitor<'tcx> for LocalAnalyzer
171171
if let Some(local) = place.as_local() {
172172
self.define(local, DefLocation::Assignment(location));
173173
if self.locals[local] != LocalKind::Memory {
174-
let decl_span = self.fx.mir.local_decls[local].source_info.span;
175-
if !self.fx.rvalue_creates_operand(rvalue, decl_span) {
174+
if !self.fx.rvalue_creates_operand(rvalue) {
176175
self.locals[local] = LocalKind::Memory;
177176
}
178177
}

compiler/rustc_codegen_ssa/src/mir/operand.rs

Lines changed: 108 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -565,118 +565,159 @@ impl<'a, 'tcx, V: CodegenObject> OperandRef<'tcx, V> {
565565
}
566566
}
567567
}
568+
}
568569

569-
/// Creates an incomplete operand containing the [`abi::Scalar`]s expected based
570-
/// on the `layout` passed. This is for use with [`OperandRef::insert_field`]
571-
/// later to set the necessary immediate(s), one-by-one converting all the `Right` to `Left`.
572-
///
573-
/// Returns `None` for `layout`s which cannot be built this way.
574-
pub(crate) fn builder(
575-
layout: TyAndLayout<'tcx>,
576-
) -> Option<OperandRef<'tcx, Either<V, abi::Scalar>>> {
577-
// Uninhabited types are weird, because for example `Result<!, !>`
578-
// shows up as `FieldsShape::Primitive` and we need to be able to write
579-
// a field into `(u32, !)`. We'll do that in an `alloca` instead.
580-
if layout.uninhabited {
581-
return None;
582-
}
570+
/// Each of these variants starts out as `Either::Right` when it's uninitialized,
571+
/// then setting the field changes that to `Either::Left` with the backend value.
572+
#[derive(Debug, Copy, Clone)]
573+
enum OperandValueBuilder<V> {
574+
ZeroSized,
575+
Immediate(Either<V, abi::Scalar>),
576+
Pair(Either<V, abi::Scalar>, Either<V, abi::Scalar>),
577+
/// `repr(simd)` types need special handling because they each have a non-empty
578+
/// array field (which uses [`OperandValue::Ref`]) despite the SIMD type itself
579+
/// using [`OperandValue::Immediate`] which for any other kind of type would
580+
/// mean that its one non-ZST field would also be [`OperandValue::Immediate`].
581+
Vector(Either<V, ()>),
582+
}
583583

584+
/// Allows building up an `OperandRef` by setting fields one at a time.
585+
#[derive(Debug, Copy, Clone)]
586+
pub(super) struct OperandRefBuilder<'tcx, V> {
587+
val: OperandValueBuilder<V>,
588+
layout: TyAndLayout<'tcx>,
589+
}
590+
591+
impl<'a, 'tcx, V: CodegenObject> OperandRefBuilder<'tcx, V> {
592+
/// Creates an uninitialized builder for an instance of the `layout`.
593+
///
594+
/// ICEs for [`BackendRepr::Memory`] types (other than ZSTs), which should
595+
/// be built up inside a [`PlaceRef`] instead as they need an allocated place
596+
/// into which to write the values of the fields.
597+
pub(super) fn new(layout: TyAndLayout<'tcx>) -> Self {
584598
let val = match layout.backend_repr {
585-
BackendRepr::Memory { .. } if layout.is_zst() => OperandValue::ZeroSized,
586-
BackendRepr::Scalar(s) => OperandValue::Immediate(Either::Right(s)),
587-
BackendRepr::ScalarPair(a, b) => OperandValue::Pair(Either::Right(a), Either::Right(b)),
588-
BackendRepr::Memory { .. } | BackendRepr::SimdVector { .. } => return None,
599+
BackendRepr::Memory { .. } if layout.is_zst() => OperandValueBuilder::ZeroSized,
600+
BackendRepr::Scalar(s) => OperandValueBuilder::Immediate(Either::Right(s)),
601+
BackendRepr::ScalarPair(a, b) => {
602+
OperandValueBuilder::Pair(Either::Right(a), Either::Right(b))
603+
}
604+
BackendRepr::SimdVector { .. } => OperandValueBuilder::Vector(Either::Right(())),
605+
BackendRepr::Memory { .. } => {
606+
bug!("Cannot use non-ZST Memory-ABI type in operand builder: {layout:?}");
607+
}
589608
};
590-
Some(OperandRef { val, layout })
609+
OperandRefBuilder { val, layout }
591610
}
592-
}
593611

594-
impl<'a, 'tcx, V: CodegenObject> OperandRef<'tcx, Either<V, abi::Scalar>> {
595-
pub(crate) fn insert_field<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
612+
pub(super) fn insert_field<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
596613
&mut self,
597614
bx: &mut Bx,
598-
v: VariantIdx,
599-
f: FieldIdx,
615+
variant: VariantIdx,
616+
field: FieldIdx,
600617
operand: OperandRef<'tcx, V>,
601618
) {
602-
let (expect_zst, is_zero_offset) = if let abi::FieldsShape::Primitive = self.layout.fields {
619+
if let OperandValue::ZeroSized = operand.val {
620+
// A ZST never adds any state, so just ignore it.
621+
// This special-casing is worth it because of things like
622+
// `Result<!, !>` where `Ok(never)` is legal to write,
623+
// but the type shows as FieldShape::Primitive so we can't
624+
// actually look at the layout for the field being set.
625+
return;
626+
}
627+
628+
let is_zero_offset = if let abi::FieldsShape::Primitive = self.layout.fields {
603629
// The other branch looking at field layouts ICEs for primitives,
604630
// so we need to handle them separately.
605-
// Multiple fields is possible for cases such as aggregating
606-
// a thin pointer, where the second field is the unit.
631+
// Because we handled ZSTs above (like the metadata in a thin pointer),
632+
// the only possibility is that we're setting the one-and-only field.
607633
assert!(!self.layout.is_zst());
608-
assert_eq!(v, FIRST_VARIANT);
609-
let first_field = f == FieldIdx::ZERO;
610-
(!first_field, first_field)
634+
assert_eq!(variant, FIRST_VARIANT);
635+
assert_eq!(field, FieldIdx::ZERO);
636+
true
611637
} else {
612-
let variant_layout = self.layout.for_variant(bx.cx(), v);
613-
let field_layout = variant_layout.field(bx.cx(), f.as_usize());
614-
let field_offset = variant_layout.fields.offset(f.as_usize());
615-
(field_layout.is_zst(), field_offset == Size::ZERO)
638+
let variant_layout = self.layout.for_variant(bx.cx(), variant);
639+
let field_offset = variant_layout.fields.offset(field.as_usize());
640+
field_offset == Size::ZERO
616641
};
617642

618643
let mut update = |tgt: &mut Either<V, abi::Scalar>, src, from_scalar| {
619644
let to_scalar = tgt.unwrap_right();
645+
// We transmute here (rather than just `from_immediate`) because in
646+
// `Result<usize, *const ()>` the field of the `Ok` is an integer,
647+
// but the corresponding scalar in the enum is a pointer.
620648
let imm = transmute_scalar(bx, src, from_scalar, to_scalar);
621649
*tgt = Either::Left(imm);
622650
};
623651

624652
match (operand.val, operand.layout.backend_repr) {
625-
(OperandValue::ZeroSized, _) if expect_zst => {}
653+
(OperandValue::ZeroSized, _) => unreachable!("Handled above"),
626654
(OperandValue::Immediate(v), BackendRepr::Scalar(from_scalar)) => match &mut self.val {
627-
OperandValue::Immediate(val @ Either::Right(_)) if is_zero_offset => {
655+
OperandValueBuilder::Immediate(val @ Either::Right(_)) if is_zero_offset => {
628656
update(val, v, from_scalar);
629657
}
630-
OperandValue::Pair(fst @ Either::Right(_), _) if is_zero_offset => {
658+
OperandValueBuilder::Pair(fst @ Either::Right(_), _) if is_zero_offset => {
631659
update(fst, v, from_scalar);
632660
}
633-
OperandValue::Pair(_, snd @ Either::Right(_)) if !is_zero_offset => {
661+
OperandValueBuilder::Pair(_, snd @ Either::Right(_)) if !is_zero_offset => {
634662
update(snd, v, from_scalar);
635663
}
636-
_ => bug!("Tried to insert {operand:?} into {v:?}.{f:?} of {self:?}"),
664+
_ => bug!("Tried to insert {operand:?} into {variant:?}.{field:?} of {self:?}"),
665+
},
666+
(OperandValue::Immediate(v), BackendRepr::SimdVector { .. }) => match &mut self.val {
667+
OperandValueBuilder::Vector(val @ Either::Right(())) if is_zero_offset => {
668+
*val = Either::Left(v);
669+
}
670+
_ => bug!("Tried to insert {operand:?} into {variant:?}.{field:?} of {self:?}"),
637671
},
638672
(OperandValue::Pair(a, b), BackendRepr::ScalarPair(from_sa, from_sb)) => {
639673
match &mut self.val {
640-
OperandValue::Pair(fst @ Either::Right(_), snd @ Either::Right(_)) => {
674+
OperandValueBuilder::Pair(fst @ Either::Right(_), snd @ Either::Right(_)) => {
641675
update(fst, a, from_sa);
642676
update(snd, b, from_sb);
643677
}
644-
_ => bug!("Tried to insert {operand:?} into {v:?}.{f:?} of {self:?}"),
678+
_ => bug!("Tried to insert {operand:?} into {variant:?}.{field:?} of {self:?}"),
645679
}
646680
}
647-
_ => bug!("Unsupported operand {operand:?} inserting into {v:?}.{f:?} of {self:?}"),
681+
(OperandValue::Ref(place), BackendRepr::Memory { .. }) => match &mut self.val {
682+
OperandValueBuilder::Vector(val @ Either::Right(())) => {
683+
let ibty = bx.cx().immediate_backend_type(self.layout);
684+
let simd = bx.load_from_place(ibty, place);
685+
*val = Either::Left(simd);
686+
}
687+
_ => bug!("Tried to insert {operand:?} into {variant:?}.{field:?} of {self:?}"),
688+
},
689+
_ => bug!("Operand cannot be used with `insert_field`: {operand:?}"),
648690
}
649691
}
650692

651693
/// Insert the immediate value `imm` for field `f` in the *type itself*,
652694
/// rather than into one of the variants.
653695
///
654-
/// Most things want [`OperandRef::insert_field`] instead, but this one is
696+
/// Most things want [`Self::insert_field`] instead, but this one is
655697
/// necessary for writing things like enum tags that aren't in any variant.
656698
pub(super) fn insert_imm(&mut self, f: FieldIdx, imm: V) {
657699
let field_offset = self.layout.fields.offset(f.as_usize());
658700
let is_zero_offset = field_offset == Size::ZERO;
659701
match &mut self.val {
660-
OperandValue::Immediate(val @ Either::Right(_)) if is_zero_offset => {
702+
OperandValueBuilder::Immediate(val @ Either::Right(_)) if is_zero_offset => {
661703
*val = Either::Left(imm);
662704
}
663-
OperandValue::Pair(fst @ Either::Right(_), _) if is_zero_offset => {
705+
OperandValueBuilder::Pair(fst @ Either::Right(_), _) if is_zero_offset => {
664706
*fst = Either::Left(imm);
665707
}
666-
OperandValue::Pair(_, snd @ Either::Right(_)) if !is_zero_offset => {
708+
OperandValueBuilder::Pair(_, snd @ Either::Right(_)) if !is_zero_offset => {
667709
*snd = Either::Left(imm);
668710
}
669711
_ => bug!("Tried to insert {imm:?} into field {f:?} of {self:?}"),
670712
}
671713
}
672714

673-
/// After having set all necessary fields, this converts the
674-
/// `OperandValue<Either<V, _>>` (as obtained from [`OperandRef::builder`])
675-
/// to the normal `OperandValue<V>`.
715+
/// After having set all necessary fields, this converts the builder back
716+
/// to the normal `OperandRef`.
676717
///
677718
/// ICEs if any required fields were not set.
678-
pub fn build(&self, cx: &impl CodegenMethods<'tcx, Value = V>) -> OperandRef<'tcx, V> {
679-
let OperandRef { val, layout } = *self;
719+
pub(super) fn build(&self, cx: &impl CodegenMethods<'tcx, Value = V>) -> OperandRef<'tcx, V> {
720+
let OperandRefBuilder { val, layout } = *self;
680721

681722
// For something like `Option::<u32>::None`, it's expected that the
682723
// payload scalar will not actually have been set, so this converts
@@ -692,10 +733,22 @@ impl<'a, 'tcx, V: CodegenObject> OperandRef<'tcx, Either<V, abi::Scalar>> {
692733
};
693734

694735
let val = match val {
695-
OperandValue::ZeroSized => OperandValue::ZeroSized,
696-
OperandValue::Immediate(v) => OperandValue::Immediate(unwrap(v)),
697-
OperandValue::Pair(a, b) => OperandValue::Pair(unwrap(a), unwrap(b)),
698-
OperandValue::Ref(_) => bug!(),
736+
OperandValueBuilder::ZeroSized => OperandValue::ZeroSized,
737+
OperandValueBuilder::Immediate(v) => OperandValue::Immediate(unwrap(v)),
738+
OperandValueBuilder::Pair(a, b) => OperandValue::Pair(unwrap(a), unwrap(b)),
739+
OperandValueBuilder::Vector(v) => match v {
740+
Either::Left(v) => OperandValue::Immediate(v),
741+
Either::Right(())
742+
if let BackendRepr::SimdVector { element, .. } = layout.backend_repr
743+
&& element.is_uninit_valid()
744+
=> {
745+
let bty = cx.immediate_backend_type(layout);
746+
OperandValue::Immediate(cx.const_undef(bty))
747+
}
748+
Either::Right(()) => {
749+
bug!("OperandRef::build called while fields are missing {self:?}")
750+
}
751+
},
699752
};
700753
OperandRef { val, layout }
701754
}

compiler/rustc_codegen_ssa/src/mir/rvalue.rs

Lines changed: 7 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,9 @@ use rustc_middle::ty::layout::{HasTyCtxt, HasTypingEnv, LayoutOf, TyAndLayout};
44
use rustc_middle::ty::{self, Instance, Ty, TyCtxt};
55
use rustc_middle::{bug, mir};
66
use rustc_session::config::OptLevel;
7-
use rustc_span::{DUMMY_SP, Span};
87
use tracing::{debug, instrument};
98

10-
use super::operand::{OperandRef, OperandValue};
9+
use super::operand::{OperandRef, OperandRefBuilder, OperandValue};
1110
use super::place::{PlaceRef, codegen_tag_value};
1211
use super::{FunctionCx, LocalRef};
1312
use crate::common::{IntPredicate, TypeKind};
@@ -181,7 +180,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
181180
}
182181

183182
_ => {
184-
assert!(self.rvalue_creates_operand(rvalue, DUMMY_SP));
183+
assert!(self.rvalue_creates_operand(rvalue));
185184
let temp = self.codegen_rvalue_operand(bx, rvalue);
186185
temp.val.store(bx, dest);
187186
}
@@ -354,10 +353,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
354353
bx: &mut Bx,
355354
rvalue: &mir::Rvalue<'tcx>,
356355
) -> OperandRef<'tcx, Bx::Value> {
357-
assert!(
358-
self.rvalue_creates_operand(rvalue, DUMMY_SP),
359-
"cannot codegen {rvalue:?} to operand",
360-
);
356+
assert!(self.rvalue_creates_operand(rvalue), "cannot codegen {rvalue:?} to operand",);
361357

362358
match *rvalue {
363359
mir::Rvalue::Cast(ref kind, ref source, mir_cast_ty) => {
@@ -668,9 +664,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
668664

669665
// `rvalue_creates_operand` has arranged that we only get here if
670666
// we can build the aggregate immediate from the field immediates.
671-
let Some(mut builder) = OperandRef::builder(layout) else {
672-
bug!("Cannot use type in operand builder: {layout:?}")
673-
};
667+
let mut builder = OperandRefBuilder::new(layout);
674668
for (field_idx, field) in fields.iter_enumerated() {
675669
let op = self.codegen_operand(bx, field);
676670
let fi = active_field_index.unwrap_or(field_idx);
@@ -980,7 +974,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
980974
/// will not actually take the operand path because the result type is such
981975
/// that it always gets an `alloca`, but where it's not worth re-checking the
982976
/// layout in this code when the right thing will happen anyway.
983-
pub(crate) fn rvalue_creates_operand(&self, rvalue: &mir::Rvalue<'tcx>, span: Span) -> bool {
977+
pub(crate) fn rvalue_creates_operand(&self, rvalue: &mir::Rvalue<'tcx>) -> bool {
984978
match *rvalue {
985979
mir::Rvalue::Cast(mir::CastKind::Transmute, ref operand, cast_ty) => {
986980
let operand_ty = operand.ty(self.mir, self.cx.tcx());
@@ -1025,18 +1019,13 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
10251019
mir::Rvalue::NullaryOp(..) |
10261020
mir::Rvalue::ThreadLocalRef(_) |
10271021
mir::Rvalue::Use(..) |
1022+
mir::Rvalue::Aggregate(..) | // (*)
10281023
mir::Rvalue::WrapUnsafeBinder(..) => // (*)
10291024
true,
10301025
// Arrays are always aggregates, so it's not worth checking anything here.
10311026
// (If it's really `[(); N]` or `[T; 0]` and we use the place path, fine.)
10321027
mir::Rvalue::Repeat(..) => false,
1033-
mir::Rvalue::Aggregate(..) => {
1034-
let ty = rvalue.ty(self.mir, self.cx.tcx());
1035-
let ty = self.monomorphize(ty);
1036-
let layout = self.cx.spanned_layout_of(ty, span);
1037-
OperandRef::<Bx::Value>::builder(layout).is_some()
1038-
}
1039-
}
1028+
}
10401029

10411030
// (*) this is only true if the type is suitable
10421031
}

tests/codegen/enum/enum-aggregate.rs

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -112,17 +112,14 @@ fn make_uninhabited_err_indirectly(n: Never) -> Result<u32, Never> {
112112

113113
#[no_mangle]
114114
fn make_fully_uninhabited_result(v: u32, n: Never) -> Result<(u32, Never), (Never, u32)> {
115-
// We don't try to do this in SSA form since the whole type is uninhabited.
115+
// Actually reaching this would be UB, so we don't actually build a result.
116116

117117
// CHECK-LABEL: { i32, i32 } @make_fully_uninhabited_result(i32 %v)
118-
// CHECK: %[[ALLOC_V:.+]] = alloca [4 x i8]
119-
// CHECK: %[[RET:.+]] = alloca [8 x i8]
120-
// CHECK: store i32 %v, ptr %[[ALLOC_V]]
121-
// CHECK: %[[TEMP_V:.+]] = load i32, ptr %[[ALLOC_V]]
122-
// CHECK: %[[INNER:.+]] = getelementptr inbounds i8, ptr %[[RET]]
123-
// CHECK: store i32 %[[TEMP_V]], ptr %[[INNER]]
124-
// CHECK: call void @llvm.trap()
125-
// CHECK: unreachable
118+
// CHECK-NEXT: start:
119+
// CHECK-NEXT: call void @llvm.trap()
120+
// CHECK-NEXT: call void @llvm.trap()
121+
// CHECK-NEXT: call void @llvm.trap()
122+
// CHECK-NEXT: unreachable
126123
Ok((v, n))
127124
}
128125

0 commit comments

Comments
 (0)