]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_transform/src/generator.rs
Auto merge of #104999 - saethlin:immediate-abort-inlining, r=thomcc
[rust.git] / compiler / rustc_mir_transform / src / 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 either the `Generator::resume` or `Future::poll`
15 //! function and the drop shim for the generator based on the MIR input.
16 //! It converts the generator argument from Self to &mut Self adding derefs in the MIR as needed.
17 //! It computes the final layout of the generator 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 //!     ```ignore (illustrative)
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)`,
36 //! or `Poll::Ready(x)` and `Poll::Pending` respectively.
37 //! MIR locals which are live across a suspension point are moved to the generator struct
38 //! with references to them being updated with references to the generator struct.
39 //!
40 //! The pass creates two functions which have a switch on the generator state giving
41 //! the action to take.
42 //!
43 //! One of them is the implementation of `Generator::resume` / `Future::poll`.
44 //! For generators with state 0 (unresumed) it starts the execution of the generator.
45 //! For generators with state 1 (returned) and state 2 (poisoned) it panics.
46 //! Otherwise it continues the execution from the last suspension point.
47 //!
48 //! The other function is the drop glue for the generator.
49 //! For generators with state 0 (unresumed) it drops the upvars of the generator.
50 //! For generators with state 1 (returned) and state 2 (poisoned) it does nothing.
51 //! Otherwise it drops all the values in scope at the last suspension point.
52
53 use crate::deref_separator::deref_finder;
54 use crate::simplify;
55 use crate::util::expand_aggregate;
56 use crate::MirPass;
57 use rustc_data_structures::fx::FxHashMap;
58 use rustc_hir as hir;
59 use rustc_hir::lang_items::LangItem;
60 use rustc_hir::GeneratorKind;
61 use rustc_index::bit_set::{BitMatrix, BitSet, GrowableBitSet};
62 use rustc_index::vec::{Idx, IndexVec};
63 use rustc_middle::mir::dump_mir;
64 use rustc_middle::mir::visit::{MutVisitor, PlaceContext, Visitor};
65 use rustc_middle::mir::*;
66 use rustc_middle::ty::{self, AdtDef, Ty, TyCtxt};
67 use rustc_middle::ty::{GeneratorSubsts, SubstsRef};
68 use rustc_mir_dataflow::impls::{
69     MaybeBorrowedLocals, MaybeLiveLocals, MaybeRequiresStorage, MaybeStorageLive,
70 };
71 use rustc_mir_dataflow::storage::always_storage_live_locals;
72 use rustc_mir_dataflow::{self, Analysis};
73 use rustc_target::abi::VariantIdx;
74 use rustc_target::spec::PanicStrategy;
75 use std::{iter, ops};
76
77 pub struct StateTransform;
78
79 struct RenameLocalVisitor<'tcx> {
80     from: Local,
81     to: Local,
82     tcx: TyCtxt<'tcx>,
83 }
84
85 impl<'tcx> MutVisitor<'tcx> for RenameLocalVisitor<'tcx> {
86     fn tcx(&self) -> TyCtxt<'tcx> {
87         self.tcx
88     }
89
90     fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
91         if *local == self.from {
92             *local = self.to;
93         }
94     }
95
96     fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, location: Location) {
97         match terminator.kind {
98             TerminatorKind::Return => {
99                 // Do not replace the implicit `_0` access here, as that's not possible. The
100                 // transform already handles `return` correctly.
101             }
102             _ => self.super_terminator(terminator, location),
103         }
104     }
105 }
106
107 struct DerefArgVisitor<'tcx> {
108     tcx: TyCtxt<'tcx>,
109 }
110
111 impl<'tcx> MutVisitor<'tcx> for DerefArgVisitor<'tcx> {
112     fn tcx(&self) -> TyCtxt<'tcx> {
113         self.tcx
114     }
115
116     fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
117         assert_ne!(*local, SELF_ARG);
118     }
119
120     fn visit_place(&mut self, place: &mut Place<'tcx>, context: PlaceContext, location: Location) {
121         if place.local == SELF_ARG {
122             replace_base(
123                 place,
124                 Place {
125                     local: SELF_ARG,
126                     projection: self.tcx().intern_place_elems(&[ProjectionElem::Deref]),
127                 },
128                 self.tcx,
129             );
130         } else {
131             self.visit_local(&mut place.local, context, location);
132
133             for elem in place.projection.iter() {
134                 if let PlaceElem::Index(local) = elem {
135                     assert_ne!(local, SELF_ARG);
136                 }
137             }
138         }
139     }
140 }
141
142 struct PinArgVisitor<'tcx> {
143     ref_gen_ty: Ty<'tcx>,
144     tcx: TyCtxt<'tcx>,
145 }
146
147 impl<'tcx> MutVisitor<'tcx> for PinArgVisitor<'tcx> {
148     fn tcx(&self) -> TyCtxt<'tcx> {
149         self.tcx
150     }
151
152     fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
153         assert_ne!(*local, SELF_ARG);
154     }
155
156     fn visit_place(&mut self, place: &mut Place<'tcx>, context: PlaceContext, location: Location) {
157         if place.local == SELF_ARG {
158             replace_base(
159                 place,
160                 Place {
161                     local: SELF_ARG,
162                     projection: self.tcx().intern_place_elems(&[ProjectionElem::Field(
163                         Field::new(0),
164                         self.ref_gen_ty,
165                     )]),
166                 },
167                 self.tcx,
168             );
169         } else {
170             self.visit_local(&mut place.local, context, location);
171
172             for elem in place.projection.iter() {
173                 if let PlaceElem::Index(local) = elem {
174                     assert_ne!(local, SELF_ARG);
175                 }
176             }
177         }
178     }
179 }
180
181 fn replace_base<'tcx>(place: &mut Place<'tcx>, new_base: Place<'tcx>, tcx: TyCtxt<'tcx>) {
182     place.local = new_base.local;
183
184     let mut new_projection = new_base.projection.to_vec();
185     new_projection.append(&mut place.projection.to_vec());
186
187     place.projection = tcx.intern_place_elems(&new_projection);
188 }
189
190 const SELF_ARG: Local = Local::from_u32(1);
191
192 /// Generator has not been resumed yet.
193 const UNRESUMED: usize = GeneratorSubsts::UNRESUMED;
194 /// Generator has returned / is completed.
195 const RETURNED: usize = GeneratorSubsts::RETURNED;
196 /// Generator has panicked and is poisoned.
197 const POISONED: usize = GeneratorSubsts::POISONED;
198
199 /// Number of variants to reserve in generator state. Corresponds to
200 /// `UNRESUMED` (beginning of a generator) and `RETURNED`/`POISONED`
201 /// (end of a generator) states.
202 const RESERVED_VARIANTS: usize = 3;
203
204 /// A `yield` point in the generator.
205 struct SuspensionPoint<'tcx> {
206     /// State discriminant used when suspending or resuming at this point.
207     state: usize,
208     /// The block to jump to after resumption.
209     resume: BasicBlock,
210     /// Where to move the resume argument after resumption.
211     resume_arg: Place<'tcx>,
212     /// Which block to jump to if the generator is dropped in this state.
213     drop: Option<BasicBlock>,
214     /// Set of locals that have live storage while at this suspension point.
215     storage_liveness: GrowableBitSet<Local>,
216 }
217
218 struct TransformVisitor<'tcx> {
219     tcx: TyCtxt<'tcx>,
220     is_async_kind: bool,
221     state_adt_ref: AdtDef<'tcx>,
222     state_substs: SubstsRef<'tcx>,
223
224     // The type of the discriminant in the generator struct
225     discr_ty: Ty<'tcx>,
226
227     // Mapping from Local to (type of local, generator struct index)
228     // FIXME(eddyb) This should use `IndexVec<Local, Option<_>>`.
229     remap: FxHashMap<Local, (Ty<'tcx>, VariantIdx, usize)>,
230
231     // A map from a suspension point in a block to the locals which have live storage at that point
232     storage_liveness: IndexVec<BasicBlock, Option<BitSet<Local>>>,
233
234     // A list of suspension points, generated during the transform
235     suspension_points: Vec<SuspensionPoint<'tcx>>,
236
237     // The set of locals that have no `StorageLive`/`StorageDead` annotations.
238     always_live_locals: BitSet<Local>,
239
240     // The original RETURN_PLACE local
241     new_ret_local: Local,
242 }
243
244 impl<'tcx> TransformVisitor<'tcx> {
245     // Make a `GeneratorState` or `Poll` variant assignment.
246     //
247     // `core::ops::GeneratorState` only has single element tuple variants,
248     // so we can just write to the downcasted first field and then set the
249     // discriminant to the appropriate variant.
250     fn make_state(
251         &self,
252         val: Operand<'tcx>,
253         source_info: SourceInfo,
254         is_return: bool,
255         statements: &mut Vec<Statement<'tcx>>,
256     ) {
257         let idx = VariantIdx::new(match (is_return, self.is_async_kind) {
258             (true, false) => 1,  // GeneratorState::Complete
259             (false, false) => 0, // GeneratorState::Yielded
260             (true, true) => 0,   // Poll::Ready
261             (false, true) => 1,  // Poll::Pending
262         });
263
264         let kind = AggregateKind::Adt(self.state_adt_ref.did(), idx, self.state_substs, None, None);
265
266         // `Poll::Pending`
267         if self.is_async_kind && idx == VariantIdx::new(1) {
268             assert_eq!(self.state_adt_ref.variant(idx).fields.len(), 0);
269
270             // FIXME(swatinem): assert that `val` is indeed unit?
271             statements.extend(expand_aggregate(
272                 Place::return_place(),
273                 std::iter::empty(),
274                 kind,
275                 source_info,
276                 self.tcx,
277             ));
278             return;
279         }
280
281         // else: `Poll::Ready(x)`, `GeneratorState::Yielded(x)` or `GeneratorState::Complete(x)`
282         assert_eq!(self.state_adt_ref.variant(idx).fields.len(), 1);
283
284         let ty = self
285             .tcx
286             .bound_type_of(self.state_adt_ref.variant(idx).fields[0].did)
287             .subst(self.tcx, self.state_substs);
288
289         statements.extend(expand_aggregate(
290             Place::return_place(),
291             std::iter::once((val, ty)),
292             kind,
293             source_info,
294             self.tcx,
295         ));
296     }
297
298     // Create a Place referencing a generator struct field
299     fn make_field(&self, variant_index: VariantIdx, idx: usize, ty: Ty<'tcx>) -> Place<'tcx> {
300         let self_place = Place::from(SELF_ARG);
301         let base = self.tcx.mk_place_downcast_unnamed(self_place, variant_index);
302         let mut projection = base.projection.to_vec();
303         projection.push(ProjectionElem::Field(Field::new(idx), ty));
304
305         Place { local: base.local, projection: self.tcx.intern_place_elems(&projection) }
306     }
307
308     // Create a statement which changes the discriminant
309     fn set_discr(&self, state_disc: VariantIdx, source_info: SourceInfo) -> Statement<'tcx> {
310         let self_place = Place::from(SELF_ARG);
311         Statement {
312             source_info,
313             kind: StatementKind::SetDiscriminant {
314                 place: Box::new(self_place),
315                 variant_index: state_disc,
316             },
317         }
318     }
319
320     // Create a statement which reads the discriminant into a temporary
321     fn get_discr(&self, body: &mut Body<'tcx>) -> (Statement<'tcx>, Place<'tcx>) {
322         let temp_decl = LocalDecl::new(self.discr_ty, body.span).internal();
323         let local_decls_len = body.local_decls.push(temp_decl);
324         let temp = Place::from(local_decls_len);
325
326         let self_place = Place::from(SELF_ARG);
327         let assign = Statement {
328             source_info: SourceInfo::outermost(body.span),
329             kind: StatementKind::Assign(Box::new((temp, Rvalue::Discriminant(self_place)))),
330         };
331         (assign, temp)
332     }
333 }
334
335 impl<'tcx> MutVisitor<'tcx> for TransformVisitor<'tcx> {
336     fn tcx(&self) -> TyCtxt<'tcx> {
337         self.tcx
338     }
339
340     fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
341         assert_eq!(self.remap.get(local), None);
342     }
343
344     fn visit_place(
345         &mut self,
346         place: &mut Place<'tcx>,
347         _context: PlaceContext,
348         _location: Location,
349     ) {
350         // Replace an Local in the remap with a generator struct access
351         if let Some(&(ty, variant_index, idx)) = self.remap.get(&place.local) {
352             replace_base(place, self.make_field(variant_index, idx, ty), self.tcx);
353         }
354     }
355
356     fn visit_basic_block_data(&mut self, block: BasicBlock, data: &mut BasicBlockData<'tcx>) {
357         // Remove StorageLive and StorageDead statements for remapped locals
358         data.retain_statements(|s| match s.kind {
359             StatementKind::StorageLive(l) | StatementKind::StorageDead(l) => {
360                 !self.remap.contains_key(&l)
361             }
362             _ => true,
363         });
364
365         let ret_val = match data.terminator().kind {
366             TerminatorKind::Return => {
367                 Some((true, None, Operand::Move(Place::from(self.new_ret_local)), None))
368             }
369             TerminatorKind::Yield { ref value, resume, resume_arg, drop } => {
370                 Some((false, Some((resume, resume_arg)), value.clone(), drop))
371             }
372             _ => None,
373         };
374
375         if let Some((is_return, resume, v, drop)) = ret_val {
376             let source_info = data.terminator().source_info;
377             // We must assign the value first in case it gets declared dead below
378             self.make_state(v, source_info, is_return, &mut data.statements);
379             let state = if let Some((resume, mut resume_arg)) = resume {
380                 // Yield
381                 let state = RESERVED_VARIANTS + self.suspension_points.len();
382
383                 // The resume arg target location might itself be remapped if its base local is
384                 // live across a yield.
385                 let resume_arg =
386                     if let Some(&(ty, variant, idx)) = self.remap.get(&resume_arg.local) {
387                         replace_base(&mut resume_arg, self.make_field(variant, idx, ty), self.tcx);
388                         resume_arg
389                     } else {
390                         resume_arg
391                     };
392
393                 self.suspension_points.push(SuspensionPoint {
394                     state,
395                     resume,
396                     resume_arg,
397                     drop,
398                     storage_liveness: self.storage_liveness[block].clone().unwrap().into(),
399                 });
400
401                 VariantIdx::new(state)
402             } else {
403                 // Return
404                 VariantIdx::new(RETURNED) // state for returned
405             };
406             data.statements.push(self.set_discr(state, source_info));
407             data.terminator_mut().kind = TerminatorKind::Return;
408         }
409
410         self.super_basic_block_data(block, data);
411     }
412 }
413
414 fn make_generator_state_argument_indirect<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
415     let gen_ty = body.local_decls.raw[1].ty;
416
417     let ref_gen_ty =
418         tcx.mk_ref(tcx.lifetimes.re_erased, ty::TypeAndMut { ty: gen_ty, mutbl: Mutability::Mut });
419
420     // Replace the by value generator argument
421     body.local_decls.raw[1].ty = ref_gen_ty;
422
423     // Add a deref to accesses of the generator state
424     DerefArgVisitor { tcx }.visit_body(body);
425 }
426
427 fn make_generator_state_argument_pinned<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
428     let ref_gen_ty = body.local_decls.raw[1].ty;
429
430     let pin_did = tcx.require_lang_item(LangItem::Pin, Some(body.span));
431     let pin_adt_ref = tcx.adt_def(pin_did);
432     let substs = tcx.intern_substs(&[ref_gen_ty.into()]);
433     let pin_ref_gen_ty = tcx.mk_adt(pin_adt_ref, substs);
434
435     // Replace the by ref generator argument
436     body.local_decls.raw[1].ty = pin_ref_gen_ty;
437
438     // Add the Pin field access to accesses of the generator state
439     PinArgVisitor { ref_gen_ty, tcx }.visit_body(body);
440 }
441
442 /// Allocates a new local and replaces all references of `local` with it. Returns the new local.
443 ///
444 /// `local` will be changed to a new local decl with type `ty`.
445 ///
446 /// Note that the new local will be uninitialized. It is the caller's responsibility to assign some
447 /// valid value to it before its first use.
448 fn replace_local<'tcx>(
449     local: Local,
450     ty: Ty<'tcx>,
451     body: &mut Body<'tcx>,
452     tcx: TyCtxt<'tcx>,
453 ) -> Local {
454     let new_decl = LocalDecl::new(ty, body.span);
455     let new_local = body.local_decls.push(new_decl);
456     body.local_decls.swap(local, new_local);
457
458     RenameLocalVisitor { from: local, to: new_local, tcx }.visit_body(body);
459
460     new_local
461 }
462
463 struct LivenessInfo {
464     /// Which locals are live across any suspension point.
465     saved_locals: GeneratorSavedLocals,
466
467     /// The set of saved locals live at each suspension point.
468     live_locals_at_suspension_points: Vec<BitSet<GeneratorSavedLocal>>,
469
470     /// Parallel vec to the above with SourceInfo for each yield terminator.
471     source_info_at_suspension_points: Vec<SourceInfo>,
472
473     /// For every saved local, the set of other saved locals that are
474     /// storage-live at the same time as this local. We cannot overlap locals in
475     /// the layout which have conflicting storage.
476     storage_conflicts: BitMatrix<GeneratorSavedLocal, GeneratorSavedLocal>,
477
478     /// For every suspending block, the locals which are storage-live across
479     /// that suspension point.
480     storage_liveness: IndexVec<BasicBlock, Option<BitSet<Local>>>,
481 }
482
483 fn locals_live_across_suspend_points<'tcx>(
484     tcx: TyCtxt<'tcx>,
485     body: &Body<'tcx>,
486     always_live_locals: &BitSet<Local>,
487     movable: bool,
488 ) -> LivenessInfo {
489     let body_ref: &Body<'_> = &body;
490
491     // Calculate when MIR locals have live storage. This gives us an upper bound of their
492     // lifetimes.
493     let mut storage_live = MaybeStorageLive::new(always_live_locals.clone())
494         .into_engine(tcx, body_ref)
495         .iterate_to_fixpoint()
496         .into_results_cursor(body_ref);
497
498     // Calculate the MIR locals which have been previously
499     // borrowed (even if they are still active).
500     let borrowed_locals_results =
501         MaybeBorrowedLocals.into_engine(tcx, body_ref).pass_name("generator").iterate_to_fixpoint();
502
503     let mut borrowed_locals_cursor =
504         rustc_mir_dataflow::ResultsCursor::new(body_ref, &borrowed_locals_results);
505
506     // Calculate the MIR locals that we actually need to keep storage around
507     // for.
508     let requires_storage_results = MaybeRequiresStorage::new(body, &borrowed_locals_results)
509         .into_engine(tcx, body_ref)
510         .iterate_to_fixpoint();
511     let mut requires_storage_cursor =
512         rustc_mir_dataflow::ResultsCursor::new(body_ref, &requires_storage_results);
513
514     // Calculate the liveness of MIR locals ignoring borrows.
515     let mut liveness = MaybeLiveLocals
516         .into_engine(tcx, body_ref)
517         .pass_name("generator")
518         .iterate_to_fixpoint()
519         .into_results_cursor(body_ref);
520
521     let mut storage_liveness_map = IndexVec::from_elem(None, &body.basic_blocks);
522     let mut live_locals_at_suspension_points = Vec::new();
523     let mut source_info_at_suspension_points = Vec::new();
524     let mut live_locals_at_any_suspension_point = BitSet::new_empty(body.local_decls.len());
525
526     for (block, data) in body.basic_blocks.iter_enumerated() {
527         if let TerminatorKind::Yield { .. } = data.terminator().kind {
528             let loc = Location { block, statement_index: data.statements.len() };
529
530             liveness.seek_to_block_end(block);
531             let mut live_locals: BitSet<_> = BitSet::new_empty(body.local_decls.len());
532             live_locals.union(liveness.get());
533
534             if !movable {
535                 // The `liveness` variable contains the liveness of MIR locals ignoring borrows.
536                 // This is correct for movable generators since borrows cannot live across
537                 // suspension points. However for immovable generators we need to account for
538                 // borrows, so we conservatively assume that all borrowed locals are live until
539                 // we find a StorageDead statement referencing the locals.
540                 // To do this we just union our `liveness` result with `borrowed_locals`, which
541                 // contains all the locals which has been borrowed before this suspension point.
542                 // If a borrow is converted to a raw reference, we must also assume that it lives
543                 // forever. Note that the final liveness is still bounded by the storage liveness
544                 // of the local, which happens using the `intersect` operation below.
545                 borrowed_locals_cursor.seek_before_primary_effect(loc);
546                 live_locals.union(borrowed_locals_cursor.get());
547             }
548
549             // Store the storage liveness for later use so we can restore the state
550             // after a suspension point
551             storage_live.seek_before_primary_effect(loc);
552             storage_liveness_map[block] = Some(storage_live.get().clone());
553
554             // Locals live are live at this point only if they are used across
555             // suspension points (the `liveness` variable)
556             // and their storage is required (the `storage_required` variable)
557             requires_storage_cursor.seek_before_primary_effect(loc);
558             live_locals.intersect(requires_storage_cursor.get());
559
560             // The generator argument is ignored.
561             live_locals.remove(SELF_ARG);
562
563             debug!("loc = {:?}, live_locals = {:?}", loc, live_locals);
564
565             // Add the locals live at this suspension point to the set of locals which live across
566             // any suspension points
567             live_locals_at_any_suspension_point.union(&live_locals);
568
569             live_locals_at_suspension_points.push(live_locals);
570             source_info_at_suspension_points.push(data.terminator().source_info);
571         }
572     }
573
574     debug!("live_locals_anywhere = {:?}", live_locals_at_any_suspension_point);
575     let saved_locals = GeneratorSavedLocals(live_locals_at_any_suspension_point);
576
577     // Renumber our liveness_map bitsets to include only the locals we are
578     // saving.
579     let live_locals_at_suspension_points = live_locals_at_suspension_points
580         .iter()
581         .map(|live_here| saved_locals.renumber_bitset(&live_here))
582         .collect();
583
584     let storage_conflicts = compute_storage_conflicts(
585         body_ref,
586         &saved_locals,
587         always_live_locals.clone(),
588         requires_storage_results,
589     );
590
591     LivenessInfo {
592         saved_locals,
593         live_locals_at_suspension_points,
594         source_info_at_suspension_points,
595         storage_conflicts,
596         storage_liveness: storage_liveness_map,
597     }
598 }
599
600 /// The set of `Local`s that must be saved across yield points.
601 ///
602 /// `GeneratorSavedLocal` is indexed in terms of the elements in this set;
603 /// i.e. `GeneratorSavedLocal::new(1)` corresponds to the second local
604 /// included in this set.
605 struct GeneratorSavedLocals(BitSet<Local>);
606
607 impl GeneratorSavedLocals {
608     /// Returns an iterator over each `GeneratorSavedLocal` along with the `Local` it corresponds
609     /// to.
610     fn iter_enumerated(&self) -> impl '_ + Iterator<Item = (GeneratorSavedLocal, Local)> {
611         self.iter().enumerate().map(|(i, l)| (GeneratorSavedLocal::from(i), l))
612     }
613
614     /// Transforms a `BitSet<Local>` that contains only locals saved across yield points to the
615     /// equivalent `BitSet<GeneratorSavedLocal>`.
616     fn renumber_bitset(&self, input: &BitSet<Local>) -> BitSet<GeneratorSavedLocal> {
617         assert!(self.superset(&input), "{:?} not a superset of {:?}", self.0, input);
618         let mut out = BitSet::new_empty(self.count());
619         for (saved_local, local) in self.iter_enumerated() {
620             if input.contains(local) {
621                 out.insert(saved_local);
622             }
623         }
624         out
625     }
626
627     fn get(&self, local: Local) -> Option<GeneratorSavedLocal> {
628         if !self.contains(local) {
629             return None;
630         }
631
632         let idx = self.iter().take_while(|&l| l < local).count();
633         Some(GeneratorSavedLocal::new(idx))
634     }
635 }
636
637 impl ops::Deref for GeneratorSavedLocals {
638     type Target = BitSet<Local>;
639
640     fn deref(&self) -> &Self::Target {
641         &self.0
642     }
643 }
644
645 /// For every saved local, looks for which locals are StorageLive at the same
646 /// time. Generates a bitset for every local of all the other locals that may be
647 /// StorageLive simultaneously with that local. This is used in the layout
648 /// computation; see `GeneratorLayout` for more.
649 fn compute_storage_conflicts<'mir, 'tcx>(
650     body: &'mir Body<'tcx>,
651     saved_locals: &GeneratorSavedLocals,
652     always_live_locals: BitSet<Local>,
653     requires_storage: rustc_mir_dataflow::Results<'tcx, MaybeRequiresStorage<'mir, 'tcx>>,
654 ) -> BitMatrix<GeneratorSavedLocal, GeneratorSavedLocal> {
655     assert_eq!(body.local_decls.len(), saved_locals.domain_size());
656
657     debug!("compute_storage_conflicts({:?})", body.span);
658     debug!("always_live = {:?}", always_live_locals);
659
660     // Locals that are always live or ones that need to be stored across
661     // suspension points are not eligible for overlap.
662     let mut ineligible_locals = always_live_locals;
663     ineligible_locals.intersect(&**saved_locals);
664
665     // Compute the storage conflicts for all eligible locals.
666     let mut visitor = StorageConflictVisitor {
667         body,
668         saved_locals: &saved_locals,
669         local_conflicts: BitMatrix::from_row_n(&ineligible_locals, body.local_decls.len()),
670     };
671
672     requires_storage.visit_reachable_with(body, &mut visitor);
673
674     let local_conflicts = visitor.local_conflicts;
675
676     // Compress the matrix using only stored locals (Local -> GeneratorSavedLocal).
677     //
678     // NOTE: Today we store a full conflict bitset for every local. Technically
679     // this is twice as many bits as we need, since the relation is symmetric.
680     // However, in practice these bitsets are not usually large. The layout code
681     // also needs to keep track of how many conflicts each local has, so it's
682     // simpler to keep it this way for now.
683     let mut storage_conflicts = BitMatrix::new(saved_locals.count(), saved_locals.count());
684     for (saved_local_a, local_a) in saved_locals.iter_enumerated() {
685         if ineligible_locals.contains(local_a) {
686             // Conflicts with everything.
687             storage_conflicts.insert_all_into_row(saved_local_a);
688         } else {
689             // Keep overlap information only for stored locals.
690             for (saved_local_b, local_b) in saved_locals.iter_enumerated() {
691                 if local_conflicts.contains(local_a, local_b) {
692                     storage_conflicts.insert(saved_local_a, saved_local_b);
693                 }
694             }
695         }
696     }
697     storage_conflicts
698 }
699
700 struct StorageConflictVisitor<'mir, 'tcx, 's> {
701     body: &'mir Body<'tcx>,
702     saved_locals: &'s GeneratorSavedLocals,
703     // FIXME(tmandry): Consider using sparse bitsets here once we have good
704     // benchmarks for generators.
705     local_conflicts: BitMatrix<Local, Local>,
706 }
707
708 impl<'mir, 'tcx> rustc_mir_dataflow::ResultsVisitor<'mir, 'tcx>
709     for StorageConflictVisitor<'mir, 'tcx, '_>
710 {
711     type FlowState = BitSet<Local>;
712
713     fn visit_statement_before_primary_effect(
714         &mut self,
715         state: &Self::FlowState,
716         _statement: &'mir Statement<'tcx>,
717         loc: Location,
718     ) {
719         self.apply_state(state, loc);
720     }
721
722     fn visit_terminator_before_primary_effect(
723         &mut self,
724         state: &Self::FlowState,
725         _terminator: &'mir Terminator<'tcx>,
726         loc: Location,
727     ) {
728         self.apply_state(state, loc);
729     }
730 }
731
732 impl StorageConflictVisitor<'_, '_, '_> {
733     fn apply_state(&mut self, flow_state: &BitSet<Local>, loc: Location) {
734         // Ignore unreachable blocks.
735         if self.body.basic_blocks[loc.block].terminator().kind == TerminatorKind::Unreachable {
736             return;
737         }
738
739         let mut eligible_storage_live = flow_state.clone();
740         eligible_storage_live.intersect(&**self.saved_locals);
741
742         for local in eligible_storage_live.iter() {
743             self.local_conflicts.union_row_with(&eligible_storage_live, local);
744         }
745
746         if eligible_storage_live.count() > 1 {
747             trace!("at {:?}, eligible_storage_live={:?}", loc, eligible_storage_live);
748         }
749     }
750 }
751
752 /// Validates the typeck view of the generator against the actual set of types saved between
753 /// yield points.
754 fn sanitize_witness<'tcx>(
755     tcx: TyCtxt<'tcx>,
756     body: &Body<'tcx>,
757     witness: Ty<'tcx>,
758     upvars: Vec<Ty<'tcx>>,
759     saved_locals: &GeneratorSavedLocals,
760 ) {
761     let did = body.source.def_id();
762     let param_env = tcx.param_env(did);
763
764     let allowed_upvars = tcx.normalize_erasing_regions(param_env, upvars);
765     let allowed = match witness.kind() {
766         &ty::GeneratorWitness(interior_tys) => {
767             tcx.normalize_erasing_late_bound_regions(param_env, interior_tys)
768         }
769         _ => {
770             tcx.sess.delay_span_bug(
771                 body.span,
772                 &format!("unexpected generator witness type {:?}", witness.kind()),
773             );
774             return;
775         }
776     };
777
778     for (local, decl) in body.local_decls.iter_enumerated() {
779         // Ignore locals which are internal or not saved between yields.
780         if !saved_locals.contains(local) || decl.internal {
781             continue;
782         }
783         let decl_ty = tcx.normalize_erasing_regions(param_env, decl.ty);
784
785         // Sanity check that typeck knows about the type of locals which are
786         // live across a suspension point
787         if !allowed.contains(&decl_ty) && !allowed_upvars.contains(&decl_ty) {
788             span_bug!(
789                 body.span,
790                 "Broken MIR: generator contains type {} in MIR, \
791                        but typeck only knows about {} and {:?}",
792                 decl_ty,
793                 allowed,
794                 allowed_upvars
795             );
796         }
797     }
798 }
799
800 fn compute_layout<'tcx>(
801     liveness: LivenessInfo,
802     body: &mut Body<'tcx>,
803 ) -> (
804     FxHashMap<Local, (Ty<'tcx>, VariantIdx, usize)>,
805     GeneratorLayout<'tcx>,
806     IndexVec<BasicBlock, Option<BitSet<Local>>>,
807 ) {
808     let LivenessInfo {
809         saved_locals,
810         live_locals_at_suspension_points,
811         source_info_at_suspension_points,
812         storage_conflicts,
813         storage_liveness,
814     } = liveness;
815
816     // Gather live local types and their indices.
817     let mut locals = IndexVec::<GeneratorSavedLocal, _>::new();
818     let mut tys = IndexVec::<GeneratorSavedLocal, _>::new();
819     for (saved_local, local) in saved_locals.iter_enumerated() {
820         locals.push(local);
821         tys.push(body.local_decls[local].ty);
822         debug!("generator saved local {:?} => {:?}", saved_local, local);
823     }
824
825     // Leave empty variants for the UNRESUMED, RETURNED, and POISONED states.
826     // In debuginfo, these will correspond to the beginning (UNRESUMED) or end
827     // (RETURNED, POISONED) of the function.
828     let body_span = body.source_scopes[OUTERMOST_SOURCE_SCOPE].span;
829     let mut variant_source_info: IndexVec<VariantIdx, SourceInfo> = [
830         SourceInfo::outermost(body_span.shrink_to_lo()),
831         SourceInfo::outermost(body_span.shrink_to_hi()),
832         SourceInfo::outermost(body_span.shrink_to_hi()),
833     ]
834     .iter()
835     .copied()
836     .collect();
837
838     // Build the generator variant field list.
839     // Create a map from local indices to generator struct indices.
840     let mut variant_fields: IndexVec<VariantIdx, IndexVec<Field, GeneratorSavedLocal>> =
841         iter::repeat(IndexVec::new()).take(RESERVED_VARIANTS).collect();
842     let mut remap = FxHashMap::default();
843     for (suspension_point_idx, live_locals) in live_locals_at_suspension_points.iter().enumerate() {
844         let variant_index = VariantIdx::from(RESERVED_VARIANTS + suspension_point_idx);
845         let mut fields = IndexVec::new();
846         for (idx, saved_local) in live_locals.iter().enumerate() {
847             fields.push(saved_local);
848             // Note that if a field is included in multiple variants, we will
849             // just use the first one here. That's fine; fields do not move
850             // around inside generators, so it doesn't matter which variant
851             // index we access them by.
852             remap.entry(locals[saved_local]).or_insert((tys[saved_local], variant_index, idx));
853         }
854         variant_fields.push(fields);
855         variant_source_info.push(source_info_at_suspension_points[suspension_point_idx]);
856     }
857     debug!("generator variant_fields = {:?}", variant_fields);
858     debug!("generator storage_conflicts = {:#?}", storage_conflicts);
859
860     let layout =
861         GeneratorLayout { field_tys: tys, variant_fields, variant_source_info, storage_conflicts };
862
863     (remap, layout, storage_liveness)
864 }
865
866 /// Replaces the entry point of `body` with a block that switches on the generator discriminant and
867 /// dispatches to blocks according to `cases`.
868 ///
869 /// After this function, the former entry point of the function will be bb1.
870 fn insert_switch<'tcx>(
871     body: &mut Body<'tcx>,
872     cases: Vec<(usize, BasicBlock)>,
873     transform: &TransformVisitor<'tcx>,
874     default: TerminatorKind<'tcx>,
875 ) {
876     let default_block = insert_term_block(body, default);
877     let (assign, discr) = transform.get_discr(body);
878     let switch_targets =
879         SwitchTargets::new(cases.iter().map(|(i, bb)| ((*i) as u128, *bb)), default_block);
880     let switch = TerminatorKind::SwitchInt {
881         discr: Operand::Move(discr),
882         switch_ty: transform.discr_ty,
883         targets: switch_targets,
884     };
885
886     let source_info = SourceInfo::outermost(body.span);
887     body.basic_blocks_mut().raw.insert(
888         0,
889         BasicBlockData {
890             statements: vec![assign],
891             terminator: Some(Terminator { source_info, kind: switch }),
892             is_cleanup: false,
893         },
894     );
895
896     let blocks = body.basic_blocks_mut().iter_mut();
897
898     for target in blocks.flat_map(|b| b.terminator_mut().successors_mut()) {
899         *target = BasicBlock::new(target.index() + 1);
900     }
901 }
902
903 fn elaborate_generator_drops<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
904     use crate::shim::DropShimElaborator;
905     use rustc_middle::mir::patch::MirPatch;
906     use rustc_mir_dataflow::elaborate_drops::{elaborate_drop, Unwind};
907
908     // Note that `elaborate_drops` only drops the upvars of a generator, and
909     // this is ok because `open_drop` can only be reached within that own
910     // generator's resume function.
911
912     let def_id = body.source.def_id();
913     let param_env = tcx.param_env(def_id);
914
915     let mut elaborator = DropShimElaborator { body, patch: MirPatch::new(body), tcx, param_env };
916
917     for (block, block_data) in body.basic_blocks.iter_enumerated() {
918         let (target, unwind, source_info) = match block_data.terminator() {
919             Terminator { source_info, kind: TerminatorKind::Drop { place, target, unwind } } => {
920                 if let Some(local) = place.as_local() {
921                     if local == SELF_ARG {
922                         (target, unwind, source_info)
923                     } else {
924                         continue;
925                     }
926                 } else {
927                     continue;
928                 }
929             }
930             _ => continue,
931         };
932         let unwind = if block_data.is_cleanup {
933             Unwind::InCleanup
934         } else {
935             Unwind::To(unwind.unwrap_or_else(|| elaborator.patch.resume_block()))
936         };
937         elaborate_drop(
938             &mut elaborator,
939             *source_info,
940             Place::from(SELF_ARG),
941             (),
942             *target,
943             unwind,
944             block,
945         );
946     }
947     elaborator.patch.apply(body);
948 }
949
950 fn create_generator_drop_shim<'tcx>(
951     tcx: TyCtxt<'tcx>,
952     transform: &TransformVisitor<'tcx>,
953     gen_ty: Ty<'tcx>,
954     body: &mut Body<'tcx>,
955     drop_clean: BasicBlock,
956 ) -> Body<'tcx> {
957     let mut body = body.clone();
958     body.arg_count = 1; // make sure the resume argument is not included here
959
960     let source_info = SourceInfo::outermost(body.span);
961
962     let mut cases = create_cases(&mut body, transform, Operation::Drop);
963
964     cases.insert(0, (UNRESUMED, drop_clean));
965
966     // The returned state and the poisoned state fall through to the default
967     // case which is just to return
968
969     insert_switch(&mut body, cases, &transform, TerminatorKind::Return);
970
971     for block in body.basic_blocks_mut() {
972         let kind = &mut block.terminator_mut().kind;
973         if let TerminatorKind::GeneratorDrop = *kind {
974             *kind = TerminatorKind::Return;
975         }
976     }
977
978     // Replace the return variable
979     body.local_decls[RETURN_PLACE] = LocalDecl::with_source_info(tcx.mk_unit(), source_info);
980
981     make_generator_state_argument_indirect(tcx, &mut body);
982
983     // Change the generator argument from &mut to *mut
984     body.local_decls[SELF_ARG] = LocalDecl::with_source_info(
985         tcx.mk_ptr(ty::TypeAndMut { ty: gen_ty, mutbl: hir::Mutability::Mut }),
986         source_info,
987     );
988     if tcx.sess.opts.unstable_opts.mir_emit_retag {
989         // Alias tracking must know we changed the type
990         body.basic_blocks_mut()[START_BLOCK].statements.insert(
991             0,
992             Statement {
993                 source_info,
994                 kind: StatementKind::Retag(RetagKind::Raw, Box::new(Place::from(SELF_ARG))),
995             },
996         )
997     }
998
999     // Make sure we remove dead blocks to remove
1000     // unrelated code from the resume part of the function
1001     simplify::remove_dead_blocks(tcx, &mut body);
1002
1003     dump_mir(tcx, None, "generator_drop", &0, &body, |_, _| Ok(()));
1004
1005     body
1006 }
1007
1008 fn insert_term_block<'tcx>(body: &mut Body<'tcx>, kind: TerminatorKind<'tcx>) -> BasicBlock {
1009     let source_info = SourceInfo::outermost(body.span);
1010     body.basic_blocks_mut().push(BasicBlockData {
1011         statements: Vec::new(),
1012         terminator: Some(Terminator { source_info, kind }),
1013         is_cleanup: false,
1014     })
1015 }
1016
1017 fn insert_panic_block<'tcx>(
1018     tcx: TyCtxt<'tcx>,
1019     body: &mut Body<'tcx>,
1020     message: AssertMessage<'tcx>,
1021 ) -> BasicBlock {
1022     let assert_block = BasicBlock::new(body.basic_blocks.len());
1023     let term = TerminatorKind::Assert {
1024         cond: Operand::Constant(Box::new(Constant {
1025             span: body.span,
1026             user_ty: None,
1027             literal: ConstantKind::from_bool(tcx, false),
1028         })),
1029         expected: true,
1030         msg: message,
1031         target: assert_block,
1032         cleanup: None,
1033     };
1034
1035     let source_info = SourceInfo::outermost(body.span);
1036     body.basic_blocks_mut().push(BasicBlockData {
1037         statements: Vec::new(),
1038         terminator: Some(Terminator { source_info, kind: term }),
1039         is_cleanup: false,
1040     });
1041
1042     assert_block
1043 }
1044
1045 fn can_return<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool {
1046     // Returning from a function with an uninhabited return type is undefined behavior.
1047     if body.return_ty().is_privately_uninhabited(tcx, param_env) {
1048         return false;
1049     }
1050
1051     // If there's a return terminator the function may return.
1052     for block in body.basic_blocks.iter() {
1053         if let TerminatorKind::Return = block.terminator().kind {
1054             return true;
1055         }
1056     }
1057
1058     // Otherwise the function can't return.
1059     false
1060 }
1061
1062 fn can_unwind<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>) -> bool {
1063     // Nothing can unwind when landing pads are off.
1064     if tcx.sess.panic_strategy() == PanicStrategy::Abort {
1065         return false;
1066     }
1067
1068     // Unwinds can only start at certain terminators.
1069     for block in body.basic_blocks.iter() {
1070         match block.terminator().kind {
1071             // These never unwind.
1072             TerminatorKind::Goto { .. }
1073             | TerminatorKind::SwitchInt { .. }
1074             | TerminatorKind::Abort
1075             | TerminatorKind::Return
1076             | TerminatorKind::Unreachable
1077             | TerminatorKind::GeneratorDrop
1078             | TerminatorKind::FalseEdge { .. }
1079             | TerminatorKind::FalseUnwind { .. } => {}
1080
1081             // Resume will *continue* unwinding, but if there's no other unwinding terminator it
1082             // will never be reached.
1083             TerminatorKind::Resume => {}
1084
1085             TerminatorKind::Yield { .. } => {
1086                 unreachable!("`can_unwind` called before generator transform")
1087             }
1088
1089             // These may unwind.
1090             TerminatorKind::Drop { .. }
1091             | TerminatorKind::DropAndReplace { .. }
1092             | TerminatorKind::Call { .. }
1093             | TerminatorKind::InlineAsm { .. }
1094             | TerminatorKind::Assert { .. } => return true,
1095         }
1096     }
1097
1098     // If we didn't find an unwinding terminator, the function cannot unwind.
1099     false
1100 }
1101
1102 fn create_generator_resume_function<'tcx>(
1103     tcx: TyCtxt<'tcx>,
1104     transform: TransformVisitor<'tcx>,
1105     body: &mut Body<'tcx>,
1106     can_return: bool,
1107 ) {
1108     let can_unwind = can_unwind(tcx, body);
1109
1110     // Poison the generator when it unwinds
1111     if can_unwind {
1112         let source_info = SourceInfo::outermost(body.span);
1113         let poison_block = body.basic_blocks_mut().push(BasicBlockData {
1114             statements: vec![transform.set_discr(VariantIdx::new(POISONED), source_info)],
1115             terminator: Some(Terminator { source_info, kind: TerminatorKind::Resume }),
1116             is_cleanup: true,
1117         });
1118
1119         for (idx, block) in body.basic_blocks_mut().iter_enumerated_mut() {
1120             let source_info = block.terminator().source_info;
1121
1122             if let TerminatorKind::Resume = block.terminator().kind {
1123                 // An existing `Resume` terminator is redirected to jump to our dedicated
1124                 // "poisoning block" above.
1125                 if idx != poison_block {
1126                     *block.terminator_mut() = Terminator {
1127                         source_info,
1128                         kind: TerminatorKind::Goto { target: poison_block },
1129                     };
1130                 }
1131             } else if !block.is_cleanup {
1132                 // Any terminators that *can* unwind but don't have an unwind target set are also
1133                 // pointed at our poisoning block (unless they're part of the cleanup path).
1134                 if let Some(unwind @ None) = block.terminator_mut().unwind_mut() {
1135                     *unwind = Some(poison_block);
1136                 }
1137             }
1138         }
1139     }
1140
1141     let mut cases = create_cases(body, &transform, Operation::Resume);
1142
1143     use rustc_middle::mir::AssertKind::{ResumedAfterPanic, ResumedAfterReturn};
1144
1145     // Jump to the entry point on the unresumed
1146     cases.insert(0, (UNRESUMED, BasicBlock::new(0)));
1147
1148     // Panic when resumed on the returned or poisoned state
1149     let generator_kind = body.generator_kind().unwrap();
1150
1151     if can_unwind {
1152         cases.insert(
1153             1,
1154             (POISONED, insert_panic_block(tcx, body, ResumedAfterPanic(generator_kind))),
1155         );
1156     }
1157
1158     if can_return {
1159         cases.insert(
1160             1,
1161             (RETURNED, insert_panic_block(tcx, body, ResumedAfterReturn(generator_kind))),
1162         );
1163     }
1164
1165     insert_switch(body, cases, &transform, TerminatorKind::Unreachable);
1166
1167     make_generator_state_argument_indirect(tcx, body);
1168     make_generator_state_argument_pinned(tcx, body);
1169
1170     // Make sure we remove dead blocks to remove
1171     // unrelated code from the drop part of the function
1172     simplify::remove_dead_blocks(tcx, body);
1173
1174     dump_mir(tcx, None, "generator_resume", &0, body, |_, _| Ok(()));
1175 }
1176
1177 fn insert_clean_drop(body: &mut Body<'_>) -> BasicBlock {
1178     let return_block = insert_term_block(body, TerminatorKind::Return);
1179
1180     let term =
1181         TerminatorKind::Drop { place: Place::from(SELF_ARG), target: return_block, unwind: None };
1182     let source_info = SourceInfo::outermost(body.span);
1183
1184     // Create a block to destroy an unresumed generators. This can only destroy upvars.
1185     body.basic_blocks_mut().push(BasicBlockData {
1186         statements: Vec::new(),
1187         terminator: Some(Terminator { source_info, kind: term }),
1188         is_cleanup: false,
1189     })
1190 }
1191
1192 /// An operation that can be performed on a generator.
1193 #[derive(PartialEq, Copy, Clone)]
1194 enum Operation {
1195     Resume,
1196     Drop,
1197 }
1198
1199 impl Operation {
1200     fn target_block(self, point: &SuspensionPoint<'_>) -> Option<BasicBlock> {
1201         match self {
1202             Operation::Resume => Some(point.resume),
1203             Operation::Drop => point.drop,
1204         }
1205     }
1206 }
1207
1208 fn create_cases<'tcx>(
1209     body: &mut Body<'tcx>,
1210     transform: &TransformVisitor<'tcx>,
1211     operation: Operation,
1212 ) -> Vec<(usize, BasicBlock)> {
1213     let source_info = SourceInfo::outermost(body.span);
1214
1215     transform
1216         .suspension_points
1217         .iter()
1218         .filter_map(|point| {
1219             // Find the target for this suspension point, if applicable
1220             operation.target_block(point).map(|target| {
1221                 let mut statements = Vec::new();
1222
1223                 // Create StorageLive instructions for locals with live storage
1224                 for i in 0..(body.local_decls.len()) {
1225                     if i == 2 {
1226                         // The resume argument is live on function entry. Don't insert a
1227                         // `StorageLive`, or the following `Assign` will read from uninitialized
1228                         // memory.
1229                         continue;
1230                     }
1231
1232                     let l = Local::new(i);
1233                     let needs_storage_live = point.storage_liveness.contains(l)
1234                         && !transform.remap.contains_key(&l)
1235                         && !transform.always_live_locals.contains(l);
1236                     if needs_storage_live {
1237                         statements
1238                             .push(Statement { source_info, kind: StatementKind::StorageLive(l) });
1239                     }
1240                 }
1241
1242                 if operation == Operation::Resume {
1243                     // Move the resume argument to the destination place of the `Yield` terminator
1244                     let resume_arg = Local::new(2); // 0 = return, 1 = self
1245                     statements.push(Statement {
1246                         source_info,
1247                         kind: StatementKind::Assign(Box::new((
1248                             point.resume_arg,
1249                             Rvalue::Use(Operand::Move(resume_arg.into())),
1250                         ))),
1251                     });
1252                 }
1253
1254                 // Then jump to the real target
1255                 let block = body.basic_blocks_mut().push(BasicBlockData {
1256                     statements,
1257                     terminator: Some(Terminator {
1258                         source_info,
1259                         kind: TerminatorKind::Goto { target },
1260                     }),
1261                     is_cleanup: false,
1262                 });
1263
1264                 (point.state, block)
1265             })
1266         })
1267         .collect()
1268 }
1269
1270 impl<'tcx> MirPass<'tcx> for StateTransform {
1271     fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
1272         let Some(yield_ty) = body.yield_ty() else {
1273             // This only applies to generators
1274             return;
1275         };
1276
1277         assert!(body.generator_drop().is_none());
1278
1279         // The first argument is the generator type passed by value
1280         let gen_ty = body.local_decls.raw[1].ty;
1281
1282         // Get the interior types and substs which typeck computed
1283         let (upvars, interior, discr_ty, movable) = match *gen_ty.kind() {
1284             ty::Generator(_, substs, movability) => {
1285                 let substs = substs.as_generator();
1286                 (
1287                     substs.upvar_tys().collect(),
1288                     substs.witness(),
1289                     substs.discr_ty(tcx),
1290                     movability == hir::Movability::Movable,
1291                 )
1292             }
1293             _ => {
1294                 tcx.sess
1295                     .delay_span_bug(body.span, &format!("unexpected generator type {}", gen_ty));
1296                 return;
1297             }
1298         };
1299
1300         let is_async_kind = body.generator_kind().unwrap() != GeneratorKind::Gen;
1301         let (state_adt_ref, state_substs) = if is_async_kind {
1302             // Compute Poll<return_ty>
1303             let state_did = tcx.require_lang_item(LangItem::Poll, None);
1304             let state_adt_ref = tcx.adt_def(state_did);
1305             let state_substs = tcx.intern_substs(&[body.return_ty().into()]);
1306             (state_adt_ref, state_substs)
1307         } else {
1308             // Compute GeneratorState<yield_ty, return_ty>
1309             let state_did = tcx.require_lang_item(LangItem::GeneratorState, None);
1310             let state_adt_ref = tcx.adt_def(state_did);
1311             let state_substs = tcx.intern_substs(&[yield_ty.into(), body.return_ty().into()]);
1312             (state_adt_ref, state_substs)
1313         };
1314         let ret_ty = tcx.mk_adt(state_adt_ref, state_substs);
1315
1316         // We rename RETURN_PLACE which has type mir.return_ty to new_ret_local
1317         // RETURN_PLACE then is a fresh unused local with type ret_ty.
1318         let new_ret_local = replace_local(RETURN_PLACE, ret_ty, body, tcx);
1319
1320         // We also replace the resume argument and insert an `Assign`.
1321         // This is needed because the resume argument `_2` might be live across a `yield`, in which
1322         // case there is no `Assign` to it that the transform can turn into a store to the generator
1323         // state. After the yield the slot in the generator state would then be uninitialized.
1324         let resume_local = Local::new(2);
1325         let new_resume_local =
1326             replace_local(resume_local, body.local_decls[resume_local].ty, body, tcx);
1327
1328         // When first entering the generator, move the resume argument into its new local.
1329         let source_info = SourceInfo::outermost(body.span);
1330         let stmts = &mut body.basic_blocks_mut()[BasicBlock::new(0)].statements;
1331         stmts.insert(
1332             0,
1333             Statement {
1334                 source_info,
1335                 kind: StatementKind::Assign(Box::new((
1336                     new_resume_local.into(),
1337                     Rvalue::Use(Operand::Move(resume_local.into())),
1338                 ))),
1339             },
1340         );
1341
1342         let always_live_locals = always_storage_live_locals(&body);
1343
1344         let liveness_info =
1345             locals_live_across_suspend_points(tcx, body, &always_live_locals, movable);
1346
1347         sanitize_witness(tcx, body, interior, upvars, &liveness_info.saved_locals);
1348
1349         if tcx.sess.opts.unstable_opts.validate_mir {
1350             let mut vis = EnsureGeneratorFieldAssignmentsNeverAlias {
1351                 assigned_local: None,
1352                 saved_locals: &liveness_info.saved_locals,
1353                 storage_conflicts: &liveness_info.storage_conflicts,
1354             };
1355
1356             vis.visit_body(body);
1357         }
1358
1359         // Extract locals which are live across suspension point into `layout`
1360         // `remap` gives a mapping from local indices onto generator struct indices
1361         // `storage_liveness` tells us which locals have live storage at suspension points
1362         let (remap, layout, storage_liveness) = compute_layout(liveness_info, body);
1363
1364         let can_return = can_return(tcx, body, tcx.param_env(body.source.def_id()));
1365
1366         // Run the transformation which converts Places from Local to generator struct
1367         // accesses for locals in `remap`.
1368         // It also rewrites `return x` and `yield y` as writing a new generator state and returning
1369         // either GeneratorState::Complete(x) and GeneratorState::Yielded(y),
1370         // or Poll::Ready(x) and Poll::Pending respectively depending on `is_async_kind`.
1371         let mut transform = TransformVisitor {
1372             tcx,
1373             is_async_kind,
1374             state_adt_ref,
1375             state_substs,
1376             remap,
1377             storage_liveness,
1378             always_live_locals,
1379             suspension_points: Vec::new(),
1380             new_ret_local,
1381             discr_ty,
1382         };
1383         transform.visit_body(body);
1384
1385         // Update our MIR struct to reflect the changes we've made
1386         body.arg_count = 2; // self, resume arg
1387         body.spread_arg = None;
1388
1389         body.generator.as_mut().unwrap().yield_ty = None;
1390         body.generator.as_mut().unwrap().generator_layout = Some(layout);
1391
1392         // Insert `drop(generator_struct)` which is used to drop upvars for generators in
1393         // the unresumed state.
1394         // This is expanded to a drop ladder in `elaborate_generator_drops`.
1395         let drop_clean = insert_clean_drop(body);
1396
1397         dump_mir(tcx, None, "generator_pre-elab", &0, body, |_, _| Ok(()));
1398
1399         // Expand `drop(generator_struct)` to a drop ladder which destroys upvars.
1400         // If any upvars are moved out of, drop elaboration will handle upvar destruction.
1401         // However we need to also elaborate the code generated by `insert_clean_drop`.
1402         elaborate_generator_drops(tcx, body);
1403
1404         dump_mir(tcx, None, "generator_post-transform", &0, body, |_, _| Ok(()));
1405
1406         // Create a copy of our MIR and use it to create the drop shim for the generator
1407         let drop_shim = create_generator_drop_shim(tcx, &transform, gen_ty, body, drop_clean);
1408
1409         body.generator.as_mut().unwrap().generator_drop = Some(drop_shim);
1410
1411         // Create the Generator::resume / Future::poll function
1412         create_generator_resume_function(tcx, transform, body, can_return);
1413
1414         // Run derefer to fix Derefs that are not in the first place
1415         deref_finder(tcx, body);
1416     }
1417 }
1418
1419 /// Looks for any assignments between locals (e.g., `_4 = _5`) that will both be converted to fields
1420 /// in the generator state machine but whose storage is not marked as conflicting
1421 ///
1422 /// Validation needs to happen immediately *before* `TransformVisitor` is invoked, not after.
1423 ///
1424 /// This condition would arise when the assignment is the last use of `_5` but the initial
1425 /// definition of `_4` if we weren't extra careful to mark all locals used inside a statement as
1426 /// conflicting. Non-conflicting generator saved locals may be stored at the same location within
1427 /// the generator state machine, which would result in ill-formed MIR: the left-hand and right-hand
1428 /// sides of an assignment may not alias. This caused a miscompilation in [#73137].
1429 ///
1430 /// [#73137]: https://github.com/rust-lang/rust/issues/73137
1431 struct EnsureGeneratorFieldAssignmentsNeverAlias<'a> {
1432     saved_locals: &'a GeneratorSavedLocals,
1433     storage_conflicts: &'a BitMatrix<GeneratorSavedLocal, GeneratorSavedLocal>,
1434     assigned_local: Option<GeneratorSavedLocal>,
1435 }
1436
1437 impl EnsureGeneratorFieldAssignmentsNeverAlias<'_> {
1438     fn saved_local_for_direct_place(&self, place: Place<'_>) -> Option<GeneratorSavedLocal> {
1439         if place.is_indirect() {
1440             return None;
1441         }
1442
1443         self.saved_locals.get(place.local)
1444     }
1445
1446     fn check_assigned_place(&mut self, place: Place<'_>, f: impl FnOnce(&mut Self)) {
1447         if let Some(assigned_local) = self.saved_local_for_direct_place(place) {
1448             assert!(self.assigned_local.is_none(), "`check_assigned_place` must not recurse");
1449
1450             self.assigned_local = Some(assigned_local);
1451             f(self);
1452             self.assigned_local = None;
1453         }
1454     }
1455 }
1456
1457 impl<'tcx> Visitor<'tcx> for EnsureGeneratorFieldAssignmentsNeverAlias<'_> {
1458     fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
1459         let Some(lhs) = self.assigned_local else {
1460             // This visitor only invokes `visit_place` for the right-hand side of an assignment
1461             // and only after setting `self.assigned_local`. However, the default impl of
1462             // `Visitor::super_body` may call `visit_place` with a `NonUseContext` for places
1463             // with debuginfo. Ignore them here.
1464             assert!(!context.is_use());
1465             return;
1466         };
1467
1468         let Some(rhs) = self.saved_local_for_direct_place(*place) else { return };
1469
1470         if !self.storage_conflicts.contains(lhs, rhs) {
1471             bug!(
1472                 "Assignment between generator saved locals whose storage is not \
1473                     marked as conflicting: {:?}: {:?} = {:?}",
1474                 location,
1475                 lhs,
1476                 rhs,
1477             );
1478         }
1479     }
1480
1481     fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
1482         match &statement.kind {
1483             StatementKind::Assign(box (lhs, rhs)) => {
1484                 self.check_assigned_place(*lhs, |this| this.visit_rvalue(rhs, location));
1485             }
1486
1487             StatementKind::FakeRead(..)
1488             | StatementKind::SetDiscriminant { .. }
1489             | StatementKind::Deinit(..)
1490             | StatementKind::StorageLive(_)
1491             | StatementKind::StorageDead(_)
1492             | StatementKind::Retag(..)
1493             | StatementKind::AscribeUserType(..)
1494             | StatementKind::Coverage(..)
1495             | StatementKind::Intrinsic(..)
1496             | StatementKind::Nop => {}
1497         }
1498     }
1499
1500     fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
1501         // Checking for aliasing in terminators is probably overkill, but until we have actual
1502         // semantics, we should be conservative here.
1503         match &terminator.kind {
1504             TerminatorKind::Call {
1505                 func,
1506                 args,
1507                 destination,
1508                 target: Some(_),
1509                 cleanup: _,
1510                 from_hir_call: _,
1511                 fn_span: _,
1512             } => {
1513                 self.check_assigned_place(*destination, |this| {
1514                     this.visit_operand(func, location);
1515                     for arg in args {
1516                         this.visit_operand(arg, location);
1517                     }
1518                 });
1519             }
1520
1521             TerminatorKind::Yield { value, resume: _, resume_arg, drop: _ } => {
1522                 self.check_assigned_place(*resume_arg, |this| this.visit_operand(value, location));
1523             }
1524
1525             // FIXME: Does `asm!` have any aliasing requirements?
1526             TerminatorKind::InlineAsm { .. } => {}
1527
1528             TerminatorKind::Call { .. }
1529             | TerminatorKind::Goto { .. }
1530             | TerminatorKind::SwitchInt { .. }
1531             | TerminatorKind::Resume
1532             | TerminatorKind::Abort
1533             | TerminatorKind::Return
1534             | TerminatorKind::Unreachable
1535             | TerminatorKind::Drop { .. }
1536             | TerminatorKind::DropAndReplace { .. }
1537             | TerminatorKind::Assert { .. }
1538             | TerminatorKind::GeneratorDrop
1539             | TerminatorKind::FalseEdge { .. }
1540             | TerminatorKind::FalseUnwind { .. } => {}
1541         }
1542     }
1543 }