Skip to content

Commit ca3516b

Browse files
relocate upvars to Unresumed state and make coroutine prefix trivial
Co-authored-by: Dario Nieuwenhuis <[email protected]>
1 parent 334e509 commit ca3516b

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

54 files changed

+950
-399
lines changed

Diff for: compiler/rustc_borrowck/src/lib.rs

+21-4
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ use std::rc::Rc;
2626
use consumers::{BodyWithBorrowckFacts, ConsumerOptions};
2727
use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
2828
use rustc_data_structures::graph::dominators::Dominators;
29+
use rustc_data_structures::unord::UnordMap;
2930
use rustc_errors::Diag;
3031
use rustc_hir as hir;
3132
use rustc_hir::def_id::LocalDefId;
@@ -292,6 +293,7 @@ fn do_mir_borrowck<'tcx>(
292293
regioncx: regioncx.clone(),
293294
used_mut: Default::default(),
294295
used_mut_upvars: SmallVec::new(),
296+
local_from_upvars: UnordMap::default(),
295297
borrow_set: Rc::clone(&borrow_set),
296298
upvars: &[],
297299
local_names: IndexVec::from_elem(None, &promoted_body.local_decls),
@@ -318,6 +320,12 @@ fn do_mir_borrowck<'tcx>(
318320
}
319321
}
320322

