]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/generator.rs
Rollup merge of #59432 - phansch:compiletest_docs, r=alexcrichton
[rust.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 rustc::hir;
53 use rustc::hir::def_id::DefId;
54 use rustc::mir::*;
55 use rustc::mir::visit::{PlaceContext, Visitor, MutVisitor};
56 use rustc::ty::{self, TyCtxt, AdtDef, Ty};
57 use rustc::ty::layout::VariantIdx;
58 use rustc::ty::subst::SubstsRef;
59 use rustc_data_structures::fx::FxHashMap;
60 use rustc_data_structures::indexed_vec::Idx;
61 use rustc_data_structures::bit_set::BitSet;
62 use std::borrow::Cow;
63 use std::iter::once;
64 use std::mem;
65 use crate::transform::{MirPass, MirSource};
66 use crate::transform::simplify;
67 use crate::transform::no_landing_pads::no_landing_pads;
68 use crate::dataflow::{do_dataflow, DebugFormatted, state_for_location};
69 use crate::dataflow::{MaybeStorageLive, HaveBeenBorrowedLocals};
70 use crate::util::dump_mir;
71 use crate::util::liveness;
72
73 pub struct StateTransform;
74
75 struct RenameLocalVisitor {
76     from: Local,
77     to: Local,
78 }
79
80 impl<'tcx> MutVisitor<'tcx> for RenameLocalVisitor {
81     fn visit_local(&mut self,
82                    local: &mut Local,
83                    _: PlaceContext<'tcx>,
84                    _: Location) {
85         if *local == self.from {
86             *local = self.to;
87         }
88     }
89 }
90
91 struct DerefArgVisitor;
92
93 impl<'tcx> MutVisitor<'tcx> for DerefArgVisitor {
94     fn visit_local(&mut self,
95                    local: &mut Local,
96                    _: PlaceContext<'tcx>,
97                    _: Location) {
98         assert_ne!(*local, self_arg());
99     }
100
101     fn visit_place(&mut self,
102                     place: &mut Place<'tcx>,
103                     context: PlaceContext<'tcx>,
104                     location: Location) {
105         if *place == Place::Base(PlaceBase::Local(self_arg())) {
106             *place = Place::Projection(Box::new(Projection {
107                 base: place.clone(),
108                 elem: ProjectionElem::Deref,
109             }));
110         } else {
111             self.super_place(place, context, location);
112         }
113     }
114 }
115
116 struct PinArgVisitor<'tcx> {
117     ref_gen_ty: Ty<'tcx>,
118 }
119
120 impl<'tcx> MutVisitor<'tcx> for PinArgVisitor<'tcx> {
121     fn visit_local(&mut self,
122                    local: &mut Local,
123                    _: PlaceContext<'tcx>,
124                    _: Location) {
125         assert_ne!(*local, self_arg());
126     }
127
128     fn visit_place(&mut self,
129                     place: &mut Place<'tcx>,
130                     context: PlaceContext<'tcx>,
131                     location: Location) {
132         if *place == Place::Base(PlaceBase::Local(self_arg())) {
133             *place = Place::Projection(Box::new(Projection {
134                 base: place.clone(),
135                 elem: ProjectionElem::Field(Field::new(0), self.ref_gen_ty),
136             }));
137         } else {
138             self.super_place(place, context, location);
139         }
140     }
141 }
142
143 fn self_arg() -> Local {
144     Local::new(1)
145 }
146
147 /// Generator have not been resumed yet
148 const UNRESUMED: u32 = 0;
149 /// Generator has returned / is completed
150 const RETURNED: u32 = 1;
151 /// Generator has been poisoned
152 const POISONED: u32 = 2;
153
154 struct SuspensionPoint {
155     state: u32,
156     resume: BasicBlock,
157     drop: Option<BasicBlock>,
158     storage_liveness: liveness::LiveVarSet,
159 }
160
161 struct TransformVisitor<'a, 'tcx: 'a> {
162     tcx: TyCtxt<'a, 'tcx, 'tcx>,
163     state_adt_ref: &'tcx AdtDef,
164     state_substs: SubstsRef<'tcx>,
165
166     // The index of the generator state in the generator struct
167     state_field: usize,
168
169     // Mapping from Local to (type of local, generator struct index)
170     // FIXME(eddyb) This should use `IndexVec<Local, Option<_>>`.
171     remap: FxHashMap<Local, (Ty<'tcx>, usize)>,
172
173     // A map from a suspension point in a block to the locals which have live storage at that point
174     // FIXME(eddyb) This should use `IndexVec<BasicBlock, Option<_>>`.
175     storage_liveness: FxHashMap<BasicBlock, liveness::LiveVarSet>,
176
177     // A list of suspension points, generated during the transform
178     suspension_points: Vec<SuspensionPoint>,
179
180     // The original RETURN_PLACE local
181     new_ret_local: Local,
182 }
183
184 impl<'a, 'tcx> TransformVisitor<'a, 'tcx> {
185     // Make a GeneratorState rvalue
186     fn make_state(&self, idx: VariantIdx, val: Operand<'tcx>) -> Rvalue<'tcx> {
187         let adt = AggregateKind::Adt(self.state_adt_ref, idx, self.state_substs, None, None);
188         Rvalue::Aggregate(box adt, vec![val])
189     }
190
191     // Create a Place referencing a generator struct field
192     fn make_field(&self, idx: usize, ty: Ty<'tcx>) -> Place<'tcx> {
193         let base = Place::Base(PlaceBase::Local(self_arg()));
194         let field = Projection {
195             base: base,
196             elem: ProjectionElem::Field(Field::new(idx), ty),
197         };
198         Place::Projection(Box::new(field))
199     }
200
201     // Create a statement which changes the generator state
202     fn set_state(&self, state_disc: u32, source_info: SourceInfo) -> Statement<'tcx> {
203         let state = self.make_field(self.state_field, self.tcx.types.u32);
204         let val = Operand::Constant(box Constant {
205             span: source_info.span,
206             ty: self.tcx.types.u32,
207             user_ty: None,
208             literal: self.tcx.mk_const(ty::Const::from_bits(
209                 self.tcx,
210                 state_disc.into(),
211                 ty::ParamEnv::empty().and(self.tcx.types.u32)
212             )),
213         });
214         Statement {
215             source_info,
216             kind: StatementKind::Assign(state, box Rvalue::Use(val)),
217         }
218     }
219 }
220
221 impl<'a, 'tcx> MutVisitor<'tcx> for TransformVisitor<'a, 'tcx> {
222     fn visit_local(&mut self,
223                    local: &mut Local,
224                    _: PlaceContext<'tcx>,
225                    _: Location) {
226         assert_eq!(self.remap.get(local), None);
227     }
228
229     fn visit_place(&mut self,
230                     place: &mut Place<'tcx>,
231                     context: PlaceContext<'tcx>,
232                     location: Location) {
233         if let Place::Base(PlaceBase::Local(l)) = *place {
234             // Replace an Local in the remap with a generator struct access
235             if let Some(&(ty, idx)) = self.remap.get(&l) {
236                 *place = self.make_field(idx, ty);
237             }
238         } else {
239             self.super_place(place, context, location);
240         }
241     }
242
243     fn visit_basic_block_data(&mut self,
244                               block: BasicBlock,
245                               data: &mut BasicBlockData<'tcx>) {
246         // Remove StorageLive and StorageDead statements for remapped locals
247         data.retain_statements(|s| {
248             match s.kind {
249                 StatementKind::StorageLive(l) | StatementKind::StorageDead(l) => {
250                     !self.remap.contains_key(&l)
251                 }
252                 _ => true
253             }
254         });
255
256         let ret_val = match data.terminator().kind {
257             TerminatorKind::Return => Some((VariantIdx::new(1),
258                 None,
259                 Operand::Move(Place::Base(PlaceBase::Local(self.new_ret_local))),
260                 None)),
261             TerminatorKind::Yield { ref value, resume, drop } => Some((VariantIdx::new(0),
262                 Some(resume),
263                 value.clone(),
264                 drop)),
265             _ => None
266         };
267
268         if let Some((state_idx, resume, v, drop)) = ret_val {
269             let source_info = data.terminator().source_info;
270             // We must assign the value first in case it gets declared dead below
271             data.statements.push(Statement {
272                 source_info,
273                 kind: StatementKind::Assign(Place::RETURN_PLACE,
274                                             box self.make_state(state_idx, v)),
275             });
276             let state = if let Some(resume) = resume { // Yield
277                 let state = 3 + self.suspension_points.len() as u32;
278
279                 self.suspension_points.push(SuspensionPoint {
280                     state,
281                     resume,
282                     drop,
283                     storage_liveness: self.storage_liveness.get(&block).unwrap().clone(),
284                 });
285
286                 state
287             } else { // Return
288                 RETURNED // state for returned
289             };
290             data.statements.push(self.set_state(state, source_info));
291             data.terminator.as_mut().unwrap().kind = TerminatorKind::Return;
292         }
293
294         self.super_basic_block_data(block, data);
295     }
296 }
297
298 fn make_generator_state_argument_indirect<'a, 'tcx>(
299                 tcx: TyCtxt<'a, 'tcx, 'tcx>,
300                 def_id: DefId,
301                 mir: &mut Mir<'tcx>) {
302     let gen_ty = mir.local_decls.raw[1].ty;
303
304     let region = ty::ReFree(ty::FreeRegion {
305         scope: def_id,
306         bound_region: ty::BoundRegion::BrEnv,
307     });
308
309     let region = tcx.mk_region(region);
310
311     let ref_gen_ty = tcx.mk_ref(region, ty::TypeAndMut {
312         ty: gen_ty,
313         mutbl: hir::MutMutable
314     });
315
316     // Replace the by value generator argument
317     mir.local_decls.raw[1].ty = ref_gen_ty;
318
319     // Add a deref to accesses of the generator state
320     DerefArgVisitor.visit_mir(mir);
321 }
322
323 fn make_generator_state_argument_pinned<'a, 'tcx>(
324                 tcx: TyCtxt<'a, 'tcx, 'tcx>,
325                 mir: &mut Mir<'tcx>) {
326     let ref_gen_ty = mir.local_decls.raw[1].ty;
327
328     let pin_did = tcx.lang_items().pin_type().unwrap();
329     let pin_adt_ref = tcx.adt_def(pin_did);
330     let substs = tcx.intern_substs(&[ref_gen_ty.into()]);
331     let pin_ref_gen_ty = tcx.mk_adt(pin_adt_ref, substs);
332
333     // Replace the by ref generator argument
334     mir.local_decls.raw[1].ty = pin_ref_gen_ty;
335
336     // Add the Pin field access to accesses of the generator state
337     PinArgVisitor { ref_gen_ty }.visit_mir(mir);
338 }
339
340 fn replace_result_variable<'tcx>(
341     ret_ty: Ty<'tcx>,
342     mir: &mut Mir<'tcx>,
343 ) -> Local {
344     let source_info = source_info(mir);
345     let new_ret = LocalDecl {
346         mutability: Mutability::Mut,
347         ty: ret_ty,
348         user_ty: UserTypeProjections::none(),
349         name: None,
350         source_info,
351         visibility_scope: source_info.scope,
352         internal: false,
353         is_block_tail: None,
354         is_user_variable: None,
355     };
356     let new_ret_local = Local::new(mir.local_decls.len());
357     mir.local_decls.push(new_ret);
358     mir.local_decls.swap(RETURN_PLACE, new_ret_local);
359
360     RenameLocalVisitor {
361         from: RETURN_PLACE,
362         to: new_ret_local,
363     }.visit_mir(mir);
364
365     new_ret_local
366 }
367
368 struct StorageIgnored(liveness::LiveVarSet);
369
370 impl<'tcx> Visitor<'tcx> for StorageIgnored {
371     fn visit_statement(&mut self,
372                        _block: BasicBlock,
373                        statement: &Statement<'tcx>,
374                        _location: Location) {
375         match statement.kind {
376             StatementKind::StorageLive(l) |
377             StatementKind::StorageDead(l) => { self.0.remove(l); }
378             _ => (),
379         }
380     }
381 }
382
383 fn locals_live_across_suspend_points(
384     tcx: TyCtxt<'a, 'tcx, 'tcx>,
385     mir: &Mir<'tcx>,
386     source: MirSource<'tcx>,
387     movable: bool,
388 ) -> (
389     liveness::LiveVarSet,
390     FxHashMap<BasicBlock, liveness::LiveVarSet>,
391 ) {
392     let dead_unwinds = BitSet::new_empty(mir.basic_blocks().len());
393     let def_id = source.def_id();
394
395     // Calculate when MIR locals have live storage. This gives us an upper bound of their
396     // lifetimes.
397     let storage_live_analysis = MaybeStorageLive::new(mir);
398     let storage_live =
399         do_dataflow(tcx, mir, def_id, &[], &dead_unwinds, storage_live_analysis,
400                     |bd, p| DebugFormatted::new(&bd.mir().local_decls[p]));
401
402     // Find the MIR locals which do not use StorageLive/StorageDead statements.
403     // The storage of these locals are always live.
404     let mut ignored = StorageIgnored(BitSet::new_filled(mir.local_decls.len()));
405     ignored.visit_mir(mir);
406
407     // Calculate the MIR locals which have been previously
408     // borrowed (even if they are still active).
409     // This is only used for immovable generators.
410     let borrowed_locals = if !movable {
411         let analysis = HaveBeenBorrowedLocals::new(mir);
412         let result =
413             do_dataflow(tcx, mir, def_id, &[], &dead_unwinds, analysis,
414                         |bd, p| DebugFormatted::new(&bd.mir().local_decls[p]));
415         Some((analysis, result))
416     } else {
417         None
418     };
419
420     // Calculate the liveness of MIR locals ignoring borrows.
421     let mut set = liveness::LiveVarSet::new_empty(mir.local_decls.len());
422     let mut liveness = liveness::liveness_of_locals(
423         mir,
424     );
425     liveness::dump_mir(
426         tcx,
427         "generator_liveness",
428         source,
429         mir,
430         &liveness,
431     );
432
433     let mut storage_liveness_map = FxHashMap::default();
434
435     for (block, data) in mir.basic_blocks().iter_enumerated() {
436         if let TerminatorKind::Yield { .. } = data.terminator().kind {
437             let loc = Location {
438                 block: block,
439                 statement_index: data.statements.len(),
440             };
441
442             if let Some((ref analysis, ref result)) = borrowed_locals {
443                 let borrowed_locals = state_for_location(loc,
444                                                          analysis,
445                                                          result,
446                                                          mir);
447                 // The `liveness` variable contains the liveness of MIR locals ignoring borrows.
448                 // This is correct for movable generators since borrows cannot live across
449                 // suspension points. However for immovable generators we need to account for
450                 // borrows, so we conseratively assume that all borrowed locals are live until
451                 // we find a StorageDead statement referencing the locals.
452                 // To do this we just union our `liveness` result with `borrowed_locals`, which
453                 // contains all the locals which has been borrowed before this suspension point.
454                 // If a borrow is converted to a raw reference, we must also assume that it lives
455                 // forever. Note that the final liveness is still bounded by the storage liveness
456                 // of the local, which happens using the `intersect` operation below.
457                 liveness.outs[block].union(&borrowed_locals);
458             }
459
460             let mut storage_liveness = state_for_location(loc,
461                                                           &storage_live_analysis,
462                                                           &storage_live,
463                                                           mir);
464
465             // Store the storage liveness for later use so we can restore the state
466             // after a suspension point
467             storage_liveness_map.insert(block, storage_liveness.clone());
468
469             // Mark locals without storage statements as always having live storage
470             storage_liveness.union(&ignored.0);
471
472             // Locals live are live at this point only if they are used across
473             // suspension points (the `liveness` variable)
474             // and their storage is live (the `storage_liveness` variable)
475             storage_liveness.intersect(&liveness.outs[block]);
476
477             let live_locals = storage_liveness;
478
479             // Add the locals life at this suspension point to the set of locals which live across
480             // any suspension points
481             set.union(&live_locals);
482         }
483     }
484
485     // The generator argument is ignored
486     set.remove(self_arg());
487
488     (set, storage_liveness_map)
489 }
490
491 fn compute_layout<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
492                             source: MirSource<'tcx>,
493                             upvars: Vec<Ty<'tcx>>,
494                             interior: Ty<'tcx>,
495                             movable: bool,
496                             mir: &mut Mir<'tcx>)
497     -> (FxHashMap<Local, (Ty<'tcx>, usize)>,
498         GeneratorLayout<'tcx>,
499         FxHashMap<BasicBlock, liveness::LiveVarSet>)
500 {
501     // Use a liveness analysis to compute locals which are live across a suspension point
502     let (live_locals, storage_liveness) = locals_live_across_suspend_points(tcx,
503                                                                             mir,
504                                                                             source,
505                                                                             movable);
506     // Erase regions from the types passed in from typeck so we can compare them with
507     // MIR types
508     let allowed_upvars = tcx.erase_regions(&upvars);
509     let allowed = match interior.sty {
510         ty::GeneratorWitness(s) => tcx.erase_late_bound_regions(&s),
511         _ => bug!(),
512     };
513
514     for (local, decl) in mir.local_decls.iter_enumerated() {
515         // Ignore locals which are internal or not live
516         if !live_locals.contains(local) || decl.internal {
517             continue;
518         }
519
520         // Sanity check that typeck knows about the type of locals which are
521         // live across a suspension point
522         if !allowed.contains(&decl.ty) && !allowed_upvars.contains(&decl.ty) {
523             span_bug!(mir.span,
524                       "Broken MIR: generator contains type {} in MIR, \
525                        but typeck only knows about {}",
526                       decl.ty,
527                       interior);
528         }
529     }
530
531     let upvar_len = mir.upvar_decls.len();
532     let dummy_local = LocalDecl::new_internal(tcx.mk_unit(), mir.span);
533
534     // Gather live locals and their indices replacing values in mir.local_decls with a dummy
535     // to avoid changing local indices
536     let live_decls = live_locals.iter().map(|local| {
537         let var = mem::replace(&mut mir.local_decls[local], dummy_local.clone());
538         (local, var)
539     });
540
541     // Create a map from local indices to generator struct indices.
542     // These are offset by (upvar_len + 1) because of fields which comes before locals.
543     // We also create a vector of the LocalDecls of these locals.
544     let (remap, vars) = live_decls.enumerate().map(|(idx, (local, var))| {
545         ((local, (var.ty, upvar_len + 1 + idx)), var)
546     }).unzip();
547
548     let layout = GeneratorLayout {
549         fields: vars
550     };
551
552     (remap, layout, storage_liveness)
553 }
554
555 fn insert_switch<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
556                            mir: &mut Mir<'tcx>,
557                            cases: Vec<(u32, BasicBlock)>,
558                            transform: &TransformVisitor<'a, 'tcx>,
559                            default: TerminatorKind<'tcx>) {
560     let default_block = insert_term_block(mir, default);
561
562     let switch = TerminatorKind::SwitchInt {
563         discr: Operand::Copy(transform.make_field(transform.state_field, tcx.types.u32)),
564         switch_ty: tcx.types.u32,
565         values: Cow::from(cases.iter().map(|&(i, _)| i.into()).collect::<Vec<_>>()),
566         targets: cases.iter().map(|&(_, d)| d).chain(once(default_block)).collect(),
567     };
568
569     let source_info = source_info(mir);
570     mir.basic_blocks_mut().raw.insert(0, BasicBlockData {
571         statements: Vec::new(),
572         terminator: Some(Terminator {
573             source_info,
574             kind: switch,
575         }),
576         is_cleanup: false,
577     });
578
579     let blocks = mir.basic_blocks_mut().iter_mut();
580
581     for target in blocks.flat_map(|b| b.terminator_mut().successors_mut()) {
582         *target = BasicBlock::new(target.index() + 1);
583     }
584 }
585
586 fn elaborate_generator_drops<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
587                                        def_id: DefId,
588                                        mir: &mut Mir<'tcx>) {
589     use crate::util::elaborate_drops::{elaborate_drop, Unwind};
590     use crate::util::patch::MirPatch;
591     use crate::shim::DropShimElaborator;
592
593     // Note that `elaborate_drops` only drops the upvars of a generator, and
594     // this is ok because `open_drop` can only be reached within that own
595     // generator's resume function.
596
597     let param_env = tcx.param_env(def_id);
598     let gen = self_arg();
599
600     let mut elaborator = DropShimElaborator {
601         mir: mir,
602         patch: MirPatch::new(mir),
603         tcx,
604         param_env
605     };
606
607     for (block, block_data) in mir.basic_blocks().iter_enumerated() {
608         let (target, unwind, source_info) = match block_data.terminator() {
609             &Terminator {
610                 source_info,
611                 kind: TerminatorKind::Drop {
612                     location: Place::Base(PlaceBase::Local(local)),
613                     target,
614                     unwind
615                 }
616             } if local == gen => (target, unwind, source_info),
617             _ => continue,
618         };
619         let unwind = if block_data.is_cleanup {
620             Unwind::InCleanup
621         } else {
622             Unwind::To(unwind.unwrap_or_else(|| elaborator.patch.resume_block()))
623         };
624         elaborate_drop(
625             &mut elaborator,
626             source_info,
627             &Place::Base(PlaceBase::Local(gen)),
628             (),
629             target,
630             unwind,
631             block,
632         );
633     }
634     elaborator.patch.apply(mir);
635 }
636
637 fn create_generator_drop_shim<'a, 'tcx>(
638                 tcx: TyCtxt<'a, 'tcx, 'tcx>,
639                 transform: &TransformVisitor<'a, 'tcx>,
640                 def_id: DefId,
641                 source: MirSource<'tcx>,
642                 gen_ty: Ty<'tcx>,
643                 mir: &Mir<'tcx>,
644                 drop_clean: BasicBlock) -> Mir<'tcx> {
645     let mut mir = mir.clone();
646
647     let source_info = source_info(&mir);
648
649     let mut cases = create_cases(&mut mir, transform, |point| point.drop);
650
651     cases.insert(0, (UNRESUMED, drop_clean));
652
653     // The returned state and the poisoned state fall through to the default
654     // case which is just to return
655
656     insert_switch(tcx, &mut mir, cases, &transform, TerminatorKind::Return);
657
658     for block in mir.basic_blocks_mut() {
659         let kind = &mut block.terminator_mut().kind;
660         if let TerminatorKind::GeneratorDrop = *kind {
661             *kind = TerminatorKind::Return;
662         }
663     }
664
665     // Replace the return variable
666     mir.local_decls[RETURN_PLACE] = LocalDecl {
667         mutability: Mutability::Mut,
668         ty: tcx.mk_unit(),
669         user_ty: UserTypeProjections::none(),
670         name: None,
671         source_info,
672         visibility_scope: source_info.scope,
673         internal: false,
674         is_block_tail: None,
675         is_user_variable: None,
676     };
677
678     make_generator_state_argument_indirect(tcx, def_id, &mut mir);
679
680     // Change the generator argument from &mut to *mut
681     mir.local_decls[self_arg()] = LocalDecl {
682         mutability: Mutability::Mut,
683         ty: tcx.mk_ptr(ty::TypeAndMut {
684             ty: gen_ty,
685             mutbl: hir::Mutability::MutMutable,
686         }),
687         user_ty: UserTypeProjections::none(),
688         name: None,
689         source_info,
690         visibility_scope: source_info.scope,
691         internal: false,
692         is_block_tail: None,
693         is_user_variable: None,
694     };
695     if tcx.sess.opts.debugging_opts.mir_emit_retag {
696         // Alias tracking must know we changed the type
697         mir.basic_blocks_mut()[START_BLOCK].statements.insert(0, Statement {
698             source_info,
699             kind: StatementKind::Retag(RetagKind::Raw, Place::Base(PlaceBase::Local(self_arg()))),
700         })
701     }
702
703     no_landing_pads(tcx, &mut mir);
704
705     // Make sure we remove dead blocks to remove
706     // unrelated code from the resume part of the function
707     simplify::remove_dead_blocks(&mut mir);
708
709     dump_mir(tcx, None, "generator_drop", &0, source, &mut mir, |_, _| Ok(()) );
710
711     mir
712 }
713
714 fn insert_term_block<'tcx>(mir: &mut Mir<'tcx>, kind: TerminatorKind<'tcx>) -> BasicBlock {
715     let term_block = BasicBlock::new(mir.basic_blocks().len());
716     let source_info = source_info(mir);
717     mir.basic_blocks_mut().push(BasicBlockData {
718         statements: Vec::new(),
719         terminator: Some(Terminator {
720             source_info,
721             kind,
722         }),
723         is_cleanup: false,
724     });
725     term_block
726 }
727
728 fn insert_panic_block<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
729                                 mir: &mut Mir<'tcx>,
730                                 message: AssertMessage<'tcx>) -> BasicBlock {
731     let assert_block = BasicBlock::new(mir.basic_blocks().len());
732     let term = TerminatorKind::Assert {
733         cond: Operand::Constant(box Constant {
734             span: mir.span,
735             ty: tcx.types.bool,
736             user_ty: None,
737             literal: tcx.mk_const(
738                 ty::Const::from_bool(tcx, false),
739             ),
740         }),
741         expected: true,
742         msg: message,
743         target: assert_block,
744         cleanup: None,
745     };
746
747     let source_info = source_info(mir);
748     mir.basic_blocks_mut().push(BasicBlockData {
749         statements: Vec::new(),
750         terminator: Some(Terminator {
751             source_info,
752             kind: term,
753         }),
754         is_cleanup: false,
755     });
756
757     assert_block
758 }
759
760 fn create_generator_resume_function<'a, 'tcx>(
761         tcx: TyCtxt<'a, 'tcx, 'tcx>,
762         transform: TransformVisitor<'a, 'tcx>,
763         def_id: DefId,
764         source: MirSource<'tcx>,
765         mir: &mut Mir<'tcx>) {
766     // Poison the generator when it unwinds
767     for block in mir.basic_blocks_mut() {
768         let source_info = block.terminator().source_info;
769         if let &TerminatorKind::Resume = &block.terminator().kind {
770             block.statements.push(transform.set_state(POISONED, source_info));
771         }
772     }
773
774     let mut cases = create_cases(mir, &transform, |point| Some(point.resume));
775
776     use rustc::mir::interpret::EvalErrorKind::{
777         GeneratorResumedAfterPanic,
778         GeneratorResumedAfterReturn,
779     };
780
781     // Jump to the entry point on the unresumed
782     cases.insert(0, (UNRESUMED, BasicBlock::new(0)));
783     // Panic when resumed on the returned state
784     cases.insert(1, (RETURNED, insert_panic_block(tcx, mir, GeneratorResumedAfterReturn)));
785     // Panic when resumed on the poisoned state
786     cases.insert(2, (POISONED, insert_panic_block(tcx, mir, GeneratorResumedAfterPanic)));
787
788     insert_switch(tcx, mir, cases, &transform, TerminatorKind::Unreachable);
789
790     make_generator_state_argument_indirect(tcx, def_id, mir);
791     make_generator_state_argument_pinned(tcx, mir);
792
793     no_landing_pads(tcx, mir);
794
795     // Make sure we remove dead blocks to remove
796     // unrelated code from the drop part of the function
797     simplify::remove_dead_blocks(mir);
798
799     dump_mir(tcx, None, "generator_resume", &0, source, mir, |_, _| Ok(()) );
800 }
801
802 fn source_info<'a, 'tcx>(mir: &Mir<'tcx>) -> SourceInfo {
803     SourceInfo {
804         span: mir.span,
805         scope: OUTERMOST_SOURCE_SCOPE,
806     }
807 }
808
809 fn insert_clean_drop<'a, 'tcx>(mir: &mut Mir<'tcx>) -> BasicBlock {
810     let return_block = insert_term_block(mir, TerminatorKind::Return);
811
812     // Create a block to destroy an unresumed generators. This can only destroy upvars.
813     let drop_clean = BasicBlock::new(mir.basic_blocks().len());
814     let term = TerminatorKind::Drop {
815         location: Place::Base(PlaceBase::Local(self_arg())),
816         target: return_block,
817         unwind: None,
818     };
819     let source_info = source_info(mir);
820     mir.basic_blocks_mut().push(BasicBlockData {
821         statements: Vec::new(),
822         terminator: Some(Terminator {
823             source_info,
824             kind: term,
825         }),
826         is_cleanup: false,
827     });
828
829     drop_clean
830 }
831
832 fn create_cases<'a, 'tcx, F>(mir: &mut Mir<'tcx>,
833                           transform: &TransformVisitor<'a, 'tcx>,
834                           target: F) -> Vec<(u32, BasicBlock)>
835     where F: Fn(&SuspensionPoint) -> Option<BasicBlock> {
836     let source_info = source_info(mir);
837
838     transform.suspension_points.iter().filter_map(|point| {
839         // Find the target for this suspension point, if applicable
840         target(point).map(|target| {
841             let block = BasicBlock::new(mir.basic_blocks().len());
842             let mut statements = Vec::new();
843
844             // Create StorageLive instructions for locals with live storage
845             for i in 0..(mir.local_decls.len()) {
846                 let l = Local::new(i);
847                 if point.storage_liveness.contains(l) && !transform.remap.contains_key(&l) {
848                     statements.push(Statement {
849                         source_info,
850                         kind: StatementKind::StorageLive(l),
851                     });
852                 }
853             }
854
855             // Then jump to the real target
856             mir.basic_blocks_mut().push(BasicBlockData {
857                 statements,
858                 terminator: Some(Terminator {
859                     source_info,
860                     kind: TerminatorKind::Goto {
861                         target,
862                     },
863                 }),
864                 is_cleanup: false,
865             });
866
867             (point.state, block)
868         })
869     }).collect()
870 }
871
872 impl MirPass for StateTransform {
873     fn run_pass<'a, 'tcx>(&self,
874                     tcx: TyCtxt<'a, 'tcx, 'tcx>,
875                     source: MirSource<'tcx>,
876                     mir: &mut Mir<'tcx>) {
877         let yield_ty = if let Some(yield_ty) = mir.yield_ty {
878             yield_ty
879         } else {
880             // This only applies to generators
881             return
882         };
883
884         assert!(mir.generator_drop.is_none());
885
886         let def_id = source.def_id();
887
888         // The first argument is the generator type passed by value
889         let gen_ty = mir.local_decls.raw[1].ty;
890
891         // Get the interior types and substs which typeck computed
892         let (upvars, interior, movable) = match gen_ty.sty {
893             ty::Generator(_, substs, movability) => {
894                 (substs.upvar_tys(def_id, tcx).collect(),
895                  substs.witness(def_id, tcx),
896                  movability == hir::GeneratorMovability::Movable)
897             }
898             _ => bug!(),
899         };
900
901         // Compute GeneratorState<yield_ty, return_ty>
902         let state_did = tcx.lang_items().gen_state().unwrap();
903         let state_adt_ref = tcx.adt_def(state_did);
904         let state_substs = tcx.intern_substs(&[
905             yield_ty.into(),
906             mir.return_ty().into(),
907         ]);
908         let ret_ty = tcx.mk_adt(state_adt_ref, state_substs);
909
910         // We rename RETURN_PLACE which has type mir.return_ty to new_ret_local
911         // RETURN_PLACE then is a fresh unused local with type ret_ty.
912         let new_ret_local = replace_result_variable(ret_ty, mir);
913
914         // Extract locals which are live across suspension point into `layout`
915         // `remap` gives a mapping from local indices onto generator struct indices
916         // `storage_liveness` tells us which locals have live storage at suspension points
917         let (remap, layout, storage_liveness) = compute_layout(
918             tcx,
919             source,
920             upvars,
921             interior,
922             movable,
923             mir);
924
925         let state_field = mir.upvar_decls.len();
926
927         // Run the transformation which converts Places from Local to generator struct
928         // accesses for locals in `remap`.
929         // It also rewrites `return x` and `yield y` as writing a new generator state and returning
930         // GeneratorState::Complete(x) and GeneratorState::Yielded(y) respectively.
931         let mut transform = TransformVisitor {
932             tcx,
933             state_adt_ref,
934             state_substs,
935             remap,
936             storage_liveness,
937             suspension_points: Vec::new(),
938             new_ret_local,
939             state_field,
940         };
941         transform.visit_mir(mir);
942
943         // Update our MIR struct to reflect the changed we've made
944         mir.yield_ty = None;
945         mir.arg_count = 1;
946         mir.spread_arg = None;
947         mir.generator_layout = Some(layout);
948
949         // Insert `drop(generator_struct)` which is used to drop upvars for generators in
950         // the unresumed state.
951         // This is expanded to a drop ladder in `elaborate_generator_drops`.
952         let drop_clean = insert_clean_drop(mir);
953
954         dump_mir(tcx, None, "generator_pre-elab", &0, source, mir, |_, _| Ok(()) );
955
956         // Expand `drop(generator_struct)` to a drop ladder which destroys upvars.
957         // If any upvars are moved out of, drop elaboration will handle upvar destruction.
958         // However we need to also elaborate the code generated by `insert_clean_drop`.
959         elaborate_generator_drops(tcx, def_id, mir);
960
961         dump_mir(tcx, None, "generator_post-transform", &0, source, mir, |_, _| Ok(()) );
962
963         // Create a copy of our MIR and use it to create the drop shim for the generator
964         let drop_shim = create_generator_drop_shim(tcx,
965             &transform,
966             def_id,
967             source,
968             gen_ty,
969             &mir,
970             drop_clean);
971
972         mir.generator_drop = Some(box drop_shim);
973
974         // Create the Generator::resume function
975         create_generator_resume_function(tcx, transform, def_id, source, mir);
976     }
977 }