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