]> git.proxmox.com Git - rustc.git/blob - src/librustc_mir/transform/generator.rs
New upstream version 1.44.1+dfsg1
[rustc.git] / src / librustc_mir / transform / generator.rs
1 //! This is the implementation of the pass which transforms generators into state machines.
2 //!
3 //! MIR generation for generators creates a function which has a self argument which
4 //! passes by value. This argument is effectively a generator type which only contains upvars and
5 //! is only used for this argument inside the MIR for the generator.
6 //! It is passed by value to enable upvars to be moved out of it. Drop elaboration runs on that
7 //! MIR before this pass and creates drop flags for MIR locals.
8 //! It will also drop the generator argument (which only consists of upvars) if any of the upvars
9 //! are moved out of. This pass elaborates the drops of upvars / generator argument in the case
10 //! that none of the upvars were moved out of. This is because we cannot have any drops of this
11 //! generator in the MIR, since it is used to create the drop glue for the generator. We'd get
12 //! infinite recursion otherwise.
13 //!
14 //! This pass creates the implementation for the Generator::resume function and the drop shim
15 //! for the generator based on the MIR input. It converts the generator argument from Self to
16 //! &mut Self adding derefs in the MIR as needed. It computes the final layout of the generator
17 //! struct which looks like this:
18 //! First upvars are stored
19 //! It is followed by the generator state field.
20 //! Then finally the MIR locals which are live across a suspension point are stored.
21 //!
22 //! struct Generator {
23 //! upvars...,
24 //! state: u32,
25 //! mir_locals...,
26 //! }
27 //!
28 //! This pass computes the meaning of the state field and the MIR locals which are live
29 //! across a suspension point. There are however three hardcoded generator states:
30 //! 0 - Generator have not been resumed yet
31 //! 1 - Generator has returned / is completed
32 //! 2 - Generator has been poisoned
33 //!
34 //! It also rewrites `return x` and `yield y` as setting a new generator state and returning
35 //! GeneratorState::Complete(x) and GeneratorState::Yielded(y) respectively.
36 //! MIR locals which are live across a suspension point are moved to the generator struct
37 //! with references to them being updated with references to the generator struct.
38 //!
39 //! The pass creates two functions which have a switch on the generator state giving
40 //! the action to take.
41 //!
42 //! One of them is the implementation of Generator::resume.
43 //! For generators with state 0 (unresumed) it starts the execution of the generator.
44 //! For generators with state 1 (returned) and state 2 (poisoned) it panics.
45 //! Otherwise it continues the execution from the last suspension point.
46 //!
47 //! The other function is the drop glue for the generator.
48 //! For generators with state 0 (unresumed) it drops the upvars of the generator.
49 //! For generators with state 1 (returned) and state 2 (poisoned) it does nothing.
50 //! Otherwise it drops all the values in scope at the last suspension point.
51
52 use crate::dataflow::{self, Analysis};
53 use crate::dataflow::{MaybeBorrowedLocals, MaybeRequiresStorage, MaybeStorageLive};
54 use crate::transform::no_landing_pads::no_landing_pads;
55 use crate::transform::simplify;
56 use crate::transform::{MirPass, MirSource};
57 use crate::util::dump_mir;
58 use crate::util::liveness;
59 use crate::util::storage;
60 use rustc_data_structures::fx::FxHashMap;
61 use rustc_hir as hir;
62 use rustc_hir::def_id::DefId;
63 use rustc_index::bit_set::{BitMatrix, BitSet};
64 use rustc_index::vec::{Idx, IndexVec};
65 use rustc_middle::mir::visit::{MutVisitor, PlaceContext};
66 use rustc_middle::mir::*;
67 use rustc_middle::ty::subst::SubstsRef;
68 use rustc_middle::ty::GeneratorSubsts;
69 use rustc_middle::ty::{self, AdtDef, Ty, TyCtxt};
70 use rustc_target::abi::VariantIdx;
71 use std::borrow::Cow;
72 use std::iter;
73
74 pub struct StateTransform;
75
76 struct RenameLocalVisitor<'tcx> {
77 from: Local,
78 to: Local,
79 tcx: TyCtxt<'tcx>,
80 }
81
82 impl<'tcx> MutVisitor<'tcx> for RenameLocalVisitor<'tcx> {
83 fn tcx(&self) -> TyCtxt<'tcx> {
84 self.tcx
85 }
86
87 fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
88 if *local == self.from {
89 *local = self.to;
90 }
91 }
92 }
93
94 struct DerefArgVisitor<'tcx> {
95 tcx: TyCtxt<'tcx>,
96 }
97
98 impl<'tcx> MutVisitor<'tcx> for DerefArgVisitor<'tcx> {
99 fn tcx(&self) -> TyCtxt<'tcx> {
100 self.tcx
101 }
102
103 fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
104 assert_ne!(*local, SELF_ARG);
105 }
106
107 fn visit_place(&mut self, place: &mut Place<'tcx>, context: PlaceContext, location: Location) {
108 if place.local == SELF_ARG {
109 replace_base(
110 place,
111 Place {
112 local: SELF_ARG,
113 projection: self.tcx().intern_place_elems(&[ProjectionElem::Deref]),
114 },
115 self.tcx,
116 );
117 } else {
118 self.visit_place_base(&mut place.local, context, location);
119
120 for elem in place.projection.iter() {
121 if let PlaceElem::Index(local) = elem {
122 assert_ne!(*local, SELF_ARG);
123 }
124 }
125 }
126 }
127 }
128
129 struct PinArgVisitor<'tcx> {
130 ref_gen_ty: Ty<'tcx>,
131 tcx: TyCtxt<'tcx>,
132 }
133
134 impl<'tcx> MutVisitor<'tcx> for PinArgVisitor<'tcx> {
135 fn tcx(&self) -> TyCtxt<'tcx> {
136 self.tcx
137 }
138
139 fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
140 assert_ne!(*local, SELF_ARG);
141 }
142
143 fn visit_place(&mut self, place: &mut Place<'tcx>, context: PlaceContext, location: Location) {
144 if place.local == SELF_ARG {
145 replace_base(
146 place,
147 Place {
148 local: SELF_ARG,
149 projection: self.tcx().intern_place_elems(&[ProjectionElem::Field(
150 Field::new(0),
151 self.ref_gen_ty,
152 )]),
153 },
154 self.tcx,
155 );
156 } else {
157 self.visit_place_base(&mut place.local, context, location);
158
159 for elem in place.projection.iter() {
160 if let PlaceElem::Index(local) = elem {
161 assert_ne!(*local, SELF_ARG);
162 }
163 }
164 }
165 }
166 }
167
168 fn replace_base<'tcx>(place: &mut Place<'tcx>, new_base: Place<'tcx>, tcx: TyCtxt<'tcx>) {
169 place.local = new_base.local;
170
171 let mut new_projection = new_base.projection.to_vec();
172 new_projection.append(&mut place.projection.to_vec());
173
174 place.projection = tcx.intern_place_elems(&new_projection);
175 }
176
177 const SELF_ARG: Local = Local::from_u32(1);
178
179 /// Generator has not been resumed yet.
180 const UNRESUMED: usize = GeneratorSubsts::UNRESUMED;
181 /// Generator has returned / is completed.
182 const RETURNED: usize = GeneratorSubsts::RETURNED;
183 /// Generator has panicked and is poisoned.
184 const POISONED: usize = GeneratorSubsts::POISONED;
185
186 /// A `yield` point in the generator.
187 struct SuspensionPoint<'tcx> {
188 /// State discriminant used when suspending or resuming at this point.
189 state: usize,
190 /// The block to jump to after resumption.
191 resume: BasicBlock,
192 /// Where to move the resume argument after resumption.
193 resume_arg: Place<'tcx>,
194 /// Which block to jump to if the generator is dropped in this state.
195 drop: Option<BasicBlock>,
196 /// Set of locals that have live storage while at this suspension point.
197 storage_liveness: liveness::LiveVarSet,
198 }
199
200 struct TransformVisitor<'tcx> {
201 tcx: TyCtxt<'tcx>,
202 state_adt_ref: &'tcx AdtDef,
203 state_substs: SubstsRef<'tcx>,
204
205 // The type of the discriminant in the generator struct
206 discr_ty: Ty<'tcx>,
207
208 // Mapping from Local to (type of local, generator struct index)
209 // FIXME(eddyb) This should use `IndexVec<Local, Option<_>>`.
210 remap: FxHashMap<Local, (Ty<'tcx>, VariantIdx, usize)>,
211
212 // A map from a suspension point in a block to the locals which have live storage at that point
213 // FIXME(eddyb) This should use `IndexVec<BasicBlock, Option<_>>`.
214 storage_liveness: FxHashMap<BasicBlock, liveness::LiveVarSet>,
215
216 // A list of suspension points, generated during the transform
217 suspension_points: Vec<SuspensionPoint<'tcx>>,
218
219 // The set of locals that have no `StorageLive`/`StorageDead` annotations.
220 always_live_locals: storage::AlwaysLiveLocals,
221
222 // The original RETURN_PLACE local
223 new_ret_local: Local,
224 }
225
226 impl TransformVisitor<'tcx> {
227 // Make a GeneratorState rvalue
228 fn make_state(&self, idx: VariantIdx, val: Operand<'tcx>) -> Rvalue<'tcx> {
229 let adt = AggregateKind::Adt(self.state_adt_ref, idx, self.state_substs, None, None);
230 Rvalue::Aggregate(box adt, vec![val])
231 }
232
233 // Create a Place referencing a generator struct field
234 fn make_field(&self, variant_index: VariantIdx, idx: usize, ty: Ty<'tcx>) -> Place<'tcx> {
235 let self_place = Place::from(SELF_ARG);
236 let base = self.tcx.mk_place_downcast_unnamed(self_place, variant_index);
237 let mut projection = base.projection.to_vec();
238 projection.push(ProjectionElem::Field(Field::new(idx), ty));
239
240 Place { local: base.local, projection: self.tcx.intern_place_elems(&projection) }
241 }
242
243 // Create a statement which changes the discriminant
244 fn set_discr(&self, state_disc: VariantIdx, source_info: SourceInfo) -> Statement<'tcx> {
245 let self_place = Place::from(SELF_ARG);
246 Statement {
247 source_info,
248 kind: StatementKind::SetDiscriminant {
249 place: box self_place,
250 variant_index: state_disc,
251 },
252 }
253 }
254
255 // Create a statement which reads the discriminant into a temporary
256 fn get_discr(&self, body: &mut Body<'tcx>) -> (Statement<'tcx>, Place<'tcx>) {
257 let temp_decl = LocalDecl::new_internal(self.tcx.types.isize, body.span);
258 let local_decls_len = body.local_decls.push(temp_decl);
259 let temp = Place::from(local_decls_len);
260
261 let self_place = Place::from(SELF_ARG);
262 let assign = Statement {
263 source_info: source_info(body),
264 kind: StatementKind::Assign(box (temp, Rvalue::Discriminant(self_place))),
265 };
266 (assign, temp)
267 }
268 }
269
270 impl MutVisitor<'tcx> for TransformVisitor<'tcx> {
271 fn tcx(&self) -> TyCtxt<'tcx> {
272 self.tcx
273 }
274
275 fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
276 assert_eq!(self.remap.get(local), None);
277 }
278
279 fn visit_place(
280 &mut self,
281 place: &mut Place<'tcx>,
282 _context: PlaceContext,
283 _location: Location,
284 ) {
285 // Replace an Local in the remap with a generator struct access
286 if let Some(&(ty, variant_index, idx)) = self.remap.get(&place.local) {
287 replace_base(place, self.make_field(variant_index, idx, ty), self.tcx);
288 }
289 }
290
291 fn visit_basic_block_data(&mut self, block: BasicBlock, data: &mut BasicBlockData<'tcx>) {
292 // Remove StorageLive and StorageDead statements for remapped locals
293 data.retain_statements(|s| match s.kind {
294 StatementKind::StorageLive(l) | StatementKind::StorageDead(l) => {
295 !self.remap.contains_key(&l)
296 }
297 _ => true,
298 });
299
300 let ret_val = match data.terminator().kind {
301 TerminatorKind::Return => Some((
302 VariantIdx::new(1),
303 None,
304 Operand::Move(Place::from(self.new_ret_local)),
305 None,
306 )),
307 TerminatorKind::Yield { ref value, resume, resume_arg, drop } => {
308 Some((VariantIdx::new(0), Some((resume, resume_arg)), value.clone(), drop))
309 }
310 _ => None,
311 };
312
313 if let Some((state_idx, resume, v, drop)) = ret_val {
314 let source_info = data.terminator().source_info;
315 // We must assign the value first in case it gets declared dead below
316 data.statements.push(Statement {
317 source_info,
318 kind: StatementKind::Assign(box (
319 Place::return_place(),
320 self.make_state(state_idx, v),
321 )),
322 });
323 let state = if let Some((resume, resume_arg)) = resume {
324 // Yield
325 let state = 3 + self.suspension_points.len();
326
327 // The resume arg target location might itself be remapped if its base local is
328 // live across a yield.
329 let resume_arg =
330 if let Some(&(ty, variant, idx)) = self.remap.get(&resume_arg.local) {
331 self.make_field(variant, idx, ty)
332 } else {
333 resume_arg
334 };
335
336 self.suspension_points.push(SuspensionPoint {
337 state,
338 resume,
339 resume_arg,
340 drop,
341 storage_liveness: self.storage_liveness.get(&block).unwrap().clone(),
342 });
343
344 VariantIdx::new(state)
345 } else {
346 // Return
347 VariantIdx::new(RETURNED) // state for returned
348 };
349 data.statements.push(self.set_discr(state, source_info));
350 data.terminator_mut().kind = TerminatorKind::Return;
351 }
352
353 self.super_basic_block_data(block, data);
354 }
355 }
356
357 fn make_generator_state_argument_indirect<'tcx>(tcx: TyCtxt<'tcx>, body: &mut BodyAndCache<'tcx>) {
358 let gen_ty = body.local_decls.raw[1].ty;
359
360 let ref_gen_ty =
361 tcx.mk_ref(tcx.lifetimes.re_erased, ty::TypeAndMut { ty: gen_ty, mutbl: Mutability::Mut });
362
363 // Replace the by value generator argument
364 body.local_decls.raw[1].ty = ref_gen_ty;
365
366 // Add a deref to accesses of the generator state
367 DerefArgVisitor { tcx }.visit_body(body);
368 }
369
370 fn make_generator_state_argument_pinned<'tcx>(tcx: TyCtxt<'tcx>, body: &mut BodyAndCache<'tcx>) {
371 let ref_gen_ty = body.local_decls.raw[1].ty;
372
373 let pin_did = tcx.lang_items().pin_type().unwrap();
374 let pin_adt_ref = tcx.adt_def(pin_did);
375 let substs = tcx.intern_substs(&[ref_gen_ty.into()]);
376 let pin_ref_gen_ty = tcx.mk_adt(pin_adt_ref, substs);
377
378 // Replace the by ref generator argument
379 body.local_decls.raw[1].ty = pin_ref_gen_ty;
380
381 // Add the Pin field access to accesses of the generator state
382 PinArgVisitor { ref_gen_ty, tcx }.visit_body(body);
383 }
384
385 /// Allocates a new local and replaces all references of `local` with it. Returns the new local.
386 ///
387 /// `local` will be changed to a new local decl with type `ty`.
388 ///
389 /// Note that the new local will be uninitialized. It is the caller's responsibility to assign some
390 /// valid value to it before its first use.
391 fn replace_local<'tcx>(
392 local: Local,
393 ty: Ty<'tcx>,
394 body: &mut BodyAndCache<'tcx>,
395 tcx: TyCtxt<'tcx>,
396 ) -> Local {
397 let source_info = source_info(body);
398 let new_decl = LocalDecl {
399 mutability: Mutability::Mut,
400 ty,
401 user_ty: UserTypeProjections::none(),
402 source_info,
403 internal: false,
404 is_block_tail: None,
405 local_info: LocalInfo::Other,
406 };
407 let new_local = Local::new(body.local_decls.len());
408 body.local_decls.push(new_decl);
409 body.local_decls.swap(local, new_local);
410
411 RenameLocalVisitor { from: local, to: new_local, tcx }.visit_body(body);
412
413 new_local
414 }
415
416 struct LivenessInfo {
417 /// Which locals are live across any suspension point.
418 ///
419 /// GeneratorSavedLocal is indexed in terms of the elements in this set;
420 /// i.e. GeneratorSavedLocal::new(1) corresponds to the second local
421 /// included in this set.
422 live_locals: liveness::LiveVarSet,
423
424 /// The set of saved locals live at each suspension point.
425 live_locals_at_suspension_points: Vec<BitSet<GeneratorSavedLocal>>,
426
427 /// For every saved local, the set of other saved locals that are
428 /// storage-live at the same time as this local. We cannot overlap locals in
429 /// the layout which have conflicting storage.
430 storage_conflicts: BitMatrix<GeneratorSavedLocal, GeneratorSavedLocal>,
431
432 /// For every suspending block, the locals which are storage-live across
433 /// that suspension point.
434 storage_liveness: FxHashMap<BasicBlock, liveness::LiveVarSet>,
435 }
436
437 fn locals_live_across_suspend_points(
438 tcx: TyCtxt<'tcx>,
439 body: ReadOnlyBodyAndCache<'_, 'tcx>,
440 source: MirSource<'tcx>,
441 always_live_locals: &storage::AlwaysLiveLocals,
442 movable: bool,
443 ) -> LivenessInfo {
444 let def_id = source.def_id();
445 let body_ref: &Body<'_> = &body;
446
447 // Calculate when MIR locals have live storage. This gives us an upper bound of their
448 // lifetimes.
449 let mut storage_live = MaybeStorageLive::new(always_live_locals.clone())
450 .into_engine(tcx, body_ref, def_id)
451 .iterate_to_fixpoint()
452 .into_results_cursor(body_ref);
453
454 // Calculate the MIR locals which have been previously
455 // borrowed (even if they are still active).
456 let borrowed_locals_results =
457 MaybeBorrowedLocals::all_borrows().into_engine(tcx, body_ref, def_id).iterate_to_fixpoint();
458
459 let mut borrowed_locals_cursor =
460 dataflow::ResultsCursor::new(body_ref, &borrowed_locals_results);
461
462 // Calculate the MIR locals that we actually need to keep storage around
463 // for.
464 let requires_storage_results = MaybeRequiresStorage::new(body, &borrowed_locals_results)
465 .into_engine(tcx, body_ref, def_id)
466 .iterate_to_fixpoint();
467 let mut requires_storage_cursor =
468 dataflow::ResultsCursor::new(body_ref, &requires_storage_results);
469
470 // Calculate the liveness of MIR locals ignoring borrows.
471 let mut live_locals = liveness::LiveVarSet::new_empty(body.local_decls.len());
472 let mut liveness = liveness::liveness_of_locals(body);
473 liveness::dump_mir(tcx, "generator_liveness", source, body_ref, &liveness);
474
475 let mut storage_liveness_map = FxHashMap::default();
476 let mut live_locals_at_suspension_points = Vec::new();
477
478 for (block, data) in body.basic_blocks().iter_enumerated() {
479 if let TerminatorKind::Yield { .. } = data.terminator().kind {
480 let loc = Location { block, statement_index: data.statements.len() };
481
482 if !movable {
483 // The `liveness` variable contains the liveness of MIR locals ignoring borrows.
484 // This is correct for movable generators since borrows cannot live across
485 // suspension points. However for immovable generators we need to account for
486 // borrows, so we conseratively assume that all borrowed locals are live until
487 // we find a StorageDead statement referencing the locals.
488 // To do this we just union our `liveness` result with `borrowed_locals`, which
489 // contains all the locals which has been borrowed before this suspension point.
490 // If a borrow is converted to a raw reference, we must also assume that it lives
491 // forever. Note that the final liveness is still bounded by the storage liveness
492 // of the local, which happens using the `intersect` operation below.
493 borrowed_locals_cursor.seek_before(loc);
494 liveness.outs[block].union(borrowed_locals_cursor.get());
495 }
496
497 storage_live.seek_before(loc);
498 let mut storage_liveness = storage_live.get().clone();
499
500 // Later passes handle the generator's `self` argument separately.
501 storage_liveness.remove(SELF_ARG);
502
503 // Store the storage liveness for later use so we can restore the state
504 // after a suspension point
505 storage_liveness_map.insert(block, storage_liveness);
506
507 requires_storage_cursor.seek_before(loc);
508 let storage_required = requires_storage_cursor.get().clone();
509
510 // Locals live are live at this point only if they are used across
511 // suspension points (the `liveness` variable)
512 // and their storage is required (the `storage_required` variable)
513 let mut live_locals_here = storage_required;
514 live_locals_here.intersect(&liveness.outs[block]);
515
516 // The generator argument is ignored.
517 live_locals_here.remove(SELF_ARG);
518
519 debug!("loc = {:?}, live_locals_here = {:?}", loc, live_locals_here);
520
521 // Add the locals live at this suspension point to the set of locals which live across
522 // any suspension points
523 live_locals.union(&live_locals_here);
524
525 live_locals_at_suspension_points.push(live_locals_here);
526 }
527 }
528 debug!("live_locals = {:?}", live_locals);
529
530 // Renumber our liveness_map bitsets to include only the locals we are
531 // saving.
532 let live_locals_at_suspension_points = live_locals_at_suspension_points
533 .iter()
534 .map(|live_here| renumber_bitset(&live_here, &live_locals))
535 .collect();
536
537 let storage_conflicts = compute_storage_conflicts(
538 body_ref,
539 &live_locals,
540 always_live_locals.clone(),
541 requires_storage_results,
542 );
543
544 LivenessInfo {
545 live_locals,
546 live_locals_at_suspension_points,
547 storage_conflicts,
548 storage_liveness: storage_liveness_map,
549 }
550 }
551
552 /// Renumbers the items present in `stored_locals` and applies the renumbering
553 /// to 'input`.
554 ///
555 /// For example, if `stored_locals = [1, 3, 5]`, this would be renumbered to
556 /// `[0, 1, 2]`. Thus, if `input = [3, 5]` we would return `[1, 2]`.
557 fn renumber_bitset(
558 input: &BitSet<Local>,
559 stored_locals: &liveness::LiveVarSet,
560 ) -> BitSet<GeneratorSavedLocal> {
561 assert!(stored_locals.superset(&input), "{:?} not a superset of {:?}", stored_locals, input);
562 let mut out = BitSet::new_empty(stored_locals.count());
563 for (idx, local) in stored_locals.iter().enumerate() {
564 let saved_local = GeneratorSavedLocal::from(idx);
565 if input.contains(local) {
566 out.insert(saved_local);
567 }
568 }
569 debug!("renumber_bitset({:?}, {:?}) => {:?}", input, stored_locals, out);
570 out
571 }
572
573 /// For every saved local, looks for which locals are StorageLive at the same
574 /// time. Generates a bitset for every local of all the other locals that may be
575 /// StorageLive simultaneously with that local. This is used in the layout
576 /// computation; see `GeneratorLayout` for more.
577 fn compute_storage_conflicts(
578 body: &'mir Body<'tcx>,
579 stored_locals: &liveness::LiveVarSet,
580 always_live_locals: storage::AlwaysLiveLocals,
581 requires_storage: dataflow::Results<'tcx, MaybeRequiresStorage<'mir, 'tcx>>,
582 ) -> BitMatrix<GeneratorSavedLocal, GeneratorSavedLocal> {
583 assert_eq!(body.local_decls.len(), stored_locals.domain_size());
584
585 debug!("compute_storage_conflicts({:?})", body.span);
586 debug!("always_live = {:?}", always_live_locals);
587
588 // Locals that are always live or ones that need to be stored across
589 // suspension points are not eligible for overlap.
590 let mut ineligible_locals = always_live_locals.into_inner();
591 ineligible_locals.intersect(stored_locals);
592
593 // Compute the storage conflicts for all eligible locals.
594 let mut visitor = StorageConflictVisitor {
595 body,
596 stored_locals: &stored_locals,
597 local_conflicts: BitMatrix::from_row_n(&ineligible_locals, body.local_decls.len()),
598 };
599
600 // Visit only reachable basic blocks. The exact order is not important.
601 let reachable_blocks = traversal::preorder(body).map(|(bb, _)| bb);
602 requires_storage.visit_with(body, reachable_blocks, &mut visitor);
603
604 let local_conflicts = visitor.local_conflicts;
605
606 // Compress the matrix using only stored locals (Local -> GeneratorSavedLocal).
607 //
608 // NOTE: Today we store a full conflict bitset for every local. Technically
609 // this is twice as many bits as we need, since the relation is symmetric.
610 // However, in practice these bitsets are not usually large. The layout code
611 // also needs to keep track of how many conflicts each local has, so it's
612 // simpler to keep it this way for now.
613 let mut storage_conflicts = BitMatrix::new(stored_locals.count(), stored_locals.count());
614 for (idx_a, local_a) in stored_locals.iter().enumerate() {
615 let saved_local_a = GeneratorSavedLocal::new(idx_a);
616 if ineligible_locals.contains(local_a) {
617 // Conflicts with everything.
618 storage_conflicts.insert_all_into_row(saved_local_a);
619 } else {
620 // Keep overlap information only for stored locals.
621 for (idx_b, local_b) in stored_locals.iter().enumerate() {
622 let saved_local_b = GeneratorSavedLocal::new(idx_b);
623 if local_conflicts.contains(local_a, local_b) {
624 storage_conflicts.insert(saved_local_a, saved_local_b);
625 }
626 }
627 }
628 }
629 storage_conflicts
630 }
631
632 struct StorageConflictVisitor<'mir, 'tcx, 's> {
633 body: &'mir Body<'tcx>,
634 stored_locals: &'s liveness::LiveVarSet,
635 // FIXME(tmandry): Consider using sparse bitsets here once we have good
636 // benchmarks for generators.
637 local_conflicts: BitMatrix<Local, Local>,
638 }
639
640 impl dataflow::ResultsVisitor<'mir, 'tcx> for StorageConflictVisitor<'mir, 'tcx, '_> {
641 type FlowState = BitSet<Local>;
642
643 fn visit_statement(
644 &mut self,
645 state: &Self::FlowState,
646 _statement: &'mir Statement<'tcx>,
647 loc: Location,
648 ) {
649 self.apply_state(state, loc);
650 }
651
652 fn visit_terminator(
653 &mut self,
654 state: &Self::FlowState,
655 _terminator: &'mir Terminator<'tcx>,
656 loc: Location,
657 ) {
658 self.apply_state(state, loc);
659 }
660 }
661
662 impl<'body, 'tcx, 's> StorageConflictVisitor<'body, 'tcx, 's> {
663 fn apply_state(&mut self, flow_state: &BitSet<Local>, loc: Location) {
664 // Ignore unreachable blocks.
665 if self.body.basic_blocks()[loc.block].terminator().kind == TerminatorKind::Unreachable {
666 return;
667 }
668
669 let mut eligible_storage_live = flow_state.clone();
670 eligible_storage_live.intersect(&self.stored_locals);
671
672 for local in eligible_storage_live.iter() {
673 self.local_conflicts.union_row_with(&eligible_storage_live, local);
674 }
675
676 if eligible_storage_live.count() > 1 {
677 trace!("at {:?}, eligible_storage_live={:?}", loc, eligible_storage_live);
678 }
679 }
680 }
681
682 fn compute_layout<'tcx>(
683 tcx: TyCtxt<'tcx>,
684 source: MirSource<'tcx>,
685 upvars: &Vec<Ty<'tcx>>,
686 interior: Ty<'tcx>,
687 always_live_locals: &storage::AlwaysLiveLocals,
688 movable: bool,
689 body: &mut BodyAndCache<'tcx>,
690 ) -> (
691 FxHashMap<Local, (Ty<'tcx>, VariantIdx, usize)>,
692 GeneratorLayout<'tcx>,
693 FxHashMap<BasicBlock, liveness::LiveVarSet>,
694 ) {
695 // Use a liveness analysis to compute locals which are live across a suspension point
696 let LivenessInfo {
697 live_locals,
698 live_locals_at_suspension_points,
699 storage_conflicts,
700 storage_liveness,
701 } = locals_live_across_suspend_points(
702 tcx,
703 read_only!(body),
704 source,
705 always_live_locals,
706 movable,
707 );
708
709 // Erase regions from the types passed in from typeck so we can compare them with
710 // MIR types
711 let allowed_upvars = tcx.erase_regions(upvars);
712 let allowed = match interior.kind {
713 ty::GeneratorWitness(s) => tcx.erase_late_bound_regions(&s),
714 _ => bug!(),
715 };
716
717 let param_env = tcx.param_env(source.def_id());
718
719 for (local, decl) in body.local_decls.iter_enumerated() {
720 // Ignore locals which are internal or not live
721 if !live_locals.contains(local) || decl.internal {
722 continue;
723 }
724 let decl_ty = tcx.normalize_erasing_regions(param_env, decl.ty);
725
726 // Sanity check that typeck knows about the type of locals which are
727 // live across a suspension point
728 if !allowed.contains(&decl_ty) && !allowed_upvars.contains(&decl_ty) {
729 span_bug!(
730 body.span,
731 "Broken MIR: generator contains type {} in MIR, \
732 but typeck only knows about {}",
733 decl.ty,
734 interior
735 );
736 }
737 }
738
739 // Gather live local types and their indices.
740 let mut locals = IndexVec::<GeneratorSavedLocal, _>::new();
741 let mut tys = IndexVec::<GeneratorSavedLocal, _>::new();
742 for (idx, local) in live_locals.iter().enumerate() {
743 locals.push(local);
744 tys.push(body.local_decls[local].ty);
745 debug!("generator saved local {:?} => {:?}", GeneratorSavedLocal::from(idx), local);
746 }
747
748 // Leave empty variants for the UNRESUMED, RETURNED, and POISONED states.
749 const RESERVED_VARIANTS: usize = 3;
750
751 // Build the generator variant field list.
752 // Create a map from local indices to generator struct indices.
753 let mut variant_fields: IndexVec<VariantIdx, IndexVec<Field, GeneratorSavedLocal>> =
754 iter::repeat(IndexVec::new()).take(RESERVED_VARIANTS).collect();
755 let mut remap = FxHashMap::default();
756 for (suspension_point_idx, live_locals) in live_locals_at_suspension_points.iter().enumerate() {
757 let variant_index = VariantIdx::from(RESERVED_VARIANTS + suspension_point_idx);
758 let mut fields = IndexVec::new();
759 for (idx, saved_local) in live_locals.iter().enumerate() {
760 fields.push(saved_local);
761 // Note that if a field is included in multiple variants, we will
762 // just use the first one here. That's fine; fields do not move
763 // around inside generators, so it doesn't matter which variant
764 // index we access them by.
765 remap.entry(locals[saved_local]).or_insert((tys[saved_local], variant_index, idx));
766 }
767 variant_fields.push(fields);
768 }
769 debug!("generator variant_fields = {:?}", variant_fields);
770 debug!("generator storage_conflicts = {:#?}", storage_conflicts);
771
772 let layout = GeneratorLayout { field_tys: tys, variant_fields, storage_conflicts };
773
774 (remap, layout, storage_liveness)
775 }
776
777 /// Replaces the entry point of `body` with a block that switches on the generator discriminant and
778 /// dispatches to blocks according to `cases`.
779 ///
780 /// After this function, the former entry point of the function will be bb1.
781 fn insert_switch<'tcx>(
782 body: &mut BodyAndCache<'tcx>,
783 cases: Vec<(usize, BasicBlock)>,
784 transform: &TransformVisitor<'tcx>,
785 default: TerminatorKind<'tcx>,
786 ) {
787 let default_block = insert_term_block(body, default);
788 let (assign, discr) = transform.get_discr(body);
789 let switch = TerminatorKind::SwitchInt {
790 discr: Operand::Move(discr),
791 switch_ty: transform.discr_ty,
792 values: Cow::from(cases.iter().map(|&(i, _)| i as u128).collect::<Vec<_>>()),
793 targets: cases.iter().map(|&(_, d)| d).chain(iter::once(default_block)).collect(),
794 };
795
796 let source_info = source_info(body);
797 body.basic_blocks_mut().raw.insert(
798 0,
799 BasicBlockData {
800 statements: vec![assign],
801 terminator: Some(Terminator { source_info, kind: switch }),
802 is_cleanup: false,
803 },
804 );
805
806 let blocks = body.basic_blocks_mut().iter_mut();
807
808 for target in blocks.flat_map(|b| b.terminator_mut().successors_mut()) {
809 *target = BasicBlock::new(target.index() + 1);
810 }
811 }
812
813 fn elaborate_generator_drops<'tcx>(
814 tcx: TyCtxt<'tcx>,
815 def_id: DefId,
816 body: &mut BodyAndCache<'tcx>,
817 ) {
818 use crate::shim::DropShimElaborator;
819 use crate::util::elaborate_drops::{elaborate_drop, Unwind};
820 use crate::util::patch::MirPatch;
821
822 // Note that `elaborate_drops` only drops the upvars of a generator, and
823 // this is ok because `open_drop` can only be reached within that own
824 // generator's resume function.
825
826 let param_env = tcx.param_env(def_id);
827
828 let mut elaborator = DropShimElaborator { body, patch: MirPatch::new(body), tcx, param_env };
829
830 for (block, block_data) in body.basic_blocks().iter_enumerated() {
831 let (target, unwind, source_info) = match block_data.terminator() {
832 Terminator { source_info, kind: TerminatorKind::Drop { location, target, unwind } } => {
833 if let Some(local) = location.as_local() {
834 if local == SELF_ARG {
835 (target, unwind, source_info)
836 } else {
837 continue;
838 }
839 } else {
840 continue;
841 }
842 }
843 _ => continue,
844 };
845 let unwind = if block_data.is_cleanup {
846 Unwind::InCleanup
847 } else {
848 Unwind::To(unwind.unwrap_or_else(|| elaborator.patch.resume_block()))
849 };
850 elaborate_drop(
851 &mut elaborator,
852 *source_info,
853 Place::from(SELF_ARG),
854 (),
855 *target,
856 unwind,
857 block,
858 );
859 }
860 elaborator.patch.apply(body);
861 }
862
863 fn create_generator_drop_shim<'tcx>(
864 tcx: TyCtxt<'tcx>,
865 transform: &TransformVisitor<'tcx>,
866 source: MirSource<'tcx>,
867 gen_ty: Ty<'tcx>,
868 body: &mut BodyAndCache<'tcx>,
869 drop_clean: BasicBlock,
870 ) -> BodyAndCache<'tcx> {
871 let mut body = body.clone();
872 body.arg_count = 1; // make sure the resume argument is not included here
873
874 let source_info = source_info(&body);
875
876 let mut cases = create_cases(&mut body, transform, Operation::Drop);
877
878 cases.insert(0, (UNRESUMED, drop_clean));
879
880 // The returned state and the poisoned state fall through to the default
881 // case which is just to return
882
883 insert_switch(&mut body, cases, &transform, TerminatorKind::Return);
884
885 for block in body.basic_blocks_mut() {
886 let kind = &mut block.terminator_mut().kind;
887 if let TerminatorKind::GeneratorDrop = *kind {
888 *kind = TerminatorKind::Return;
889 }
890 }
891
892 // Replace the return variable
893 body.local_decls[RETURN_PLACE] = LocalDecl {
894 mutability: Mutability::Mut,
895 ty: tcx.mk_unit(),
896 user_ty: UserTypeProjections::none(),
897 source_info,
898 internal: false,
899 is_block_tail: None,
900 local_info: LocalInfo::Other,
901 };
902
903 make_generator_state_argument_indirect(tcx, &mut body);
904
905 // Change the generator argument from &mut to *mut
906 body.local_decls[SELF_ARG] = LocalDecl {
907 mutability: Mutability::Mut,
908 ty: tcx.mk_ptr(ty::TypeAndMut { ty: gen_ty, mutbl: hir::Mutability::Mut }),
909 user_ty: UserTypeProjections::none(),
910 source_info,
911 internal: false,
912 is_block_tail: None,
913 local_info: LocalInfo::Other,
914 };
915 if tcx.sess.opts.debugging_opts.mir_emit_retag {
916 // Alias tracking must know we changed the type
917 body.basic_blocks_mut()[START_BLOCK].statements.insert(
918 0,
919 Statement {
920 source_info,
921 kind: StatementKind::Retag(RetagKind::Raw, box Place::from(SELF_ARG)),
922 },
923 )
924 }
925
926 no_landing_pads(tcx, &mut body);
927
928 // Make sure we remove dead blocks to remove
929 // unrelated code from the resume part of the function
930 simplify::remove_dead_blocks(&mut body);
931
932 dump_mir(tcx, None, "generator_drop", &0, source, &body, |_, _| Ok(()));
933
934 body
935 }
936
937 fn insert_term_block<'tcx>(
938 body: &mut BodyAndCache<'tcx>,
939 kind: TerminatorKind<'tcx>,
940 ) -> BasicBlock {
941 let term_block = BasicBlock::new(body.basic_blocks().len());
942 let source_info = source_info(body);
943 body.basic_blocks_mut().push(BasicBlockData {
944 statements: Vec::new(),
945 terminator: Some(Terminator { source_info, kind }),
946 is_cleanup: false,
947 });
948 term_block
949 }
950
951 fn insert_panic_block<'tcx>(
952 tcx: TyCtxt<'tcx>,
953 body: &mut BodyAndCache<'tcx>,
954 message: AssertMessage<'tcx>,
955 ) -> BasicBlock {
956 let assert_block = BasicBlock::new(body.basic_blocks().len());
957 let term = TerminatorKind::Assert {
958 cond: Operand::Constant(box Constant {
959 span: body.span,
960 user_ty: None,
961 literal: ty::Const::from_bool(tcx, false),
962 }),
963 expected: true,
964 msg: message,
965 target: assert_block,
966 cleanup: None,
967 };
968
969 let source_info = source_info(body);
970 body.basic_blocks_mut().push(BasicBlockData {
971 statements: Vec::new(),
972 terminator: Some(Terminator { source_info, kind: term }),
973 is_cleanup: false,
974 });
975
976 assert_block
977 }
978
979 fn can_return<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>) -> bool {
980 // Returning from a function with an uninhabited return type is undefined behavior.
981 if body.return_ty().conservative_is_privately_uninhabited(tcx) {
982 return false;
983 }
984
985 // If there's a return terminator the function may return.
986 for block in body.basic_blocks() {
987 if let TerminatorKind::Return = block.terminator().kind {
988 return true;
989 }
990 }
991
992 // Otherwise the function can't return.
993 false
994 }
995
996 fn can_unwind<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>) -> bool {
997 // Nothing can unwind when landing pads are off.
998 if tcx.sess.no_landing_pads() {
999 return false;
1000 }
1001
1002 // Unwinds can only start at certain terminators.
1003 for block in body.basic_blocks() {
1004 match block.terminator().kind {
1005 // These never unwind.
1006 TerminatorKind::Goto { .. }
1007 | TerminatorKind::SwitchInt { .. }
1008 | TerminatorKind::Abort
1009 | TerminatorKind::Return
1010 | TerminatorKind::Unreachable
1011 | TerminatorKind::GeneratorDrop
1012 | TerminatorKind::FalseEdges { .. }
1013 | TerminatorKind::FalseUnwind { .. } => {}
1014
1015 // Resume will *continue* unwinding, but if there's no other unwinding terminator it
1016 // will never be reached.
1017 TerminatorKind::Resume => {}
1018
1019 TerminatorKind::Yield { .. } => {
1020 unreachable!("`can_unwind` called before generator transform")
1021 }
1022
1023 // These may unwind.
1024 TerminatorKind::Drop { .. }
1025 | TerminatorKind::DropAndReplace { .. }
1026 | TerminatorKind::Call { .. }
1027 | TerminatorKind::Assert { .. } => return true,
1028 }
1029 }
1030
1031 // If we didn't find an unwinding terminator, the function cannot unwind.
1032 false
1033 }
1034
1035 fn create_generator_resume_function<'tcx>(
1036 tcx: TyCtxt<'tcx>,
1037 transform: TransformVisitor<'tcx>,
1038 source: MirSource<'tcx>,
1039 body: &mut BodyAndCache<'tcx>,
1040 can_return: bool,
1041 ) {
1042 let can_unwind = can_unwind(tcx, body);
1043
1044 // Poison the generator when it unwinds
1045 if can_unwind {
1046 let poison_block = BasicBlock::new(body.basic_blocks().len());
1047 let source_info = source_info(body);
1048 body.basic_blocks_mut().push(BasicBlockData {
1049 statements: vec![transform.set_discr(VariantIdx::new(POISONED), source_info)],
1050 terminator: Some(Terminator { source_info, kind: TerminatorKind::Resume }),
1051 is_cleanup: true,
1052 });
1053
1054 for (idx, block) in body.basic_blocks_mut().iter_enumerated_mut() {
1055 let source_info = block.terminator().source_info;
1056
1057 if let TerminatorKind::Resume = block.terminator().kind {
1058 // An existing `Resume` terminator is redirected to jump to our dedicated
1059 // "poisoning block" above.
1060 if idx != poison_block {
1061 *block.terminator_mut() = Terminator {
1062 source_info,
1063 kind: TerminatorKind::Goto { target: poison_block },
1064 };
1065 }
1066 } else if !block.is_cleanup {
1067 // Any terminators that *can* unwind but don't have an unwind target set are also
1068 // pointed at our poisoning block (unless they're part of the cleanup path).
1069 if let Some(unwind @ None) = block.terminator_mut().unwind_mut() {
1070 *unwind = Some(poison_block);
1071 }
1072 }
1073 }
1074 }
1075
1076 let mut cases = create_cases(body, &transform, Operation::Resume);
1077
1078 use rustc_middle::mir::AssertKind::{ResumedAfterPanic, ResumedAfterReturn};
1079
1080 // Jump to the entry point on the unresumed
1081 cases.insert(0, (UNRESUMED, BasicBlock::new(0)));
1082
1083 // Panic when resumed on the returned or poisoned state
1084 let generator_kind = body.generator_kind.unwrap();
1085
1086 if can_unwind {
1087 cases.insert(
1088 1,
1089 (POISONED, insert_panic_block(tcx, body, ResumedAfterPanic(generator_kind))),
1090 );
1091 }
1092
1093 if can_return {
1094 cases.insert(
1095 1,
1096 (RETURNED, insert_panic_block(tcx, body, ResumedAfterReturn(generator_kind))),
1097 );
1098 }
1099
1100 insert_switch(body, cases, &transform, TerminatorKind::Unreachable);
1101
1102 make_generator_state_argument_indirect(tcx, body);
1103 make_generator_state_argument_pinned(tcx, body);
1104
1105 no_landing_pads(tcx, body);
1106
1107 // Make sure we remove dead blocks to remove
1108 // unrelated code from the drop part of the function
1109 simplify::remove_dead_blocks(body);
1110
1111 dump_mir(tcx, None, "generator_resume", &0, source, body, |_, _| Ok(()));
1112 }
1113
1114 fn source_info(body: &Body<'_>) -> SourceInfo {
1115 SourceInfo { span: body.span, scope: OUTERMOST_SOURCE_SCOPE }
1116 }
1117
1118 fn insert_clean_drop(body: &mut BodyAndCache<'_>) -> BasicBlock {
1119 let return_block = insert_term_block(body, TerminatorKind::Return);
1120
1121 // Create a block to destroy an unresumed generators. This can only destroy upvars.
1122 let drop_clean = BasicBlock::new(body.basic_blocks().len());
1123 let term = TerminatorKind::Drop {
1124 location: Place::from(SELF_ARG),
1125 target: return_block,
1126 unwind: None,
1127 };
1128 let source_info = source_info(body);
1129 body.basic_blocks_mut().push(BasicBlockData {
1130 statements: Vec::new(),
1131 terminator: Some(Terminator { source_info, kind: term }),
1132 is_cleanup: false,
1133 });
1134
1135 drop_clean
1136 }
1137
1138 /// An operation that can be performed on a generator.
1139 #[derive(PartialEq, Copy, Clone)]
1140 enum Operation {
1141 Resume,
1142 Drop,
1143 }
1144
1145 impl Operation {
1146 fn target_block(self, point: &SuspensionPoint<'_>) -> Option<BasicBlock> {
1147 match self {
1148 Operation::Resume => Some(point.resume),
1149 Operation::Drop => point.drop,
1150 }
1151 }
1152 }
1153
1154 fn create_cases<'tcx>(
1155 body: &mut BodyAndCache<'tcx>,
1156 transform: &TransformVisitor<'tcx>,
1157 operation: Operation,
1158 ) -> Vec<(usize, BasicBlock)> {
1159 let source_info = source_info(body);
1160
1161 transform
1162 .suspension_points
1163 .iter()
1164 .filter_map(|point| {
1165 // Find the target for this suspension point, if applicable
1166 operation.target_block(point).map(|target| {
1167 let block = BasicBlock::new(body.basic_blocks().len());
1168 let mut statements = Vec::new();
1169
1170 // Create StorageLive instructions for locals with live storage
1171 for i in 0..(body.local_decls.len()) {
1172 if i == 2 {
1173 // The resume argument is live on function entry. Don't insert a
1174 // `StorageLive`, or the following `Assign` will read from uninitialized
1175 // memory.
1176 continue;
1177 }
1178
1179 let l = Local::new(i);
1180 let needs_storage_live = point.storage_liveness.contains(l)
1181 && !transform.remap.contains_key(&l)
1182 && !transform.always_live_locals.contains(l);
1183 if needs_storage_live {
1184 statements
1185 .push(Statement { source_info, kind: StatementKind::StorageLive(l) });
1186 }
1187 }
1188
1189 if operation == Operation::Resume {
1190 // Move the resume argument to the destination place of the `Yield` terminator
1191 let resume_arg = Local::new(2); // 0 = return, 1 = self
1192 statements.push(Statement {
1193 source_info,
1194 kind: StatementKind::Assign(box (
1195 point.resume_arg,
1196 Rvalue::Use(Operand::Move(resume_arg.into())),
1197 )),
1198 });
1199 }
1200
1201 // Then jump to the real target
1202 body.basic_blocks_mut().push(BasicBlockData {
1203 statements,
1204 terminator: Some(Terminator {
1205 source_info,
1206 kind: TerminatorKind::Goto { target },
1207 }),
1208 is_cleanup: false,
1209 });
1210
1211 (point.state, block)
1212 })
1213 })
1214 .collect()
1215 }
1216
1217 impl<'tcx> MirPass<'tcx> for StateTransform {
1218 fn run_pass(&self, tcx: TyCtxt<'tcx>, source: MirSource<'tcx>, body: &mut BodyAndCache<'tcx>) {
1219 let yield_ty = if let Some(yield_ty) = body.yield_ty {
1220 yield_ty
1221 } else {
1222 // This only applies to generators
1223 return;
1224 };
1225
1226 assert!(body.generator_drop.is_none());
1227
1228 let def_id = source.def_id();
1229
1230 // The first argument is the generator type passed by value
1231 let gen_ty = body.local_decls.raw[1].ty;
1232
1233 // Get the interior types and substs which typeck computed
1234 let (upvars, interior, discr_ty, movable) = match gen_ty.kind {
1235 ty::Generator(_, substs, movability) => {
1236 let substs = substs.as_generator();
1237 (
1238 substs.upvar_tys().collect(),
1239 substs.witness(),
1240 substs.discr_ty(tcx),
1241 movability == hir::Movability::Movable,
1242 )
1243 }
1244 _ => bug!(),
1245 };
1246
1247 // Compute GeneratorState<yield_ty, return_ty>
1248 let state_did = tcx.lang_items().gen_state().unwrap();
1249 let state_adt_ref = tcx.adt_def(state_did);
1250 let state_substs = tcx.intern_substs(&[yield_ty.into(), body.return_ty().into()]);
1251 let ret_ty = tcx.mk_adt(state_adt_ref, state_substs);
1252
1253 // We rename RETURN_PLACE which has type mir.return_ty to new_ret_local
1254 // RETURN_PLACE then is a fresh unused local with type ret_ty.
1255 let new_ret_local = replace_local(RETURN_PLACE, ret_ty, body, tcx);
1256
1257 // We also replace the resume argument and insert an `Assign`.
1258 // This is needed because the resume argument `_2` might be live across a `yield`, in which
1259 // case there is no `Assign` to it that the transform can turn into a store to the generator
1260 // state. After the yield the slot in the generator state would then be uninitialized.
1261 let resume_local = Local::new(2);
1262 let new_resume_local =
1263 replace_local(resume_local, body.local_decls[resume_local].ty, body, tcx);
1264
1265 // When first entering the generator, move the resume argument into its new local.
1266 let source_info = source_info(body);
1267 let stmts = &mut body.basic_blocks_mut()[BasicBlock::new(0)].statements;
1268 stmts.insert(
1269 0,
1270 Statement {
1271 source_info,
1272 kind: StatementKind::Assign(box (
1273 new_resume_local.into(),
1274 Rvalue::Use(Operand::Move(resume_local.into())),
1275 )),
1276 },
1277 );
1278
1279 let always_live_locals = storage::AlwaysLiveLocals::new(&body);
1280
1281 // Extract locals which are live across suspension point into `layout`
1282 // `remap` gives a mapping from local indices onto generator struct indices
1283 // `storage_liveness` tells us which locals have live storage at suspension points
1284 let (remap, layout, storage_liveness) =
1285 compute_layout(tcx, source, &upvars, interior, &always_live_locals, movable, body);
1286
1287 let can_return = can_return(tcx, body);
1288
1289 // Run the transformation which converts Places from Local to generator struct
1290 // accesses for locals in `remap`.
1291 // It also rewrites `return x` and `yield y` as writing a new generator state and returning
1292 // GeneratorState::Complete(x) and GeneratorState::Yielded(y) respectively.
1293 let mut transform = TransformVisitor {
1294 tcx,
1295 state_adt_ref,
1296 state_substs,
1297 remap,
1298 storage_liveness,
1299 always_live_locals,
1300 suspension_points: Vec::new(),
1301 new_ret_local,
1302 discr_ty,
1303 };
1304 transform.visit_body(body);
1305
1306 // Update our MIR struct to reflect the changes we've made
1307 body.yield_ty = None;
1308 body.arg_count = 2; // self, resume arg
1309 body.spread_arg = None;
1310 body.generator_layout = Some(layout);
1311
1312 // Insert `drop(generator_struct)` which is used to drop upvars for generators in
1313 // the unresumed state.
1314 // This is expanded to a drop ladder in `elaborate_generator_drops`.
1315 let drop_clean = insert_clean_drop(body);
1316
1317 dump_mir(tcx, None, "generator_pre-elab", &0, source, body, |_, _| Ok(()));
1318
1319 // Expand `drop(generator_struct)` to a drop ladder which destroys upvars.
1320 // If any upvars are moved out of, drop elaboration will handle upvar destruction.
1321 // However we need to also elaborate the code generated by `insert_clean_drop`.
1322 elaborate_generator_drops(tcx, def_id, body);
1323
1324 dump_mir(tcx, None, "generator_post-transform", &0, source, body, |_, _| Ok(()));
1325
1326 // Create a copy of our MIR and use it to create the drop shim for the generator
1327 let drop_shim =
1328 create_generator_drop_shim(tcx, &transform, source, gen_ty, body, drop_clean);
1329
1330 body.generator_drop = Some(box drop_shim);
1331
1332 // Create the Generator::resume function
1333 create_generator_resume_function(tcx, transform, source, body, can_return);
1334 }
1335 }