authorbors <bors@rust-lang.org> 2023-04-02 21:40:29 UTC
committerbors <bors@rust-lang.org> 2023-04-02 21:40:29 UTC
loga93bcdc30771340dfff914a1cf48556886ad33a6
treeaf18945bacc5061e824a46c8dfa5dce862c9657b
parent3a8a131e9509c478ece1c58fe0ea2d49463d2300
parentb5b6def021d37c5f1cb7e06c1cf6915bcbcd53b1

Auto merge of #109849 - scottmcm:more-fieldidx-rebase, r=oli-obk

Use `FieldIdx` in various things related to aggregates Shrank `AggregateKind` by 8 bytes on x64, since the active field of a union is tracked as an `Option<FieldIdx>` instead of `Option<usize>`. Part 3/? of https://github.com/rust-lang/compiler-team/issues/606 [`IndexSlice`](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_index/vec/struct.IndexVec.html#deref-methods-IndexSlice%3CI,+T%3E) was added in https://github.com/rust-lang/rust/pull/109787

13 files changed, 51 insertions(+), 46 deletions(-)

compiler/rustc_borrowck/src/diagnostics/mod.rs+3-2
......@@ -6,6 +6,7 @@ use rustc_errors::{Applicability, Diagnostic};
66use rustc_hir as hir;
77use rustc_hir::def::{CtorKind, Namespace};
88use rustc_hir::GeneratorKind;
9use rustc_index::vec::IndexSlice;
910use rustc_infer::infer::{LateBoundRegionConversionTime, TyCtxtInferExt};
1011use rustc_middle::mir::tcx::PlaceTy;
1112use rustc_middle::mir::{
......@@ -825,7 +826,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
825826 debug!("move_spans: def_id={:?} place={:?}", closure_def_id, place);
826827 let places = &[Operand::Move(place)];
827828 if let Some((args_span, generator_kind, capture_kind_span, path_span)) =
828 self.closure_span(closure_def_id, moved_place, places)
829 self.closure_span(closure_def_id, moved_place, IndexSlice::from_raw(places))
829830 {
830831 return ClosureUse {
831832 generator_kind,
......@@ -975,7 +976,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
975976 &self,
976977 def_id: LocalDefId,
977978 target_place: PlaceRef<'tcx>,
978 places: &[Operand<'tcx>],
979 places: &IndexSlice<FieldIdx, Operand<'tcx>>,
979980 ) -> Option<(Span, Option<GeneratorKind>, Span, Span)> {
980981 debug!(
981982 "closure_span: def_id={:?} target_place={:?} places={:?}",
compiler/rustc_borrowck/src/lib.rs+1-1
......@@ -1343,7 +1343,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
13431343 self.infcx.tcx.mir_borrowck(def_id);
13441344 debug!("{:?} used_mut_upvars={:?}", def_id, used_mut_upvars);
13451345 for field in used_mut_upvars {
1346 self.propagate_closure_used_mut_upvar(&operands[field.index()]);
1346 self.propagate_closure_used_mut_upvar(&operands[*field]);
13471347 }
13481348 }
13491349 AggregateKind::Adt(..)
compiler/rustc_borrowck/src/type_check/mod.rs+9-10
......@@ -14,7 +14,7 @@ use rustc_hir as hir;
1414use rustc_hir::def::DefKind;
1515use rustc_hir::def_id::LocalDefId;
1616use rustc_hir::lang_items::LangItem;
17use rustc_index::vec::IndexVec;
17use rustc_index::vec::{IndexSlice, IndexVec};
1818use rustc_infer::infer::canonical::QueryRegionConstraints;
1919use rustc_infer::infer::outlives::env::RegionBoundPairs;
2020use rustc_infer::infer::region_constraints::RegionConstraintData;
......@@ -1716,7 +1716,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
17161716 fn aggregate_field_ty(
17171717 &mut self,
17181718 ak: &AggregateKind<'tcx>,
1719 field_index: usize,
1719 field_index: FieldIdx,
17201720 location: Location,
17211721 ) -> Result<Ty<'tcx>, FieldAccessError> {
17221722 let tcx = self.tcx();
......@@ -1725,8 +1725,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
17251725 AggregateKind::Adt(adt_did, variant_index, substs, _, active_field_index) => {
17261726 let def = tcx.adt_def(adt_did);
17271727 let variant = &def.variant(variant_index);
1728 let adj_field_index =
1729 FieldIdx::from_usize(active_field_index.unwrap_or(field_index));
1728 let adj_field_index = active_field_index.unwrap_or(field_index);
17301729 if let Some(field) = variant.fields.get(adj_field_index) {
17311730 Ok(self.normalize(field.ty(tcx, substs), location))
17321731 } else {
......@@ -1734,7 +1733,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
17341733 }
17351734 }
17361735 AggregateKind::Closure(_, substs) => {
1737 match substs.as_closure().upvar_tys().nth(field_index) {
1736 match substs.as_closure().upvar_tys().nth(field_index.as_usize()) {
17381737 Some(ty) => Ok(ty),
17391738 None => Err(FieldAccessError::OutOfRange {
17401739 field_count: substs.as_closure().upvar_tys().count(),
......@@ -1745,7 +1744,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
17451744 // It doesn't make sense to look at a field beyond the prefix;
17461745 // these require a variant index, and are not initialized in
17471746 // aggregate rvalues.
1748 match substs.as_generator().prefix_tys().nth(field_index) {
1747 match substs.as_generator().prefix_tys().nth(field_index.as_usize()) {
17491748 Some(ty) => Ok(ty),
17501749 None => Err(FieldAccessError::OutOfRange {
17511750 field_count: substs.as_generator().prefix_tys().count(),
......@@ -2350,7 +2349,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
23502349 body: &Body<'tcx>,
23512350 rvalue: &Rvalue<'tcx>,
23522351 aggregate_kind: &AggregateKind<'tcx>,
2353 operands: &[Operand<'tcx>],
2352 operands: &IndexSlice<FieldIdx, Operand<'tcx>>,
23542353 location: Location,
23552354 ) {
23562355 let tcx = self.tcx();
......@@ -2362,7 +2361,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
23622361 return;
23632362 }
23642363
2365 for (i, operand) in operands.iter().enumerate() {
2364 for (i, operand) in operands.iter_enumerated() {
23662365 let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
23672366 Ok(field_ty) => field_ty,
23682367 Err(FieldAccessError::OutOfRange { field_count }) => {
......@@ -2370,8 +2369,8 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
23702369 self,
23712370 rvalue,
23722371 "accessed field #{} but variant only has {}",
2373 i,
2374 field_count
2372 i.as_u32(),
2373 field_count,
23752374 );
23762375 continue;
23772376 }
compiler/rustc_codegen_cranelift/src/base.rs+4-3
......@@ -802,14 +802,15 @@ fn codegen_stmt<'tcx>(
802802 if active_field_index.is_some() {
803803 assert_eq!(operands.len(), 1);
804804 }
805 for (i, operand) in operands.iter().enumerate() {
805 for (i, operand) in operands.iter_enumerated() {
806806 let operand = codegen_operand(fx, operand);
807807 let field_index = active_field_index.unwrap_or(i);
808808 let to = if let mir::AggregateKind::Array(_) = **kind {
809 let index = fx.bcx.ins().iconst(fx.pointer_type, field_index as i64);
809 let array_index = i64::from(field_index.as_u32());
810 let index = fx.bcx.ins().iconst(fx.pointer_type, array_index);
810811 variant_dest.place_index(fx, index)
811812 } else {
812 variant_dest.place_field(fx, FieldIdx::new(field_index))
813 variant_dest.place_field(fx, field_index)
813814 };
814815 to.write_cvalue(fx, operand);
815816 }
compiler/rustc_codegen_ssa/src/base.rs+3-3
......@@ -306,9 +306,9 @@ pub fn coerce_unsized_into<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
306306 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
307307 assert_eq!(def_a, def_b);
308308
309 for i in 0..def_a.variant(FIRST_VARIANT).fields.len() {
310 let src_f = src.project_field(bx, i);
311 let dst_f = dst.project_field(bx, i);
309 for i in def_a.variant(FIRST_VARIANT).fields.indices() {
310 let src_f = src.project_field(bx, i.as_usize());
311 let dst_f = dst.project_field(bx, i.as_usize());
312312
313313 if dst_f.layout.is_zst() {
314314 continue;
compiler/rustc_codegen_ssa/src/mir/rvalue.rs+3-3
......@@ -123,16 +123,16 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
123123 if active_field_index.is_some() {
124124 assert_eq!(operands.len(), 1);
125125 }
126 for (i, operand) in operands.iter().enumerate() {
126 for (i, operand) in operands.iter_enumerated() {
127127 let op = self.codegen_operand(bx, operand);
128128 // Do not generate stores and GEPis for zero-sized fields.
129129 if !op.layout.is_zst() {
130130 let field_index = active_field_index.unwrap_or(i);
131131 let field = if let mir::AggregateKind::Array(_) = **kind {
132 let llindex = bx.cx().const_usize(field_index as u64);
132 let llindex = bx.cx().const_usize(field_index.as_u32().into());
133133 variant_dest.project_index(bx, llindex)
134134 } else {
135 variant_dest.project_field(bx, field_index)
135 variant_dest.project_field(bx, field_index.as_usize())
136136 };
137137 op.val.store(bx, field);
138138 }
compiler/rustc_const_eval/src/interpret/place.rs+5-4
......@@ -5,10 +5,11 @@
55use either::{Either, Left, Right};
66
77use rustc_ast::Mutability;
8use rustc_index::vec::IndexSlice;
89use rustc_middle::mir;
910use rustc_middle::ty;
1011use rustc_middle::ty::layout::{LayoutOf, TyAndLayout};
11use rustc_target::abi::{self, Abi, Align, HasDataLayout, Size, FIRST_VARIANT};
12use rustc_target::abi::{self, Abi, Align, FieldIdx, HasDataLayout, Size, FIRST_VARIANT};
1213
1314use super::{
1415 alloc_range, mir_assign_valid_types, AllocId, AllocRef, AllocRefMut, CheckInAllocMsg,
......@@ -787,7 +788,7 @@ where
787788 pub fn write_aggregate(
788789 &mut self,
789790 kind: &mir::AggregateKind<'tcx>,
790 operands: &[mir::Operand<'tcx>],
791 operands: &IndexSlice<FieldIdx, mir::Operand<'tcx>>,
791792 dest: &PlaceTy<'tcx, M::Provenance>,
792793 ) -> InterpResult<'tcx> {
793794 self.write_uninit(&dest)?;
......@@ -801,9 +802,9 @@ where
801802 if active_field_index.is_some() {
802803 assert_eq!(operands.len(), 1);
803804 }
804 for (field_index, operand) in operands.iter().enumerate() {
805 for (field_index, operand) in operands.iter_enumerated() {
805806 let field_index = active_field_index.unwrap_or(field_index);
806 let field_dest = self.place_field(&variant_dest, field_index)?;
807 let field_dest = self.place_field(&variant_dest, field_index.as_usize())?;
807808 let op = self.eval_operand(operand, Some(field_dest.layout))?;
808809 self.copy_op(&op, &field_dest, /*allow_transmute*/ false)?;
809810 }
compiler/rustc_index/src/vec.rs+6
......@@ -93,6 +93,12 @@ impl<I: Idx, T: fmt::Debug> fmt::Debug for IndexVec<I, T> {
9393 }
9494}
9595
96impl<I: Idx, T: fmt::Debug> fmt::Debug for IndexSlice<I, T> {
97 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
98 fmt::Debug::fmt(&self.raw, fmt)
99 }
100}
101
96102impl<I: Idx, T> IndexVec<I, T> {
97103 #[inline]
98104 pub fn new() -> Self {
compiler/rustc_middle/src/mir/syntax.rs+4-3
......@@ -16,6 +16,7 @@ use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
1616use rustc_hir::def_id::DefId;
1717use rustc_hir::{self as hir};
1818use rustc_hir::{self, GeneratorKind};
19use rustc_index::vec::IndexVec;
1920use rustc_target::abi::{FieldIdx, VariantIdx};
2021
2122use rustc_ast::Mutability;
......@@ -1125,7 +1126,7 @@ pub enum Rvalue<'tcx> {
11251126 ///
11261127 /// Disallowed after deaggregation for all aggregate kinds except `Array` and `Generator`. After
11271128 /// generator lowering, `Generator` aggregate kinds are disallowed too.
1128 Aggregate(Box<AggregateKind<'tcx>>, Vec<Operand<'tcx>>),
1129 Aggregate(Box<AggregateKind<'tcx>>, IndexVec<FieldIdx, Operand<'tcx>>),
11291130
11301131 /// Transmutes a `*mut u8` into shallow-initialized `Box<T>`.
11311132 ///
......@@ -1186,7 +1187,7 @@ pub enum AggregateKind<'tcx> {
11861187 /// active field number and is present only for union expressions
11871188 /// -- e.g., for a union expression `SomeUnion { c: .. }`, the
11881189 /// active field index would identity the field `c`
1189 Adt(DefId, VariantIdx, SubstsRef<'tcx>, Option<UserTypeAnnotationIndex>, Option<usize>),
1190 Adt(DefId, VariantIdx, SubstsRef<'tcx>, Option<UserTypeAnnotationIndex>, Option<FieldIdx>),
11901191
11911192 Closure(DefId, SubstsRef<'tcx>),
11921193 Generator(DefId, SubstsRef<'tcx>, hir::Movability),
......@@ -1263,7 +1264,7 @@ pub enum BinOp {
12631264mod size_asserts {
12641265 use super::*;
12651266 // tidy-alphabetical-start
1266 static_assert_size!(AggregateKind<'_>, 40);
1267 static_assert_size!(AggregateKind<'_>, 32);
12671268 static_assert_size!(Operand<'_>, 24);
12681269 static_assert_size!(Place<'_>, 16);
12691270 static_assert_size!(PlaceElem<'_>, 24);
compiler/rustc_mir_build/src/build/custom/parse/instruction.rs+1-1
......@@ -185,7 +185,7 @@ impl<'tcx, 'body> ParseCtxt<'tcx, 'body> {
185185 },
186186 ExprKind::Adt(box AdtExpr{ adt_def, variant_index, substs, fields, .. }) => {
187187 let is_union = adt_def.is_union();
188 let active_field_index = is_union.then(|| fields[0].name.index());
188 let active_field_index = is_union.then(|| fields[0].name);
189189
190190 Ok(Rvalue::Aggregate(
191191 Box::new(AggregateKind::Adt(adt_def.did(), *variant_index, substs, None, active_field_index)),
compiler/rustc_mir_build/src/build/expr/as_rvalue.rs+6-7
......@@ -1,8 +1,8 @@
11//! See docs in `build/expr/mod.rs`.
22
3use rustc_index::vec::Idx;
3use rustc_index::vec::{Idx, IndexVec};
44use rustc_middle::ty::util::IntTypeExt;
5use rustc_target::abi::{Abi, Primitive};
5use rustc_target::abi::{Abi, FieldIdx, Primitive};
66
77use crate::build::expr::as_place::PlaceBase;
88use crate::build::expr::category::{Category, RvalueFunc};
......@@ -17,7 +17,6 @@ use rustc_middle::thir::*;
1717use rustc_middle::ty::cast::{mir_cast_kind, CastTy};
1818use rustc_middle::ty::{self, Ty, UpvarSubsts};
1919use rustc_span::Span;
20use rustc_target::abi::FieldIdx;
2120
2221impl<'a, 'tcx> Builder<'a, 'tcx> {
2322 /// Returns an rvalue suitable for use until the end of the current
......@@ -327,7 +326,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
327326
328327 // first process the set of fields
329328 let el_ty = expr.ty.sequence_element_type(this.tcx);
330 let fields: Vec<_> = fields
329 let fields: IndexVec<FieldIdx, _> = fields
331330 .into_iter()
332331 .copied()
333332 .map(|f| {
......@@ -348,7 +347,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
348347 ExprKind::Tuple { ref fields } => {
349348 // see (*) above
350349 // first process the set of fields
351 let fields: Vec<_> = fields
350 let fields: IndexVec<FieldIdx, _> = fields
352351 .into_iter()
353352 .copied()
354353 .map(|f| {
......@@ -402,7 +401,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
402401 }
403402
404403 // see (*) above
405 let operands: Vec<_> = upvars
404 let operands: IndexVec<FieldIdx, _> = upvars
406405 .into_iter()
407406 .copied()
408407 .map(|upvar| {
......@@ -710,7 +709,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
710709 }
711710 this.record_operands_moved(&[value_operand]);
712711 }
713 block.and(Rvalue::Aggregate(Box::new(AggregateKind::Array(elem_ty)), Vec::new()))
712 block.and(Rvalue::Aggregate(Box::new(AggregateKind::Array(elem_ty)), IndexVec::new()))
714713 }
715714
716715 fn limit_capture_mutability(
compiler/rustc_mir_build/src/build/expr/into.rs+4-7
......@@ -6,11 +6,9 @@ use rustc_ast::InlineAsmOptions;
66use rustc_data_structures::fx::FxHashMap;
77use rustc_data_structures::stack::ensure_sufficient_stack;
88use rustc_hir as hir;
9use rustc_index::vec::Idx;
109use rustc_middle::mir::*;
1110use rustc_middle::thir::*;
1211use rustc_middle::ty::CanonicalUserTypeAnnotation;
13use rustc_target::abi::FieldIdx;
1412use std::iter;
1513
1614impl<'a, 'tcx> Builder<'a, 'tcx> {
......@@ -320,7 +318,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
320318 // See the notes for `ExprKind::Array` in `as_rvalue` and for
321319 // `ExprKind::Borrow` above.
322320 let is_union = adt_def.is_union();
323 let active_field_index = is_union.then(|| fields[0].name.index());
321 let active_field_index = is_union.then(|| fields[0].name);
324322
325323 let scope = this.local_scope();
326324
......@@ -344,10 +342,9 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
344342 })
345343 .collect();
346344
347 let field_names: Vec<_> =
348 (0..adt_def.variant(variant_index).fields.len()).map(FieldIdx::new).collect();
345 let field_names = adt_def.variant(variant_index).fields.indices();
349346
350 let fields: Vec<_> = if let Some(FruInfo { base, field_types }) = base {
347 let fields = if let Some(FruInfo { base, field_types }) = base {
351348 let place_builder =
352349 unpack!(block = this.as_place_builder(block, &this.thir[*base]));
353350
......@@ -364,7 +361,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
364361 })
365362 .collect()
366363 } else {
367 field_names.iter().filter_map(|n| fields_map.get(n).cloned()).collect()
364 field_names.filter_map(|n| fields_map.get(&n).cloned()).collect()
368365 };
369366
370367 let inferred_ty = expr.ty;
compiler/rustc_mir_transform/src/generator.rs+2-2
......@@ -274,7 +274,7 @@ impl<'tcx> TransformVisitor<'tcx> {
274274 statements.push(Statement {
275275 kind: StatementKind::Assign(Box::new((
276276 Place::return_place(),
277 Rvalue::Aggregate(Box::new(kind), vec![]),
277 Rvalue::Aggregate(Box::new(kind), IndexVec::new()),
278278 ))),
279279 source_info,
280280 });
......@@ -287,7 +287,7 @@ impl<'tcx> TransformVisitor<'tcx> {
287287 statements.push(Statement {
288288 kind: StatementKind::Assign(Box::new((
289289 Place::return_place(),
290 Rvalue::Aggregate(Box::new(kind), vec![val]),
290 Rvalue::Aggregate(Box::new(kind), IndexVec::from_iter([val])),
291291 ))),
292292 source_info,
293293 });