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