323+
let mut local_from_upvars = UnordMap::default();
324+
for (field, &local) in body.local_upvar_map.iter_enumerated() {
325+
let Some(local) = local else { continue };
326+
local_from_upvars.insert(local, field);
327+
}
328+
debug!(?local_from_upvars, "dxf");
321329
let mut mbcx = MirBorrowckCtxt {
322330
infcx: &infcx,
323331
param_env,
@@ -333,6 +341,7 @@ fn do_mir_borrowck<'tcx>(
333341
regioncx: Rc::clone(&regioncx),
334342
used_mut: Default::default(),
335343
used_mut_upvars: SmallVec::new(),
344+
local_from_upvars,
336345
borrow_set: Rc::clone(&borrow_set),
337346
upvars: tcx.closure_captures(def),
338347
local_names,
@@ -568,6 +577,9 @@ struct MirBorrowckCtxt<'a, 'mir, 'infcx, 'tcx> {
568577
/// If the function we're checking is a closure, then we'll need to report back the list of
569578
/// mutable upvars that have been used. This field keeps track of them.
570579
used_mut_upvars: SmallVec<[FieldIdx; 8]>,
580+
/// Since upvars are moved to real locals, we need to map mutations to the locals back to
581+
/// the upvars, so that used_mut_upvars is up-to-date.
582+
local_from_upvars: UnordMap<Local, FieldIdx>,
571583
/// Region inference context. This contains the results from region inference and lets us e.g.
572584
/// find out which CFG points are contained in each borrow region.
573585
regioncx: Rc<RegionInferenceContext<'tcx>>,
@@ -2230,16 +2242,19 @@ impl<'mir, 'tcx> MirBorrowckCtxt<'_, 'mir, '_, 'tcx> {
22302242
}
22312243

22322244
/// Adds the place into the used mutable variables set
2245+
#[instrument(level = "debug", skip(self, flow_state))]
22332246
fn add_used_mut(&mut self, root_place: RootPlace<'tcx>, flow_state: &Flows<'_, 'mir, 'tcx>) {
22342247
match root_place {
22352248
RootPlace { place_local: local, place_projection: [], is_local_mutation_allowed } => {
22362249
// If the local may have been initialized, and it is now currently being
22372250
// mutated, then it is justified to be annotated with the `mut`
22382251
// keyword, since the mutation may be a possible reassignment.
2239-
if is_local_mutation_allowed != LocalMutationIsAllowed::Yes
2240-
&& self.is_local_ever_initialized(local, flow_state).is_some()
2241-
{
2242-
self.used_mut.insert(local);
2252+
if !matches!(is_local_mutation_allowed, LocalMutationIsAllowed::Yes) {
2253+
if self.is_local_ever_initialized(local, flow_state).is_some() {
2254+
self.used_mut.insert(local);
2255+
} else if let Some(&field) = self.local_from_upvars.get(&local) {
2256+
self.used_mut_upvars.push(field);
2257+
}
22432258
}
22442259
}
22452260
RootPlace {
@@ -2257,6 +2272,8 @@ impl<'mir, 'tcx> MirBorrowckCtxt<'_, 'mir, '_, 'tcx> {
22572272
projection: place_projection,
22582273
}) {
22592274
self.used_mut_upvars.push(field);
2275+
} else if let Some(&field) = self.local_from_upvars.get(&place_local) {
2276+
self.used_mut_upvars.push(field);
22602277
}
22612278
}
22622279
}

Diff for: compiler/rustc_borrowck/src/type_check/mod.rs

+12-12
Original file line numberDiff line numberDiff line change
@@ -811,15 +811,15 @@ impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> {
811811
}),
812812
};
813813
}
814-
ty::Coroutine(_, args) => {
814+
ty::Coroutine(_def_id, args) => {
815815
// Only prefix fields (upvars and current state) are
816816
// accessible without a variant index.
817-
return match args.as_coroutine().prefix_tys().get(field.index()) {
818-
Some(ty) => Ok(*ty),
819-
None => Err(FieldAccessError::OutOfRange {
820-
field_count: args.as_coroutine().prefix_tys().len(),
821-
}),
822-
};
817+
let upvar_tys = args.as_coroutine().upvar_tys();
818+
if let Some(ty) = upvar_tys.get(field.index()) {
819+
return Ok(*ty);
820+
} else {
821+
return Err(FieldAccessError::OutOfRange { field_count: upvar_tys.len() });
822+
}
823823
}
824824
ty::Tuple(tys) => {
825825
return match tys.get(field.index()) {
@@ -1837,11 +1837,11 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
18371837
// It doesn't make sense to look at a field beyond the prefix;
18381838
// these require a variant index, and are not initialized in
18391839
// aggregate rvalues.
1840-
match args.as_coroutine().prefix_tys().get(field_index.as_usize()) {
1841-
Some(ty) => Ok(*ty),
1842-
None => Err(FieldAccessError::OutOfRange {
1843-
field_count: args.as_coroutine().prefix_tys().len(),
1844-
}),
1840+
let upvar_tys = &args.as_coroutine().upvar_tys();
1841+
if let Some(ty) = upvar_tys.get(field_index.as_usize()) {
1842+
Ok(*ty)
1843+
} else {
1844+
Err(FieldAccessError::OutOfRange { field_count: upvar_tys.len() })
18451845
}
18461846
}
18471847
AggregateKind::CoroutineClosure(_, args) => {

Diff for: compiler/rustc_codegen_cranelift/src/base.rs

+3
Original file line numberDiff line numberDiff line change
@@ -880,6 +880,9 @@ fn codegen_stmt<'tcx>(
880880
let variant_dest = lval.downcast_variant(fx, variant_index);
881881
(variant_index, variant_dest, active_field_index)
882882
}
883+
mir::AggregateKind::Coroutine(_def_id, _args) => {
884+
(FIRST_VARIANT, lval.downcast_variant(fx, FIRST_VARIANT), None)
885+
}
883886
_ => (FIRST_VARIANT, lval, None),
884887
};
885888
if active_field_index.is_some() {

Diff for: compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs

+2-3
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,7 @@ use rustc_hir::def_id::{DefId, LOCAL_CRATE};
1313
use rustc_middle::bug;
1414
use rustc_middle::ty::layout::{LayoutOf, TyAndLayout};
1515
use rustc_middle::ty::{
16-
self, AdtKind, CoroutineArgsExt, Instance, ParamEnv, PolyExistentialTraitRef, Ty, TyCtxt,
17-
Visibility,
16+
self, AdtKind, Instance, ParamEnv, PolyExistentialTraitRef, Ty, TyCtxt, Visibility,
1817
};
1918
use rustc_session::config::{self, DebugInfo, Lto};
2019
use rustc_span::symbol::Symbol;
@@ -1110,7 +1109,7 @@ fn build_upvar_field_di_nodes<'ll, 'tcx>(
11101109
closure_or_coroutine_di_node: &'ll DIType,
11111110
) -> SmallVec<&'ll DIType> {
11121111
let (&def_id, up_var_tys) = match closure_or_coroutine_ty.kind() {
1113-
ty::Coroutine(def_id, args) => (def_id, args.as_coroutine().prefix_tys()),
1112+
ty::Coroutine(def_id, args) => (def_id, args.as_coroutine().upvar_tys()),
11141113
ty::Closure(def_id, args) => (def_id, args.as_closure().upvar_tys()),
11151114
ty::CoroutineClosure(def_id, args) => (def_id, args.as_coroutine_closure().upvar_tys()),
11161115
_ => {

Diff for: compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/cpp_like.rs

-2
Original file line numberDiff line numberDiff line change
@@ -672,7 +672,6 @@ fn build_union_fields_for_direct_tag_coroutine<'ll, 'tcx>(
672672
let coroutine_layout =
673673
cx.tcx.coroutine_layout(coroutine_def_id, coroutine_args.kind_ty()).unwrap();
674674

675-
let common_upvar_names = cx.tcx.closure_saved_names_of_captured_variables(coroutine_def_id);
676675
let variant_range = coroutine_args.variant_range(coroutine_def_id, cx.tcx);
677676
let variant_count = (variant_range.start.as_u32()..variant_range.end.as_u32()).len();
678677

@@ -707,7 +706,6 @@ fn build_union_fields_for_direct_tag_coroutine<'ll, 'tcx>(
707706
coroutine_type_and_layout,
708707
coroutine_type_di_node,
709708
coroutine_layout,
710-
common_upvar_names,
711709
);
712710

713711
let span = coroutine_layout.variant_source_info[variant_index].span;

Diff for: compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/mod.rs

+2-31
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,10 @@ use std::borrow::Cow;
33
use rustc_codegen_ssa::debuginfo::type_names::{compute_debuginfo_type_name, cpp_like_debuginfo};
44
use rustc_codegen_ssa::debuginfo::{tag_base_type, wants_c_like_enum_debuginfo};
55
use rustc_hir::def::CtorKind;
6-
use rustc_index::IndexSlice;
76
use rustc_middle::bug;
87
use rustc_middle::mir::CoroutineLayout;
98
use rustc_middle::ty::layout::{LayoutOf, TyAndLayout};
109
use rustc_middle::ty::{self, AdtDef, CoroutineArgs, CoroutineArgsExt, Ty, VariantDef};
11-
use rustc_span::Symbol;
1210
use rustc_target::abi::{FieldIdx, TagEncoding, VariantIdx, Variants};
1311

1412
use super::type_map::{DINodeCreationResult, UniqueTypeId};
@@ -263,7 +261,6 @@ pub fn build_coroutine_variant_struct_type_di_node<'ll, 'tcx>(
263261
coroutine_type_and_layout: TyAndLayout<'tcx>,
264262
coroutine_type_di_node: &'ll DIType,
265263
coroutine_layout: &CoroutineLayout<'tcx>,
266-
common_upvar_names: &IndexSlice<FieldIdx, Symbol>,
267264
) -> &'ll DIType {
268265
let variant_name = CoroutineArgs::variant_name(variant_index);
269266
let unique_type_id = UniqueTypeId::for_enum_variant_struct_type(
@@ -274,11 +271,6 @@ pub fn build_coroutine_variant_struct_type_di_node<'ll, 'tcx>(
274271

275272
let variant_layout = coroutine_type_and_layout.for_variant(cx, variant_index);
276273

277-
let coroutine_args = match coroutine_type_and_layout.ty.kind() {
278-
ty::Coroutine(_, args) => args.as_coroutine(),
279-
_ => unreachable!(),
280-
};
281-
282274
type_map::build_type_with_children(
283275
cx,
284276
type_map::stub(
@@ -292,7 +284,7 @@ pub fn build_coroutine_variant_struct_type_di_node<'ll, 'tcx>(
292284
),
293285
|cx, variant_struct_type_di_node| {
294286
// Fields that just belong to this variant/state
295-
let state_specific_fields: SmallVec<_> = (0..variant_layout.fields.count())
287+
(0..variant_layout.fields.count())
296288
.map(|field_index| {
297289
let coroutine_saved_local = coroutine_layout.variant_fields[variant_index]
298290
[FieldIdx::from_usize(field_index)];
@@ -314,28 +306,7 @@ pub fn build_coroutine_variant_struct_type_di_node<'ll, 'tcx>(
314306
type_di_node(cx, field_type),
315307
)
316308
})
317-
.collect();
318-
319-
// Fields that are common to all states
320-
let common_fields: SmallVec<_> = coroutine_args
321-
.prefix_tys()
322-
.iter()
323-
.zip(common_upvar_names)
324-
.enumerate()
325-
.map(|(index, (upvar_ty, upvar_name))| {
326-
build_field_di_node(
327-
cx,
328-
variant_struct_type_di_node,
329-
upvar_name.as_str(),
330-
cx.size_and_align_of(upvar_ty),
331-
coroutine_type_and_layout.fields.offset(index),
332-
DIFlags::FlagZero,
333-
type_di_node(cx, upvar_ty),
334-
)
335-
})
336-
.collect();
337-
338-
state_specific_fields.into_iter().chain(common_fields).collect()
309+
.collect()
339310
},
340311
|cx| build_generic_type_param_di_nodes(cx, coroutine_type_and_layout.ty),
341312
)

Diff for: compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/native.rs

-4
Original file line numberDiff line numberDiff line change
@@ -160,9 +160,6 @@ pub(super) fn build_coroutine_di_node<'ll, 'tcx>(
160160
)
161161
};
162162

163-
let common_upvar_names =
164-
cx.tcx.closure_saved_names_of_captured_variables(coroutine_def_id);
165-
166163
// Build variant struct types
167164
let variant_struct_type_di_nodes: SmallVec<_> = variants
168165
.indices()
@@ -190,7 +187,6 @@ pub(super) fn build_coroutine_di_node<'ll, 'tcx>(
190187
coroutine_type_and_layout,
191188
coroutine_type_di_node,
192189
coroutine_layout,
193-
common_upvar_names,
194190
),
195191
source_info,
196192
}

Diff for: compiler/rustc_codegen_ssa/src/mir/operand.rs

+4-7
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ use rustc_middle::mir::{self, ConstValue};
99
use rustc_middle::ty::layout::{LayoutOf, TyAndLayout};
1010
use rustc_middle::ty::Ty;
1111
use rustc_target::abi::{self, Abi, Align, Size};
12-
use tracing::debug;
12+
use tracing::{debug, instrument};
1313

1414
use super::place::{PlaceRef, PlaceValue};
1515
use super::{FunctionCx, LocalRef};
@@ -550,13 +550,12 @@ impl<'a, 'tcx, V: CodegenObject> OperandValue<V> {
550550
}
551551

552552
impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
553+
#[instrument(level = "debug", skip(self, bx), ret)]
553554
fn maybe_codegen_consume_direct(
554555
&mut self,
555556
bx: &mut Bx,
556557
place_ref: mir::PlaceRef<'tcx>,
557558
) -> Option<OperandRef<'tcx, Bx::Value>> {
558-
debug!("maybe_codegen_consume_direct(place_ref={:?})", place_ref);
559-
560559
match self.locals[place_ref.local] {
561560
LocalRef::Operand(mut o) => {
562561
// Moves out of scalar and scalar pair fields are trivial.
@@ -599,13 +598,12 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
599598
}
600599
}
601600

601+
#[instrument(level = "debug", skip(self, bx), ret)]
602602
pub fn codegen_consume(
603603
&mut self,
604604
bx: &mut Bx,
605605
place_ref: mir::PlaceRef<'tcx>,
606606
) -> OperandRef<'tcx, Bx::Value> {
607-
debug!("codegen_consume(place_ref={:?})", place_ref);
608-
609607
let ty = self.monomorphized_place_ty(place_ref);
610608
let layout = bx.cx().layout_of(ty);
611609

@@ -624,13 +622,12 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
624622
bx.load_operand(place)
625623
}
626624

625+
#[instrument(level = "debug", skip(self, bx), ret)]
627626
pub fn codegen_operand(
628627
&mut self,
629628
bx: &mut Bx,
630629
operand: &mir::Operand<'tcx>,
631630
) -> OperandRef<'tcx, Bx::Value> {
632-
debug!("codegen_operand(operand={:?})", operand);
633-
634631
match *operand {
635632
mir::Operand::Copy(ref place) | mir::Operand::Move(ref place) => {
636633
self.codegen_consume(bx, place.as_ref())

Diff for: compiler/rustc_codegen_ssa/src/mir/rvalue.rs

+3
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,9 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
129129
let variant_dest = dest.project_downcast(bx, variant_index);
130130
(variant_index, variant_dest, active_field_index)
131131
}
132+
mir::AggregateKind::Coroutine(_, _) => {
133+
(FIRST_VARIANT, dest.project_downcast(bx, FIRST_VARIANT), None)
134+
}
132135
_ => (FIRST_VARIANT, dest, None),
133136
};
134137
if active_field_index.is_some() {

Diff for: compiler/rustc_const_eval/src/interpret/step.rs

+3
Original file line numberDiff line numberDiff line change
@@ -294,6 +294,9 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
294294
let variant_dest = self.project_downcast(dest, variant_index)?;
295295
(variant_index, variant_dest, active_field_index)
296296
}
297+
mir::AggregateKind::Coroutine(_def_id, _args) => {
298+
(FIRST_VARIANT, self.project_downcast(dest, FIRST_VARIANT)?, None)
299+
}
297300
mir::AggregateKind::RawPtr(..) => {
298301
// Pointers don't have "fields" in the normal sense, so the
299302
// projection-based code below would either fail in projection

Diff for: compiler/rustc_middle/src/mir/mod.rs

+5
Original file line numberDiff line numberDiff line change
@@ -443,6 +443,9 @@ pub struct Body<'tcx> {
443443
/// If `-Cinstrument-coverage` is not active, or if an individual function
444444
/// is not eligible for coverage, then this should always be `None`.
445445
pub function_coverage_info: Option<Box<coverage::FunctionCoverageInfo>>,
446+
447+
/// Coroutine local-upvar map
448+
pub local_upvar_map: IndexVec<FieldIdx, Option<Local>>,
446449
}
447450

448451
impl<'tcx> Body<'tcx> {
@@ -486,6 +489,7 @@ impl<'tcx> Body<'tcx> {
486489
tainted_by_errors,
487490
coverage_info_hi: None,
488491
function_coverage_info: None,
492+
local_upvar_map: IndexVec::new(),
489493
};
490494
body.is_polymorphic = body.has_non_region_param();
491495
body
@@ -517,6 +521,7 @@ impl<'tcx> Body<'tcx> {
517521
tainted_by_errors: None,
518522
coverage_info_hi: None,
519523
function_coverage_info: None,
524+
local_upvar_map: IndexVec::new(),
520525
};
521526
body.is_polymorphic = body.has_non_region_param();
522527
body

Diff for: compiler/rustc_middle/src/mir/patch.rs

+4
Original file line numberDiff line numberDiff line change
@@ -155,10 +155,14 @@ impl<'tcx> MirPatch<'tcx> {
155155
ty: Ty<'tcx>,
156156
span: Span,
157157
local_info: LocalInfo<'tcx>,
158+
immutable: bool,
158159
) -> Local {
159160
let index = self.next_local;
160161
self.next_local += 1;
161162
let mut new_decl = LocalDecl::new(ty, span);
163+
if immutable {
164+
new_decl = new_decl.immutable();
165+
}
162166
**new_decl.local_info.as_mut().assert_crate_local() = local_info;
163167
self.new_locals.push(new_decl);
164168
Local::new(index)

Diff for: compiler/rustc_middle/src/ty/layout.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -907,9 +907,10 @@ where
907907
),
908908
Variants::Multiple { tag, tag_field, .. } => {
909909
if i == tag_field {
910-
return TyMaybeWithLayout::TyAndLayout(tag_layout(tag));
910+
TyMaybeWithLayout::TyAndLayout(tag_layout(tag))
911+
} else {
912+
TyMaybeWithLayout::Ty(args.as_coroutine().upvar_tys()[i])
911913
}
912-
TyMaybeWithLayout::Ty(args.as_coroutine().prefix_tys()[i])
913914
}
914915
},
915916

Diff for: compiler/rustc_middle/src/ty/sty.rs

-7
Original file line numberDiff line numberDiff line change
@@ -147,13 +147,6 @@ impl<'tcx> ty::CoroutineArgs<TyCtxt<'tcx>> {
147147
})
148148
})
149149
}
150-
151-
/// This is the types of the fields of a coroutine which are not stored in a
152-
/// variant.
153-
#[inline]
154-
fn prefix_tys(self) -> &'tcx List<Ty<'tcx>> {
155-
self.upvar_tys()
156-
}
157150
}
158151

159152
#[derive(Debug, Copy, Clone, HashStable, TypeFoldable, TypeVisitable)]

0 commit comments

Comments
 (0)