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