]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/generator.rs
3be21b72731e96b5e753c674285e7f7394e15b6f
[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::transform::{MirPass, MirSource};
67 use rustc::mir::visit::{LvalueContext, Visitor, MutVisitor};
68 use rustc::ty::{self, TyCtxt, AdtDef, Ty, GeneratorInterior};
69 use rustc::ty::subst::{Kind, Substs};
70 use util::dump_mir;
71 use util::liveness;
72 use rustc_const_math::ConstInt;
73 use rustc_data_structures::indexed_vec::Idx;
74 use rustc_data_structures::indexed_set::IdxSetBuf;
75 use std::collections::HashMap;
76 use std::borrow::Cow;
77 use std::iter::once;
78 use std::mem;
79 use transform::simplify;
80 use transform::no_landing_pads::no_landing_pads;
81 use dataflow::{self, MaybeStorageLive, state_for_location};
82
83 pub struct StateTransform;
84
85 struct RenameLocalVisitor {
86     from: Local,
87     to: Local,
88 }
89
90 impl<'tcx> MutVisitor<'tcx> for RenameLocalVisitor {
91     fn visit_local(&mut self,
92                    local: &mut Local,
93                    _: LvalueContext<'tcx>,
94                    _: Location) {
95         if *local == self.from {
96             *local = self.to;
97         }
98     }
99 }
100
101 struct DerefArgVisitor;
102
103 impl<'tcx> MutVisitor<'tcx> for DerefArgVisitor {
104     fn visit_local(&mut self,
105                    local: &mut Local,
106                    _: LvalueContext<'tcx>,
107                    _: Location) {
108         assert_ne!(*local, self_arg());
109     }
110
111     fn visit_lvalue(&mut self,
112                     lvalue: &mut Lvalue<'tcx>,
113                     context: LvalueContext<'tcx>,
114                     location: Location) {
115         if *lvalue == Lvalue::Local(self_arg()) {
116             *lvalue = Lvalue::Projection(Box::new(Projection {
117                 base: lvalue.clone(),
118                 elem: ProjectionElem::Deref,
119             }));
120         } else {
121             self.super_lvalue(lvalue, context, location);
122         }
123     }
124 }
125
126 fn self_arg() -> Local {
127     Local::new(1)
128 }
129
130 struct SuspensionPoint {
131     state: u32,
132     resume: BasicBlock,
133     drop: Option<BasicBlock>,
134     storage_liveness: liveness::LocalSet,
135     storage_live: Option<BasicBlock>,
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     mir_local_count: usize,
150
151     // A map from a suspension point in a block to the locals which have live storage at that point
152     storage_liveness: HashMap<BasicBlock, liveness::LocalSet>,
153
154     // A list of suspension points, generated during the transform
155     suspension_points: Vec<SuspensionPoint>,
156
157     // The original RETURN_POINTER local
158     new_ret_local: Local,
159 }
160
161 impl<'a, 'tcx> TransformVisitor<'a, 'tcx> {
162     // Make a GeneratorState rvalue
163     fn make_state(&self, idx: usize, val: Operand<'tcx>) -> Rvalue<'tcx> {
164         let adt = AggregateKind::Adt(self.state_adt_ref, idx, self.state_substs, None);
165         Rvalue::Aggregate(box adt, vec![val])
166     }
167
168     // Create a Lvalue referencing a generator struct field
169     fn make_field(&self, idx: usize, ty: Ty<'tcx>) -> Lvalue<'tcx> {
170         let base = Lvalue::Local(self_arg());
171         let field = Projection {
172             base: base,
173             elem: ProjectionElem::Field(Field::new(idx), ty),
174         };
175         Lvalue::Projection(Box::new(field))
176     }
177
178     // Create a statement which changes the generator state
179     fn set_state(&self, state_disc: u32, source_info: SourceInfo) -> Statement<'tcx> {
180         let state = self.make_field(self.state_field, self.tcx.types.u32);
181         let val = Operand::Constant(box Constant {
182             span: source_info.span,
183             ty: self.tcx.types.u32,
184             literal: Literal::Value {
185                 value: self.tcx.mk_const(ty::Const {
186                     val: ConstVal::Integral(ConstInt::U32(state_disc)),
187                     ty: self.tcx.types.u32
188                 }),
189             },
190         });
191         Statement {
192             source_info,
193             kind: StatementKind::Assign(state, Rvalue::Use(val)),
194         }
195     }
196 }
197
198 impl<'a, 'tcx> MutVisitor<'tcx> for TransformVisitor<'a, 'tcx> {
199     fn visit_local(&mut self,
200                    local: &mut Local,
201                    _: LvalueContext<'tcx>,
202                    _: Location) {
203         assert_eq!(self.remap.get(local), None);
204     }
205
206     fn visit_lvalue(&mut self,
207                     lvalue: &mut Lvalue<'tcx>,
208                     context: LvalueContext<'tcx>,
209                     location: Location) {
210         if let Lvalue::Local(l) = *lvalue {
211             // Replace an Local in the remap with a generator struct access
212             if let Some(&(ty, idx)) = self.remap.get(&l) {
213                 *lvalue = self.make_field(idx, ty);
214             }
215         } else {
216             self.super_lvalue(lvalue, context, location);
217         }
218     }
219
220     fn visit_basic_block_data(&mut self,
221                               block: BasicBlock,
222                               data: &mut BasicBlockData<'tcx>) {
223         // Remove StorageLive and StorageDead statements for remapped locals
224         data.retain_statements(|s| {
225             match s.kind {
226                 StatementKind::StorageLive(l) | StatementKind::StorageDead(l) => {
227                     !self.remap.contains_key(&l)
228                 }
229                 _ => true
230             }
231         });
232
233         let ret_val = match data.terminator().kind {
234             TerminatorKind::Return => Some((1,
235                 None,
236                 Operand::Consume(Lvalue::Local(self.new_ret_local)),
237                 None)),
238             TerminatorKind::Yield { ref value, resume, drop } => Some((0,
239                 Some(resume),
240                 value.clone(),
241                 drop)),
242             _ => None
243         };
244
245         if let Some((state_idx, resume, v, drop)) = ret_val {
246             let source_info = data.terminator().source_info;
247             let state = if let Some(resume) = resume { // Yield
248                 let state = 3 + self.suspension_points.len() as u32;
249
250                 let liveness = self.storage_liveness.get(&block).unwrap();
251
252                 for i in 0..(self.mir_local_count) {
253                     let l = Local::new(i);
254                     if liveness.contains(&l) && !self.remap.contains_key(&l) {
255                         data.statements.push(Statement {
256                             source_info,
257                             kind: StatementKind::StorageDead(l),
258                         });
259                     }
260                 }
261
262                 self.suspension_points.push(SuspensionPoint {
263                     state,
264                     resume,
265                     drop,
266                     storage_liveness: liveness.clone(),
267                     storage_live: None,
268                 });
269
270                 state
271             } else { // Return
272                  1 // state for returned
273             };
274             data.statements.push(self.set_state(state, source_info));
275             data.statements.push(Statement {
276                 source_info,
277                 kind: StatementKind::Assign(Lvalue::Local(RETURN_POINTER),
278                     self.make_state(state_idx, v)),
279             });
280             data.terminator.as_mut().unwrap().kind = TerminatorKind::Return;
281         }
282
283         self.super_basic_block_data(block, data);
284     }
285 }
286
287 fn make_generator_state_argument_indirect<'a, 'tcx>(
288                 tcx: TyCtxt<'a, 'tcx, 'tcx>,
289                 def_id: DefId,
290                 mir: &mut Mir<'tcx>) {
291     let gen_ty = mir.local_decls.raw[1].ty;
292
293     let region = ty::ReFree(ty::FreeRegion {
294         scope: def_id,
295         bound_region: ty::BoundRegion::BrEnv,
296     });
297
298     let region = tcx.mk_region(region);
299
300     let ref_gen_ty = tcx.mk_ref(region, ty::TypeAndMut {
301         ty: gen_ty,
302         mutbl: hir::MutMutable
303     });
304
305     // Replace the by value generator argument
306     mir.local_decls.raw[1].ty = ref_gen_ty;
307
308     // Add a deref to accesses of the generator state
309     DerefArgVisitor.visit_mir(mir);
310 }
311
312 fn replace_result_variable<'tcx>(ret_ty: Ty<'tcx>,
313                             mir: &mut Mir<'tcx>) -> Local {
314     let new_ret = LocalDecl {
315         mutability: Mutability::Mut,
316         ty: ret_ty,
317         name: None,
318         source_info: source_info(mir),
319         internal: false,
320         is_user_variable: false,
321     };
322     let new_ret_local = Local::new(mir.local_decls.len());
323     mir.local_decls.push(new_ret);
324     mir.local_decls.swap(0, new_ret_local.index());
325
326     RenameLocalVisitor {
327         from: RETURN_POINTER,
328         to: new_ret_local,
329     }.visit_mir(mir);
330
331     new_ret_local
332 }
333
334 struct StorageIgnored(liveness::LocalSet);
335
336 impl<'tcx> Visitor<'tcx> for StorageIgnored {
337     fn visit_statement(&mut self,
338                        _block: BasicBlock,
339                        statement: &Statement<'tcx>,
340                        _location: Location) {
341         match statement.kind {
342             StatementKind::StorageLive(l) |
343             StatementKind::StorageDead(l) => { self.0.remove(&l); }
344             _ => (),
345         }
346     }
347 }
348
349 fn locals_live_across_suspend_points<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
350                                                mir: &Mir<'tcx>,
351                                                source: MirSource) ->
352                                                (liveness::LocalSet,
353                                                 HashMap<BasicBlock, liveness::LocalSet>) {
354     let dead_unwinds = IdxSetBuf::new_empty(mir.basic_blocks().len());
355     let node_id = source.item_id();
356     let analysis = MaybeStorageLive::new(mir);
357     let storage_live =
358         dataflow::do_dataflow(tcx, mir, node_id, &[], &dead_unwinds, analysis,
359                               |bd, p| &bd.mir().local_decls[p]);
360
361     let mut ignored = StorageIgnored(IdxSetBuf::new_filled(mir.basic_blocks().len()));
362     ignored.visit_mir(mir);
363
364     let mut set = liveness::LocalSet::new_empty(mir.local_decls.len());
365     let result = liveness::liveness_of_locals(mir);
366     liveness::dump_mir(tcx, "generator_liveness", source, mir, &result);
367
368     let mut storage_liveness_map = HashMap::new();
369
370     for (block, data) in mir.basic_blocks().iter_enumerated() {
371         if let TerminatorKind::Yield { .. } = data.terminator().kind {
372             let loc = Location {
373                 block: block,
374                 statement_index: data.statements.len(),
375             };
376
377             let mut storage_liveness = state_for_location(loc, &analysis, &storage_live);
378
379             storage_liveness_map.insert(block, storage_liveness.clone());
380
381             // Mark locals without storage statements as always live
382             storage_liveness.union(&ignored.0);
383
384             // Locals live are live at this point only if they are used across suspension points
385             // and their storage is live
386             storage_liveness.intersect(&result.outs[block]);
387
388             // Add the locals life at this suspension point to the set of locals which live across
389             // any suspension points
390             set.union(&storage_liveness);
391         }
392     }
393
394     // The generator argument is ignored
395     set.remove(&self_arg());
396
397     (set, storage_liveness_map)
398 }
399
400 fn compute_layout<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
401                             source: MirSource,
402                             interior: GeneratorInterior<'tcx>,
403                             mir: &mut Mir<'tcx>)
404     -> (HashMap<Local, (Ty<'tcx>, usize)>,
405         GeneratorLayout<'tcx>,
406         HashMap<BasicBlock, liveness::LocalSet>)
407 {
408     // Use a liveness analysis to compute locals which are live across a suspension point
409     let (live_locals, storage_liveness) = locals_live_across_suspend_points(tcx, mir, source);
410
411     // Erase regions from the types passed in from typeck so we can compare them with
412     // MIR types
413     let allowed = tcx.erase_regions(&interior.as_slice());
414
415     for (local, decl) in mir.local_decls.iter_enumerated() {
416         // Ignore locals which are internal or not live
417         if !live_locals.contains(&local) || decl.internal {
418             continue;
419         }
420
421         // Sanity check that typeck knows about the type of locals which are
422         // live across a suspension point
423         if !allowed.contains(&decl.ty) {
424             span_bug!(mir.span,
425                       "Broken MIR: generator contains type {} in MIR, \
426                        but typeck only knows about {}",
427                       decl.ty,
428                       interior);
429         }
430     }
431
432     let upvar_len = mir.upvar_decls.len();
433     let dummy_local = LocalDecl::new_internal(tcx.mk_nil(), mir.span);
434
435     // Gather live locals and their indices replacing values in mir.local_decls with a dummy
436     // to avoid changing local indices
437     let live_decls = live_locals.iter().map(|local| {
438         let var = mem::replace(&mut mir.local_decls[local], dummy_local.clone());
439         (local, var)
440     });
441
442     // Create a map from local indices to generator struct indices.
443     // These are offset by (upvar_len + 1) because of fields which comes before locals.
444     // We also create a vector of the LocalDecls of these locals.
445     let (remap, vars) = live_decls.enumerate().map(|(idx, (local, var))| {
446         ((local, (var.ty, upvar_len + 1 + idx)), var)
447     }).unzip();
448
449     let layout = GeneratorLayout {
450         fields: vars
451     };
452
453     (remap, layout, storage_liveness)
454 }
455
456 fn insert_switch<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
457                            mir: &mut Mir<'tcx>,
458                            cases: Vec<(u32, BasicBlock)>,
459                            transform: &TransformVisitor<'a, 'tcx>) {
460     let return_block = insert_return_block(mir);
461
462     let switch = TerminatorKind::SwitchInt {
463         discr: Operand::Consume(transform.make_field(transform.state_field, tcx.types.u32)),
464         switch_ty: tcx.types.u32,
465         values: Cow::from(cases.iter().map(|&(i, _)| ConstInt::U32(i)).collect::<Vec<_>>()),
466         targets: cases.iter().map(|&(_, d)| d).chain(once(return_block)).collect(),
467     };
468
469     let source_info = source_info(mir);
470     mir.basic_blocks_mut().raw.insert(0, BasicBlockData {
471         statements: Vec::new(),
472         terminator: Some(Terminator {
473             source_info,
474             kind: switch,
475         }),
476         is_cleanup: false,
477     });
478
479     let blocks = mir.basic_blocks_mut().iter_mut();
480
481     for target in blocks.flat_map(|b| b.terminator_mut().successors_mut()) {
482         *target = BasicBlock::new(target.index() + 1);
483     }
484 }
485
486 fn elaborate_generator_drops<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
487                                        def_id: DefId,
488                                        mir: &mut Mir<'tcx>) {
489     use util::elaborate_drops::{elaborate_drop, Unwind};
490     use util::patch::MirPatch;
491     use shim::DropShimElaborator;
492
493     // Note that `elaborate_drops` only drops the upvars of a generator, and
494     // this is ok because `open_drop` can only be reached within that own
495     // generator's resume function.
496
497     let param_env = tcx.param_env(def_id);
498     let gen = self_arg();
499
500     for block in mir.basic_blocks().indices() {
501         let (target, unwind, source_info) = match mir.basic_blocks()[block].terminator() {
502             &Terminator {
503                 source_info,
504                 kind: TerminatorKind::Drop {
505                     location: Lvalue::Local(local),
506                     target,
507                     unwind
508                 }
509             } if local == gen => (target, unwind, source_info),
510             _ => continue,
511         };
512         let unwind = if let Some(unwind) = unwind {
513             Unwind::To(unwind)
514         } else {
515             Unwind::InCleanup
516         };
517         let patch = {
518             let mut elaborator = DropShimElaborator {
519                 mir: &mir,
520                 patch: MirPatch::new(mir),
521                 tcx,
522                 param_env
523             };
524             elaborate_drop(
525                 &mut elaborator,
526                 source_info,
527                 &Lvalue::Local(gen),
528                 (),
529                 target,
530                 unwind,
531                 block
532             );
533             elaborator.patch
534         };
535         patch.apply(mir);
536     }
537 }
538
539 fn create_generator_drop_shim<'a, 'tcx>(
540                 tcx: TyCtxt<'a, 'tcx, 'tcx>,
541                 transform: &TransformVisitor<'a, 'tcx>,
542                 def_id: DefId,
543                 source: MirSource,
544                 gen_ty: Ty<'tcx>,
545                 mir: &Mir<'tcx>,
546                 drop_clean: BasicBlock) -> Mir<'tcx> {
547     let mut mir = mir.clone();
548
549     let source_info = source_info(&mir);
550
551     let mut cases: Vec<_> = transform.suspension_points.iter().filter_map(|point| {
552         point.drop.map(|drop| {
553             // Make the point's storage live block goto the drop block
554             let block = point.storage_live.unwrap();
555             let term = Terminator {
556                 source_info,
557                 kind: TerminatorKind::Goto {
558                     target: drop,
559                 },
560             };
561             mir.basic_blocks_mut()[block].terminator = Some(term);
562             (point.state, block)
563         })
564     }).collect();
565
566     cases.insert(0, (0, drop_clean));
567
568     // The returned state 1 and the  poisoned state 2 falls through to
569     // the default case which is just to return
570
571     insert_switch(tcx, &mut mir, cases, &transform);
572
573     for block in mir.basic_blocks_mut() {
574         let kind = &mut block.terminator_mut().kind;
575         if let TerminatorKind::GeneratorDrop = *kind {
576             *kind = TerminatorKind::Return;
577         }
578     }
579
580     // Replace the return variable
581     mir.return_ty = tcx.mk_nil();
582     mir.local_decls[RETURN_POINTER] = LocalDecl {
583         mutability: Mutability::Mut,
584         ty: tcx.mk_nil(),
585         name: None,
586         source_info,
587         internal: false,
588         is_user_variable: false,
589     };
590
591     make_generator_state_argument_indirect(tcx, def_id, &mut mir);
592
593     // Change the generator argument from &mut to *mut
594     mir.local_decls[self_arg()] = LocalDecl {
595         mutability: Mutability::Mut,
596         ty: tcx.mk_ptr(ty::TypeAndMut {
597             ty: gen_ty,
598             mutbl: hir::Mutability::MutMutable,
599         }),
600         name: None,
601         source_info,
602         internal: false,
603         is_user_variable: false,
604     };
605
606     no_landing_pads(tcx, &mut mir);
607
608     // Make sure we remove dead blocks to remove
609     // unrelated code from the resume part of the function
610     simplify::remove_dead_blocks(&mut mir);
611
612     dump_mir(tcx, None, "generator_drop", &0, source, &mut mir);
613
614     mir
615 }
616
617 fn insert_return_block<'tcx>(mir: &mut Mir<'tcx>) -> BasicBlock {
618     let return_block = BasicBlock::new(mir.basic_blocks().len());
619     let source_info = source_info(mir);
620     mir.basic_blocks_mut().push(BasicBlockData {
621         statements: Vec::new(),
622         terminator: Some(Terminator {
623             source_info,
624             kind: TerminatorKind::Return,
625         }),
626         is_cleanup: false,
627     });
628     return_block
629 }
630
631 fn insert_panic_block<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
632                                 mir: &mut Mir<'tcx>,
633                                 message: AssertMessage<'tcx>) -> BasicBlock {
634     let assert_block = BasicBlock::new(mir.basic_blocks().len());
635     let term = TerminatorKind::Assert {
636         cond: Operand::Constant(box Constant {
637             span: mir.span,
638             ty: tcx.types.bool,
639             literal: Literal::Value {
640                 value: tcx.mk_const(ty::Const {
641                     val: ConstVal::Bool(false),
642                     ty: tcx.types.bool
643                 }),
644             },
645         }),
646         expected: true,
647         msg: message,
648         target: assert_block,
649         cleanup: None,
650     };
651
652     let source_info = source_info(mir);
653     mir.basic_blocks_mut().push(BasicBlockData {
654         statements: Vec::new(),
655         terminator: Some(Terminator {
656             source_info,
657             kind: term,
658         }),
659         is_cleanup: false,
660     });
661
662     assert_block
663 }
664
665 fn create_generator_resume_function<'a, 'tcx>(
666         tcx: TyCtxt<'a, 'tcx, 'tcx>,
667         transform: TransformVisitor<'a, 'tcx>,
668         def_id: DefId,
669         source: MirSource,
670         mir: &mut Mir<'tcx>) {
671     // Poison the generator when it unwinds
672     for block in mir.basic_blocks_mut() {
673         let source_info = block.terminator().source_info;
674         if let &TerminatorKind::Resume = &block.terminator().kind {
675             block.statements.push(transform.set_state(1, source_info));
676         }
677     }
678
679     let mut cases: Vec<_> = transform.suspension_points.iter().map(|point| {
680         // Make the point's storage live block goto the resume block
681         let block = point.storage_live.unwrap();
682         let term = Terminator {
683             source_info: source_info(mir),
684             kind: TerminatorKind::Goto {
685                 target: point.resume,
686             },
687         };
688         mir.basic_blocks_mut()[block].terminator = Some(term);
689         (point.state, block)
690     }).collect();
691
692     // Jump to the entry point on the 0 state
693     cases.insert(0, (0, BasicBlock::new(0)));
694     // Panic when resumed on the returned (1) state
695     cases.insert(1, (1, insert_panic_block(tcx, mir, AssertMessage::GeneratorResumedAfterReturn)));
696     // Panic when resumed on the poisoned (2) state
697     cases.insert(2, (2, insert_panic_block(tcx, mir, AssertMessage::GeneratorResumedAfterPanic)));
698
699     insert_switch(tcx, mir, cases, &transform);
700
701     make_generator_state_argument_indirect(tcx, def_id, mir);
702
703     no_landing_pads(tcx, mir);
704
705     // Make sure we remove dead blocks to remove
706     // unrelated code from the drop part of the function
707     simplify::remove_dead_blocks(mir);
708
709     dump_mir(tcx, None, "generator_resume", &0, source, mir);
710 }
711
712 fn source_info<'a, 'tcx>(mir: &Mir<'tcx>) -> SourceInfo {
713     SourceInfo {
714         span: mir.span,
715         scope: ARGUMENT_VISIBILITY_SCOPE,
716     }
717 }
718
719 fn insert_clean_drop<'a, 'tcx>(mir: &mut Mir<'tcx>) -> BasicBlock {
720     let return_block = insert_return_block(mir);
721
722     // Create a block to destroy an unresumed generators. This can only destroy upvars.
723     let drop_clean = BasicBlock::new(mir.basic_blocks().len());
724     let term = TerminatorKind::Drop {
725         location: Lvalue::Local(self_arg()),
726         target: return_block,
727         unwind: None,
728     };
729     let source_info = source_info(mir);
730     mir.basic_blocks_mut().push(BasicBlockData {
731         statements: Vec::new(),
732         terminator: Some(Terminator {
733             source_info,
734             kind: term,
735         }),
736         is_cleanup: false,
737     });
738
739     drop_clean
740 }
741
742 impl MirPass for StateTransform {
743     fn run_pass<'a, 'tcx>(&self,
744                     tcx: TyCtxt<'a, 'tcx, 'tcx>,
745                     source: MirSource,
746                     mir: &mut Mir<'tcx>) {
747         let yield_ty = if let Some(yield_ty) = mir.yield_ty {
748             yield_ty
749         } else {
750             // This only applies to generators
751             return
752         };
753
754         assert!(mir.generator_drop.is_none());
755
756         let node_id = source.item_id();
757         let def_id = tcx.hir.local_def_id(source.item_id());
758         let hir_id = tcx.hir.node_to_hir_id(node_id);
759
760         // Get the interior types which typeck computed
761         let interior = *tcx.typeck_tables_of(def_id).generator_interiors().get(hir_id).unwrap();
762
763         // The first argument is the generator type passed by value
764         let gen_ty = mir.local_decls.raw[1].ty;
765
766         // Compute GeneratorState<yield_ty, return_ty>
767         let state_did = tcx.lang_items().gen_state().unwrap();
768         let state_adt_ref = tcx.adt_def(state_did);
769         let state_substs = tcx.mk_substs([Kind::from(yield_ty),
770             Kind::from(mir.return_ty)].iter());
771         let ret_ty = tcx.mk_adt(state_adt_ref, state_substs);
772
773         // We rename RETURN_POINTER which has type mir.return_ty to new_ret_local
774         // RETURN_POINTER then is a fresh unused local with type ret_ty.
775         let new_ret_local = replace_result_variable(ret_ty, mir);
776
777         // Extract locals which are live across suspension point into `layout`
778         // `remap` gives a mapping from local indices onto generator struct indices
779         // `storage_liveness` tells us which locals have live storage at suspension points
780         let (remap, layout, storage_liveness) = compute_layout(tcx, source, interior, mir);
781
782         let state_field = mir.upvar_decls.len();
783
784         // Run the transformation which converts Lvalues from Local to generator struct
785         // accesses for locals in `remap`.
786         // It also rewrites `return x` and `yield y` as writing a new generator state and returning
787         // GeneratorState::Complete(x) and GeneratorState::Yielded(y) respectively.
788         let mut transform = TransformVisitor {
789             tcx,
790             state_adt_ref,
791             state_substs,
792             remap,
793             storage_liveness,
794             mir_local_count: mir.local_decls.len(),
795             suspension_points: Vec::new(),
796             new_ret_local,
797             state_field,
798         };
799         transform.visit_mir(mir);
800
801         // Update our MIR struct to reflect the changed we've made
802         mir.return_ty = ret_ty;
803         mir.yield_ty = None;
804         mir.arg_count = 1;
805         mir.spread_arg = None;
806         mir.generator_layout = Some(layout);
807
808         // Insert `drop(generator_struct)` which is used to drop upvars for generators in
809         // the unresumed (0) state.
810         // This is expanded to a drop ladder in `elaborate_generator_drops`.
811         let drop_clean = insert_clean_drop(mir);
812
813         dump_mir(tcx, None, "generator_pre-elab", &0, source, mir);
814
815         // Expand `drop(generator_struct)` to a drop ladder which destroys upvars.
816         // If any upvars are moved out of, drop elaboration will handle upvar destruction.
817         // However we need to also elaborate the code generated by `insert_clean_drop`.
818         elaborate_generator_drops(tcx, def_id, mir);
819
820         dump_mir(tcx, None, "generator_post-transform", &0, source, mir);
821
822         // Create StorageLive instruction blocks for suspension points
823         for point in &mut transform.suspension_points {
824             point.storage_live = Some(BasicBlock::new(mir.basic_blocks().len()));
825             let source_info = source_info(mir);
826             let mut statements = Vec::new();
827             for i in 0..(transform.mir_local_count) {
828                 let l = Local::new(i);
829                 if point.storage_liveness.contains(&l) && !transform.remap.contains_key(&l) {
830                     statements.push(Statement {
831                         source_info,
832                         kind: StatementKind::StorageLive(l),
833                     });
834                 }
835             }
836             mir.basic_blocks_mut().push(BasicBlockData {
837                 statements,
838                 terminator: Some(Terminator {
839                     source_info,
840                     kind: TerminatorKind::Unreachable,
841                 }),
842                 is_cleanup: false,
843             });
844         }
845
846         // Create a copy of our MIR and use it to create the drop shim for the generator
847         let drop_shim = create_generator_drop_shim(tcx,
848             &transform,
849             def_id,
850             source,
851             gen_ty,
852             &mir,
853             drop_clean);
854
855         mir.generator_drop = Some(box drop_shim);
856
857         // Create the Generator::resume function
858         create_generator_resume_function(tcx, transform, def_id, source, mir);
859     }
860 }