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