Refactor: VariantIdx::from_u32(0) -> FIRST_VARIANT

Since structs are always `VariantIdx(0)`, there's a bunch of files where the only reason they had `VariantIdx` or `vec::Idx` imported at all was to get the first variant.

So this uses a constant for that, and adds some doc-comments to `VariantIdx` while I'm there, since it doesn't have any today.
This commit is contained in:
Scott McMurray 2023-03-25 18:43:03 -07:00
parent 96bd50dd47
commit 0439d13176
25 changed files with 80 additions and 78 deletions

View File

@ -43,7 +43,7 @@ fn scalar_pair(&self, a: Scalar, b: Scalar) -> LayoutS {
.max_by_key(|niche| niche.available(dl));
LayoutS {
variants: Variants::Single { index: VariantIdx::new(0) },
variants: Variants::Single { index: FIRST_VARIANT },
fields: FieldsShape::Arbitrary {
offsets: vec![Size::ZERO, b_offset],
memory_index: vec![0, 1],
@ -264,7 +264,7 @@ fn univariant(
abi = Abi::Uninhabited;
}
Some(LayoutS {
variants: Variants::Single { index: VariantIdx::new(0) },
variants: Variants::Single { index: FIRST_VARIANT },
fields: FieldsShape::Arbitrary { offsets, memory_index },
abi,
largest_niche,
@ -277,7 +277,7 @@ fn layout_of_never_type(&self) -> LayoutS {
let dl = self.current_data_layout();
let dl = dl.borrow();
LayoutS {
variants: Variants::Single { index: VariantIdx::new(0) },
variants: Variants::Single { index: FIRST_VARIANT },
fields: FieldsShape::Primitive,
abi: Abi::Uninhabited,
largest_niche: None,
@ -331,7 +331,7 @@ fn layout_of_struct_or_enum(
}
// If it's a struct, still compute a layout so that we can still compute the
// field offsets.
None => VariantIdx::new(0),
None => FIRST_VARIANT,
};
let is_struct = !is_enum ||
@ -467,7 +467,7 @@ struct TmpLayout {
.max_by_key(|(_i, layout)| layout.size.bytes())
.map(|(i, _layout)| i)?;
let all_indices = (0..=variants.len() - 1).map(VariantIdx::new);
let all_indices = variants.indices();
let needs_disc =
|index: VariantIdx| index != largest_variant_index && !absent(&variants[index]);
let niche_variants = all_indices.clone().find(|v| needs_disc(*v)).unwrap().index()
@ -896,8 +896,8 @@ fn layout_of_union(
let optimize = !repr.inhibit_union_abi_opt();
let mut size = Size::ZERO;
let mut abi = Abi::Aggregate { sized: true };
let index = VariantIdx::new(0);
for field in &variants[index] {
let only_variant = &variants[FIRST_VARIANT];
for field in only_variant {
assert!(field.0.is_sized());
align = align.max(field.align());
@ -930,8 +930,8 @@ fn layout_of_union(
}
Some(LayoutS {
variants: Variants::Single { index },
fields: FieldsShape::Union(NonZeroUsize::new(variants[index].len())?),
variants: Variants::Single { index: FIRST_VARIANT },
fields: FieldsShape::Union(NonZeroUsize::new(only_variant.len())?),
abi,
largest_niche: None,
align,

View File

@ -1380,8 +1380,21 @@ pub fn reserve<C: HasDataLayout>(&self, cx: &C, count: u128) -> Option<(u128, Sc
}
rustc_index::newtype_index! {
/// The *source-order* index of a variant in a type.
///
/// For enums, these are always `0..variant_count`, regardless of any
/// custom discriminants that may have been defined, and including any
/// variants that may end up uninhabited due to field types. (Some of the
/// variants may not be present in a monomorphized ABI [`Variants`], but
/// those skipped variants are always counted when determining the *index*.)
///
/// `struct`s, `tuples`, and `unions`s are considered to have a single variant
/// with variant index zero, aka [`FIRST_VARIANT`].
#[derive(HashStable_Generic)]
pub struct VariantIdx {}
pub struct VariantIdx {
/// Equivalent to `VariantIdx(0)`.
const FIRST_VARIANT = 0;
}
}
#[derive(PartialEq, Eq, Hash, Clone)]
@ -1422,7 +1435,7 @@ pub fn scalar<C: HasDataLayout>(cx: &C, scalar: Scalar) -> Self {
let size = scalar.size(cx);
let align = scalar.align(cx);
LayoutS {
variants: Variants::Single { index: VariantIdx::new(0) },
variants: Variants::Single { index: FIRST_VARIANT },
fields: FieldsShape::Primitive,
abi: Abi::Scalar(scalar),
largest_niche,

View File

@ -14,7 +14,7 @@
use rustc_hir::def::DefKind;
use rustc_hir::def_id::LocalDefId;
use rustc_hir::lang_items::LangItem;
use rustc_index::vec::{Idx, IndexVec};
use rustc_index::vec::IndexVec;
use rustc_infer::infer::canonical::QueryRegionConstraints;
use rustc_infer::infer::outlives::env::RegionBoundPairs;
use rustc_infer::infer::region_constraints::RegionConstraintData;
@ -36,7 +36,7 @@
};
use rustc_span::def_id::CRATE_DEF_ID;
use rustc_span::{Span, DUMMY_SP};
use rustc_target::abi::VariantIdx;
use rustc_target::abi::FIRST_VARIANT;
use rustc_trait_selection::traits::query::type_op::custom::scrape_region_constraints;
use rustc_trait_selection::traits::query::type_op::custom::CustomTypeOp;
use rustc_trait_selection::traits::query::type_op::{TypeOp, TypeOpOutput};
@ -812,7 +812,7 @@ fn field_ty(
},
PlaceTy { ty, variant_index: None } => match *ty.kind() {
ty::Adt(adt_def, substs) if !adt_def.is_enum() => {
(adt_def.variant(VariantIdx::new(0)), substs)
(adt_def.variant(FIRST_VARIANT), substs)
}
ty::Closure(_, substs) => {
return match substs

View File

@ -785,7 +785,7 @@ fn is_fat_ptr<'tcx>(fx: &FunctionCx<'_, '_, 'tcx>, ty: Ty<'tcx>) -> bool {
let variant_dest = lval.downcast_variant(fx, variant_index);
(variant_index, variant_dest, active_field_index)
}
_ => (VariantIdx::from_u32(0), lval, None),
_ => (FIRST_VARIANT, lval, None),
};
if active_field_index.is_some() {
assert_eq!(operands.len(), 1);

View File

@ -86,7 +86,7 @@ mod prelude {
self, FloatTy, Instance, InstanceDef, IntTy, ParamEnv, Ty, TyCtxt, TypeAndMut,
TypeFoldable, TypeVisitableExt, UintTy,
};
pub(crate) use rustc_target::abi::{Abi, Scalar, Size, VariantIdx};
pub(crate) use rustc_target::abi::{Abi, Scalar, Size, VariantIdx, FIRST_VARIANT};
pub(crate) use rustc_data_structures::fx::FxHashMap;

View File

@ -146,7 +146,7 @@ pub(crate) fn coerce_unsized_into<'tcx>(
(&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
assert_eq!(def_a, def_b);
for i in 0..def_a.variant(VariantIdx::new(0)).fields.len() {
for i in 0..def_a.variant(FIRST_VARIANT).fields.len() {
let src_f = src.value_field(fx, mir::Field::new(i));
let dst_f = dst.place_field(fx, mir::Field::new(i));

View File

@ -24,7 +24,6 @@
use rustc_hir as hir;
use rustc_hir::def_id::{DefId, LOCAL_CRATE};
use rustc_hir::lang_items::LangItem;
use rustc_index::vec::Idx;
use rustc_metadata::EncodedMetadata;
use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
use rustc_middle::middle::exported_symbols;
@ -40,7 +39,7 @@
use rustc_span::symbol::sym;
use rustc_span::Symbol;
use rustc_span::{DebuggerVisualizerFile, DebuggerVisualizerType};
use rustc_target::abi::{Align, VariantIdx};
use rustc_target::abi::{Align, FIRST_VARIANT};
use std::collections::BTreeSet;
use std::time::{Duration, Instant};
@ -307,7 +306,7 @@ pub fn coerce_unsized_into<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
(&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
assert_eq!(def_a, def_b);
for i in 0..def_a.variant(VariantIdx::new(0)).fields.len() {
for i in 0..def_a.variant(FIRST_VARIANT).fields.len() {
let src_f = src.project_field(bx, i);
let dst_f = dst.project_field(bx, i);

View File

@ -13,7 +13,7 @@
use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf};
use rustc_middle::ty::{self, adjustment::PointerCast, Instance, Ty, TyCtxt};
use rustc_span::source_map::{Span, DUMMY_SP};
use rustc_target::abi::{self, VariantIdx};
use rustc_target::abi::{self, FIRST_VARIANT};
impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
#[instrument(level = "trace", skip(self, bx))]
@ -118,7 +118,7 @@ pub fn codegen_rvalue(
let variant_dest = dest.project_downcast(bx, variant_index);
(variant_index, variant_dest, active_field_index)
}
_ => (VariantIdx::from_u32(0), dest, None),
_ => (FIRST_VARIANT, dest, None),
};
if active_field_index.is_some() {
assert_eq!(operands.len(), 1);

View File

@ -8,7 +8,7 @@
use crate::interpret::{MPlaceTy, Value};
use rustc_middle::ty::{self, ScalarInt, Ty, TyCtxt};
use rustc_span::source_map::DUMMY_SP;
use rustc_target::abi::{Align, VariantIdx};
use rustc_target::abi::{Align, VariantIdx, FIRST_VARIANT};
#[instrument(skip(ecx), level = "debug")]
fn branches<'tcx>(
@ -412,7 +412,7 @@ fn valtree_into_mplace<'tcx>(
let inner_ty = match ty.kind() {
ty::Adt(def, substs) => {
def.variant(VariantIdx::from_u32(0)).fields[i].ty(tcx, substs)
def.variant(FIRST_VARIANT).fields[i].ty(tcx, substs)
}
ty::Tuple(inner_tys) => inner_tys[i],
_ => bug!("unexpected unsized type {:?}", ty),

View File

@ -8,7 +8,7 @@
use rustc_middle::mir;
use rustc_middle::ty;
use rustc_middle::ty::layout::{LayoutOf, TyAndLayout};
use rustc_target::abi::{self, Abi, Align, HasDataLayout, Size, VariantIdx};
use rustc_target::abi::{self, Abi, Align, HasDataLayout, Size, FIRST_VARIANT};
use super::{
alloc_range, mir_assign_valid_types, AllocId, AllocRef, AllocRefMut, CheckInAllocMsg,
@ -796,7 +796,7 @@ pub fn write_aggregate(
let variant_dest = self.place_downcast(&dest, variant_index)?;
(variant_index, variant_dest, active_field_index)
}
_ => (VariantIdx::from_u32(0), dest.clone(), None),
_ => (FIRST_VARIANT, dest.clone(), None),
};
if active_field_index.is_some() {
assert_eq!(operands.len(), 1);

View File

@ -17,7 +17,7 @@
use rustc_mir_dataflow::impls::MaybeStorageLive;
use rustc_mir_dataflow::storage::always_storage_live_locals;
use rustc_mir_dataflow::{Analysis, ResultsCursor};
use rustc_target::abi::{Size, VariantIdx};
use rustc_target::abi::{Size, FIRST_VARIANT};
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum EdgeKind {
@ -359,7 +359,7 @@ fn visit_projection_elem(
check_equal(self, location, *f_ty);
}
ty::Adt(adt_def, substs) => {
let var = parent_ty.variant_index.unwrap_or(VariantIdx::from_u32(0));
let var = parent_ty.variant_index.unwrap_or(FIRST_VARIANT);
let Some(field) = adt_def.variant(var).fields.get(f.as_usize()) else {
fail_out_of_bounds(self, location);
return;

View File

@ -14,12 +14,11 @@
use rustc_hir::def::Res;
use rustc_hir::def_id::LocalDefId;
use rustc_hir::PatKind;
use rustc_index::vec::Idx;
use rustc_infer::infer::InferCtxt;
use rustc_middle::hir::place::ProjectionKind;
use rustc_middle::mir::FakeReadCause;
use rustc_middle::ty::{self, adjustment, AdtKind, Ty, TyCtxt};
use rustc_target::abi::VariantIdx;
use rustc_target::abi::FIRST_VARIANT;
use ty::BorrowKind::ImmBorrow;
use crate::mem_categorization as mc;
@ -549,7 +548,7 @@ fn walk_struct_expr<'hir>(
&*with_expr,
with_place.clone(),
with_field.ty(self.tcx(), substs),
ProjectionKind::Field(f_index as u32, VariantIdx::new(0)),
ProjectionKind::Field(f_index as u32, FIRST_VARIANT),
);
self.delegate_consume(&field_place, field_place.hir_id);
}

View File

@ -59,10 +59,9 @@
use rustc_hir::def_id::LocalDefId;
use rustc_hir::pat_util::EnumerateAndAdjustIterator;
use rustc_hir::PatKind;
use rustc_index::vec::Idx;
use rustc_infer::infer::InferCtxt;
use rustc_span::Span;
use rustc_target::abi::VariantIdx;
use rustc_target::abi::{VariantIdx, FIRST_VARIANT};
use rustc_trait_selection::infer::InferCtxtExt;
pub(crate) trait HirNode {
@ -331,7 +330,7 @@ pub(crate) fn cat_expr_unadjusted(
expr,
base,
expr_ty,
ProjectionKind::Field(field_idx as u32, VariantIdx::new(0)),
ProjectionKind::Field(field_idx as u32, FIRST_VARIANT),
))
}
@ -561,7 +560,7 @@ fn variant_index_for_adt(
| Res::SelfTyParam { .. }
| Res::SelfTyAlias { .. } => {
// Structs and Unions have only have one variant.
Ok(VariantIdx::new(0))
Ok(FIRST_VARIANT)
}
_ => bug!("expected ADT path, found={:?}", res),
}
@ -675,7 +674,7 @@ fn cat_pattern_<F>(
for (i, subpat) in subpats.iter().enumerate_and_adjust(total_fields, dots_pos) {
let subpat_ty = self.pat_ty_adjusted(subpat)?;
let projection_kind = ProjectionKind::Field(i as u32, VariantIdx::new(0));
let projection_kind = ProjectionKind::Field(i as u32, FIRST_VARIANT);
let sub_place =
self.cat_projection(pat, place_with_id.clone(), subpat_ty, projection_kind);
self.cat_pattern_(sub_place, subpat, op)?;

View File

@ -49,8 +49,7 @@
use rustc_trait_selection::infer::InferCtxtExt;
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_index::vec::Idx;
use rustc_target::abi::VariantIdx;
use rustc_target::abi::FIRST_VARIANT;
use std::iter;
@ -1406,7 +1405,7 @@ fn has_significant_drop_outside_of_captures(
ProjectionKind::Field(..)
))
);
def.variants().get(VariantIdx::new(0)).unwrap().fields.iter().enumerate().any(
def.variants().get(FIRST_VARIANT).unwrap().fields.iter().enumerate().any(
|(i, field)| {
let paths_using_field = captured_by_move_projs
.iter()

View File

@ -58,7 +58,6 @@
use rustc_hir::def_id::{DefId, LocalDefId, LocalDefIdSet, CRATE_DEF_ID};
use rustc_hir::intravisit::FnKind as HirFnKind;
use rustc_hir::{Body, FnDecl, ForeignItemKind, GenericParamKind, Node, PatKind, PredicateOrigin};
use rustc_index::vec::Idx;
use rustc_middle::lint::in_external_macro;
use rustc_middle::ty::layout::{LayoutError, LayoutOf};
use rustc_middle::ty::print::with_no_trimmed_paths;
@ -69,7 +68,7 @@
use rustc_span::source_map::Spanned;
use rustc_span::symbol::{kw, sym, Ident, Symbol};
use rustc_span::{BytePos, InnerSpan, Span};
use rustc_target::abi::{Abi, VariantIdx};
use rustc_target::abi::{Abi, FIRST_VARIANT};
use rustc_trait_selection::infer::{InferCtxtExt, TyCtxtInferExt};
use rustc_trait_selection::traits::{self, misc::type_allowed_to_implement_copy};
@ -2788,7 +2787,7 @@ fn structurally_same_type_impl<'tcx>(
);
if is_transparent && !is_non_null {
debug_assert_eq!(def.variants().len(), 1);
let v = &def.variant(VariantIdx::new(0));
let v = &def.variant(FIRST_VARIANT);
// continue with `ty`'s non-ZST field,
// otherwise `ty` is a ZST and we can return
if let Some(field) = transparent_newtype_field(tcx, v) {

View File

@ -10,11 +10,11 @@
use rustc_hir as hir;
use rustc_hir::def::{CtorKind, DefKind, Res};
use rustc_hir::def_id::DefId;
use rustc_index::vec::{Idx, IndexVec};
use rustc_index::vec::IndexVec;
use rustc_query_system::ich::StableHashingContext;
use rustc_session::DataTypeKind;
use rustc_span::symbol::sym;
use rustc_target::abi::{ReprOptions, VariantIdx};
use rustc_target::abi::{ReprOptions, VariantIdx, FIRST_VARIANT};
use std::cell::RefCell;
use std::cmp::Ordering;
@ -228,7 +228,7 @@ pub(super) fn new(
AdtKind::Struct => AdtFlags::IS_STRUCT,
};
if kind == AdtKind::Struct && variants[VariantIdx::new(0)].ctor.is_some() {
if kind == AdtKind::Struct && variants[FIRST_VARIANT].ctor.is_some() {
flags |= AdtFlags::HAS_CTOR;
}
@ -357,7 +357,7 @@ pub fn has_non_const_dtor(self, tcx: TyCtxt<'tcx>) -> bool {
/// Asserts this is a struct or union and returns its unique variant.
pub fn non_enum_variant(self) -> &'tcx VariantDef {
assert!(self.is_struct() || self.is_union());
&self.variant(VariantIdx::new(0))
&self.variant(FIRST_VARIANT)
}
#[inline]
@ -493,7 +493,7 @@ pub fn discriminants(
#[inline]
pub fn variant_range(self) -> Range<VariantIdx> {
VariantIdx::new(0)..VariantIdx::new(self.variants().len())
FIRST_VARIANT..self.variants().next_index()
}
/// Computes the discriminant value used by a specific variant.

View File

@ -22,7 +22,7 @@
use rustc_macros::HashStable;
use rustc_span::symbol::{kw, sym, Symbol};
use rustc_span::Span;
use rustc_target::abi::VariantIdx;
use rustc_target::abi::{VariantIdx, FIRST_VARIANT};
use rustc_target::spec::abi::{self, Abi};
use std::borrow::Cow;
use std::cmp::Ordering;
@ -517,8 +517,7 @@ impl<'tcx> GeneratorSubsts<'tcx> {
#[inline]
pub fn variant_range(&self, def_id: DefId, tcx: TyCtxt<'tcx>) -> Range<VariantIdx> {
// FIXME requires optimized MIR
let num_variants = tcx.generator_layout(def_id).unwrap().variant_fields.len();
VariantIdx::new(0)..VariantIdx::new(num_variants)
FIRST_VARIANT..tcx.generator_layout(def_id).unwrap().variant_fields.next_index()
}
/// The discriminant for the given variant. Panics if the `variant_index` is

View File

@ -13,9 +13,7 @@
use rustc_middle::ty::AdtDef;
use rustc_middle::ty::{self, CanonicalUserTypeAnnotation, Ty, Variance};
use rustc_span::Span;
use rustc_target::abi::VariantIdx;
use rustc_index::vec::Idx;
use rustc_target::abi::{VariantIdx, FIRST_VARIANT};
use std::assert_matches::assert_matches;
use std::iter;
@ -91,7 +89,7 @@ fn convert_to_hir_projections_and_truncate_for_capture(
let hir_projection = match mir_projection {
ProjectionElem::Deref => HirProjectionKind::Deref,
ProjectionElem::Field(field, _) => {
let variant = variant.unwrap_or(VariantIdx::new(0));
let variant = variant.unwrap_or(FIRST_VARIANT);
HirProjectionKind::Field(field.index() as u32, variant)
}
ProjectionElem::Downcast(.., idx) => {

View File

@ -20,7 +20,7 @@
self, AdtKind, InlineConstSubsts, InlineConstSubstsParts, ScalarInt, Ty, UpvarSubsts, UserType,
};
use rustc_span::{sym, Span};
use rustc_target::abi::VariantIdx;
use rustc_target::abi::FIRST_VARIANT;
impl<'tcx> Cx<'tcx> {
pub(crate) fn mirror_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) -> ExprId {
@ -357,7 +357,7 @@ fn make_mirror_unadjusted(&mut self, expr: &'tcx hir::Expr<'tcx>) -> Expr<'tcx>
Res::Def(DefKind::Ctor(_, CtorKind::Fn), ctor_id) => {
Some((adt_def, adt_def.variant_index_with_ctor_id(ctor_id)))
}
Res::SelfCtor(..) => Some((adt_def, VariantIdx::new(0))),
Res::SelfCtor(..) => Some((adt_def, FIRST_VARIANT)),
_ => None,
})
} else {
@ -510,7 +510,7 @@ fn make_mirror_unadjusted(&mut self, expr: &'tcx hir::Expr<'tcx>) -> Expr<'tcx>
debug!("make_mirror_unadjusted: (struct/union) user_ty={:?}", user_ty);
ExprKind::Adt(Box::new(AdtExpr {
adt_def: *adt,
variant_index: VariantIdx::new(0),
variant_index: FIRST_VARIANT,
substs,
user_ty,
fields: self.field_refs(fields),
@ -732,7 +732,7 @@ fn make_mirror_unadjusted(&mut self, expr: &'tcx hir::Expr<'tcx>) -> Expr<'tcx>
}
hir::ExprKind::Field(ref source, ..) => ExprKind::Field {
lhs: self.mirror_expr(source),
variant_index: VariantIdx::new(0),
variant_index: FIRST_VARIANT,
name: Field::new(self.typeck_results.field_index(expr.hir_id)),
},
hir::ExprKind::Cast(ref source, ref cast_ty) => {

View File

@ -60,7 +60,7 @@
use rustc_middle::{middle::stability::EvalResult, mir::interpret::ConstValue};
use rustc_session::lint;
use rustc_span::{Span, DUMMY_SP};
use rustc_target::abi::{Integer, Size, VariantIdx};
use rustc_target::abi::{Integer, Size, VariantIdx, FIRST_VARIANT};
use self::Constructor::*;
use self::SliceKind::*;
@ -706,7 +706,7 @@ fn variant_index_for_adt(&self, adt: ty::AdtDef<'tcx>) -> VariantIdx {
Variant(idx) => idx,
Single => {
assert!(!adt.is_enum());
VariantIdx::new(0)
FIRST_VARIANT
}
_ => bug!("bad constructor {:?} for adt {:?}", self, adt),
}

View File

@ -7,7 +7,7 @@
use rustc_middle::ty::subst::SubstsRef;
use rustc_middle::ty::util::IntTypeExt;
use rustc_middle::ty::{self, Ty, TyCtxt};
use rustc_target::abi::VariantIdx;
use rustc_target::abi::{VariantIdx, FIRST_VARIANT};
use std::{fmt, iter};
/// The value of an inserted drop flag.
@ -468,7 +468,7 @@ fn open_drop_for_adt_contents(
let fields = self.move_paths_for_fields(
self.place,
self.path,
&adt.variant(VariantIdx::new(0)),
&adt.variant(FIRST_VARIANT),
substs,
);
self.drop_ladder(fields, succ, unwind)
@ -894,7 +894,7 @@ fn unelaborated_free_block(
let unit_temp = Place::from(self.new_temp(tcx.mk_unit()));
let free_func = tcx.require_lang_item(LangItem::BoxFree, Some(self.source_info.span));
let args = adt
.variant(VariantIdx::new(0))
.variant(FIRST_VARIANT)
.fields
.iter()
.enumerate()

View File

@ -10,7 +10,7 @@
use rustc_middle::ty::{self, Instance, InstanceDef, ParamEnv, Ty, TyCtxt};
use rustc_session::config::OptLevel;
use rustc_span::{hygiene::ExpnKind, ExpnData, LocalExpnId, Span};
use rustc_target::abi::VariantIdx;
use rustc_target::abi::FIRST_VARIANT;
use rustc_target::spec::abi::Abi;
use crate::simplify::{remove_dead_blocks, CfgSimplifier};
@ -911,7 +911,7 @@ fn visit_projection_elem(
check_equal(self, *f_ty);
}
ty::Adt(adt_def, substs) => {
let var = parent_ty.variant_index.unwrap_or(VariantIdx::from_u32(0));
let var = parent_ty.variant_index.unwrap_or(FIRST_VARIANT);
let Some(field) = adt_def.variant(var).fields.get(f.as_usize()) else {
self.validation = Err("malformed MIR");
return;

View File

@ -5,7 +5,7 @@
use rustc_middle::ty::query::Providers;
use rustc_middle::ty::InternalSubsts;
use rustc_middle::ty::{self, EarlyBinder, GeneratorSubsts, Ty, TyCtxt};
use rustc_target::abi::VariantIdx;
use rustc_target::abi::{VariantIdx, FIRST_VARIANT};
use rustc_index::vec::{Idx, IndexVec};
@ -816,11 +816,8 @@ pub fn build_adt_ctor(tcx: TyCtxt<'_>, ctor_id: DefId) -> Body<'_> {
let source_info = SourceInfo::outermost(span);
let variant_index = if adt_def.is_enum() {
adt_def.variant_index_with_ctor_id(ctor_id)
} else {
VariantIdx::new(0)
};
let variant_index =
if adt_def.is_enum() { adt_def.variant_index_with_ctor_id(ctor_id) } else { FIRST_VARIANT };
// Generate the following MIR:
//

View File

@ -8,7 +8,7 @@
use rustc_middle::ty::{self, Expr, TyCtxt, TypeVisitableExt};
use rustc_middle::{mir, thir};
use rustc_span::Span;
use rustc_target::abi::VariantIdx;
use rustc_target::abi::{VariantIdx, FIRST_VARIANT};
use std::iter;
@ -44,7 +44,7 @@ pub(crate) fn destructure_const<'tcx>(
let (head, rest) = branches.split_first().unwrap();
(VariantIdx::from_u32(head.unwrap_leaf().try_to_u32().unwrap()), rest)
} else {
(VariantIdx::from_u32(0), branches)
(FIRST_VARIANT, branches)
};
let fields = &def.variant(variant_idx).fields;
let mut field_consts = Vec::with_capacity(fields.len());

View File

@ -1,7 +1,7 @@
use hir::def_id::DefId;
use rustc_hir as hir;
use rustc_index::bit_set::BitSet;
use rustc_index::vec::{Idx, IndexVec};
use rustc_index::vec::IndexVec;
use rustc_middle::mir::{GeneratorLayout, GeneratorSavedLocal};
use rustc_middle::ty::layout::{
IntegerExt, LayoutCx, LayoutError, LayoutOf, TyAndLayout, MAX_SIMD_LANES,
@ -227,7 +227,7 @@ fn layout_of_uncached<'tcx>(
let largest_niche = if count != 0 { element.largest_niche } else { None };
tcx.mk_layout(LayoutS {
variants: Variants::Single { index: VariantIdx::new(0) },
variants: Variants::Single { index: FIRST_VARIANT },
fields: FieldsShape::Array { stride: element.size, count },
abi,
largest_niche,
@ -238,7 +238,7 @@ fn layout_of_uncached<'tcx>(
ty::Slice(element) => {
let element = cx.layout_of(element)?;
tcx.mk_layout(LayoutS {
variants: Variants::Single { index: VariantIdx::new(0) },
variants: Variants::Single { index: FIRST_VARIANT },
fields: FieldsShape::Array { stride: element.size, count: 0 },
abi: Abi::Aggregate { sized: false },
largest_niche: None,
@ -247,7 +247,7 @@ fn layout_of_uncached<'tcx>(
})
}
ty::Str => tcx.mk_layout(LayoutS {
variants: Variants::Single { index: VariantIdx::new(0) },
variants: Variants::Single { index: FIRST_VARIANT },
fields: FieldsShape::Array { stride: Size::from_bytes(1), count: 0 },
abi: Abi::Aggregate { sized: false },
largest_niche: None,
@ -399,7 +399,7 @@ fn layout_of_uncached<'tcx>(
};
tcx.mk_layout(LayoutS {
variants: Variants::Single { index: VariantIdx::new(0) },
variants: Variants::Single { index: FIRST_VARIANT },
fields,
abi: Abi::Vector { element: e_abi, count: e_len },
largest_niche: e_ly.largest_niche,