]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/generator.rs
Remove duplication using single variant for error
[rust.git] / src / librustc_mir / transform / generator.rs
1 //! This is the implementation of the pass which transforms generators into state machines.
2 //!
3 //! MIR generation for generators creates a function which has a self argument which
4 //! passes by value. This argument is effectively a generator type which only contains upvars and
5 //! is only used for this argument inside the MIR for the generator.
6 //! It is passed by value to enable upvars to be moved out of it. Drop elaboration runs on that
7 //! MIR before this pass and creates drop flags for MIR locals.
8 //! It will also drop the generator argument (which only consists of upvars) if any of the upvars
9 //! are moved out of. This pass elaborates the drops of upvars / generator argument in the case
10 //! that none of the upvars were moved out of. This is because we cannot have any drops of this
11 //! generator in the MIR, since it is used to create the drop glue for the generator. We'd get
12 //! infinite recursion otherwise.
13 //!
14 //! This pass creates the implementation for the Generator::resume function and the drop shim
15 //! for the generator based on the MIR input. It converts the generator argument from Self to
16 //! &mut Self adding derefs in the MIR as needed. It computes the final layout of the generator
17 //! struct which looks like this:
18 //!     First upvars are stored
19 //!     It is followed by the generator state field.
20 //!     Then finally the MIR locals which are live across a suspension point are stored.
21 //!
22 //!     struct Generator {
23 //!         upvars...,
24 //!         state: u32,
25 //!         mir_locals...,
26 //!     }
27 //!
28 //! This pass computes the meaning of the state field and the MIR locals which are live
29 //! across a suspension point. There are however three hardcoded generator states:
30 //!     0 - Generator have not been resumed yet
31 //!     1 - Generator has returned / is completed
32 //!     2 - Generator has been poisoned
33 //!
34 //! It also rewrites `return x` and `yield y` as setting a new generator state and returning
35 //! GeneratorState::Complete(x) and GeneratorState::Yielded(y) respectively.
36 //! MIR locals which are live across a suspension point are moved to the generator struct
37 //! with references to them being updated with references to the generator struct.
38 //!
39 //! The pass creates two functions which have a switch on the generator state giving
40 //! the action to take.
41 //!
42 //! One of them is the implementation of Generator::resume.
43 //! For generators with state 0 (unresumed) it starts the execution of the generator.
44 //! For generators with state 1 (returned) and state 2 (poisoned) it panics.
45 //! Otherwise it continues the execution from the last suspension point.
46 //!
47 //! The other function is the drop glue for the generator.
48 //! For generators with state 0 (unresumed) it drops the upvars of the generator.
49 //! For generators with state 1 (returned) and state 2 (poisoned) it does nothing.
50 //! Otherwise it drops all the values in scope at the last suspension point.
51
52 use rustc::hir;
53 use rustc::hir::def_id::DefId;
54 use rustc::mir::*;
55 use rustc::mir::visit::{PlaceContext, Visitor, MutVisitor};
56 use rustc::ty::{self, TyCtxt, AdtDef, Ty};
57 use rustc::ty::GeneratorSubsts;
58 use rustc::ty::layout::VariantIdx;
59 use rustc::ty::subst::SubstsRef;
60 use rustc_data_structures::fx::FxHashMap;
61 use rustc_index::vec::{Idx, IndexVec};
62 use rustc_index::bit_set::{BitSet, BitMatrix};
63 use std::borrow::Cow;
64 use std::iter;
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::{DataflowResults, DataflowResultsConsumer, FlowAtLocation};
69 use crate::dataflow::{do_dataflow, DebugFormatted, DataflowResultsCursor};
70 use crate::dataflow::{MaybeStorageLive, HaveBeenBorrowedLocals, RequiresStorage};
71 use crate::util::dump_mir;
72 use crate::util::liveness;
73
74 pub struct StateTransform;
75
76 struct RenameLocalVisitor<'tcx> {
77     from: Local,
78     to: Local,
79     tcx: TyCtxt<'tcx>,
80 }
81
82 impl<'tcx> MutVisitor<'tcx> for RenameLocalVisitor<'tcx> {
83     fn tcx(&self) -> TyCtxt<'tcx> {
84         self.tcx
85     }
86
87     fn visit_local(&mut self,
88                    local: &mut Local,
89                    _: PlaceContext,
90                    _: Location) {
91         if *local == self.from {
92             *local = self.to;
93         }
94     }
95
96     fn process_projection_elem(
97         &mut self,
98         elem: &PlaceElem<'tcx>,
99     ) -> Option<PlaceElem<'tcx>> {
100         match elem {
101             PlaceElem::Index(local) if *local == self.from => {
102                 Some(PlaceElem::Index(self.to))
103             }
104             _ => None,
105         }
106     }
107 }
108
109 struct DerefArgVisitor<'tcx> {
110     tcx: TyCtxt<'tcx>,
111 }
112
113 impl<'tcx> MutVisitor<'tcx> for DerefArgVisitor<'tcx> {
114     fn tcx(&self) -> TyCtxt<'tcx> {
115         self.tcx
116     }
117
118     fn visit_local(&mut self,
119                    local: &mut Local,
120                    _: PlaceContext,
121                    _: Location) {
122         assert_ne!(*local, self_arg());
123     }
124
125     fn visit_place(&mut self,
126                     place: &mut Place<'tcx>,
127                     context: PlaceContext,
128                     location: Location) {
129         if place.base == PlaceBase::Local(self_arg()) {
130             replace_base(place, Place {
131                 base: PlaceBase::Local(self_arg()),
132                 projection: self.tcx().intern_place_elems(&vec![ProjectionElem::Deref]),
133             }, self.tcx);
134         } else {
135             self.visit_place_base(&mut place.base, context, location);
136
137             for elem in place.projection.iter() {
138                 if let PlaceElem::Index(local) = elem {
139                     assert_ne!(*local, self_arg());
140                 }
141             }
142         }
143     }
144 }
145
146 struct PinArgVisitor<'tcx> {
147     ref_gen_ty: Ty<'tcx>,
148     tcx: TyCtxt<'tcx>,
149 }
150
151 impl<'tcx> MutVisitor<'tcx> for PinArgVisitor<'tcx> {
152     fn tcx(&self) -> TyCtxt<'tcx> {
153         self.tcx
154     }
155
156     fn visit_local(&mut self,
157                    local: &mut Local,
158                    _: PlaceContext,
159                    _: Location) {
160         assert_ne!(*local, self_arg());
161     }
162
163     fn visit_place(&mut self, place: &mut Place<'tcx>, context: PlaceContext, location: Location) {
164         if place.base == PlaceBase::Local(self_arg()) {
165             replace_base(
166                 place,
167                 Place {
168                     base: PlaceBase::Local(self_arg()),
169                     projection: self.tcx().intern_place_elems(&vec![ProjectionElem::Field(
170                             Field::new(0),
171                             self.ref_gen_ty,
172                     )]),
173                 },
174                 self.tcx,
175             );
176         } else {
177             self.visit_place_base(&mut place.base, context, location);
178
179             for elem in place.projection.iter() {
180                 if let PlaceElem::Index(local) = elem {
181                     assert_ne!(*local, self_arg());
182                 }
183             }
184         }
185     }
186 }
187
188 fn replace_base<'tcx>(place: &mut Place<'tcx>, new_base: Place<'tcx>, tcx: TyCtxt<'tcx>) {
189     place.base = new_base.base;
190
191     let mut new_projection = new_base.projection.to_vec();
192     new_projection.append(&mut place.projection.to_vec());
193
194     place.projection = tcx.intern_place_elems(&new_projection);
195 }
196
197 fn self_arg() -> Local {
198     Local::new(1)
199 }
200
201 /// Generator have not been resumed yet
202 const UNRESUMED: usize = GeneratorSubsts::UNRESUMED;
203 /// Generator has returned / is completed
204 const RETURNED: usize = GeneratorSubsts::RETURNED;
205 /// Generator has been poisoned
206 const POISONED: usize = GeneratorSubsts::POISONED;
207
208 struct SuspensionPoint {
209     state: usize,
210     resume: BasicBlock,
211     drop: Option<BasicBlock>,
212     storage_liveness: liveness::LiveVarSet,
213 }
214
215 struct TransformVisitor<'tcx> {
216     tcx: TyCtxt<'tcx>,
217     state_adt_ref: &'tcx AdtDef,
218     state_substs: SubstsRef<'tcx>,
219
220     // The type of the discriminant in the generator struct
221     discr_ty: Ty<'tcx>,
222
223     // Mapping from Local to (type of local, generator struct index)
224     // FIXME(eddyb) This should use `IndexVec<Local, Option<_>>`.
225     remap: FxHashMap<Local, (Ty<'tcx>, VariantIdx, usize)>,
226
227     // A map from a suspension point in a block to the locals which have live storage at that point
228     // FIXME(eddyb) This should use `IndexVec<BasicBlock, Option<_>>`.
229     storage_liveness: FxHashMap<BasicBlock, liveness::LiveVarSet>,
230
231     // A list of suspension points, generated during the transform
232     suspension_points: Vec<SuspensionPoint>,
233
234     // The original RETURN_PLACE local
235     new_ret_local: Local,
236 }
237
238 impl TransformVisitor<'tcx> {
239     // Make a GeneratorState rvalue
240     fn make_state(&self, idx: VariantIdx, val: Operand<'tcx>) -> Rvalue<'tcx> {
241         let adt = AggregateKind::Adt(self.state_adt_ref, idx, self.state_substs, None, None);
242         Rvalue::Aggregate(box adt, vec![val])
243     }
244
245     // Create a Place referencing a generator struct field
246     fn make_field(&self, variant_index: VariantIdx, idx: usize, ty: Ty<'tcx>) -> Place<'tcx> {
247         let self_place = Place::from(self_arg());
248         let base = self.tcx.mk_place_downcast_unnamed(self_place, variant_index);
249         let mut projection = base.projection.to_vec();
250         projection.push(ProjectionElem::Field(Field::new(idx), ty));
251
252         Place {
253             base: base.base,
254             projection: self.tcx.intern_place_elems(&projection),
255         }
256     }
257
258     // Create a statement which changes the discriminant
259     fn set_discr(&self, state_disc: VariantIdx, source_info: SourceInfo) -> Statement<'tcx> {
260         let self_place = Place::from(self_arg());
261         Statement {
262             source_info,
263             kind: StatementKind::SetDiscriminant {
264                 place: box self_place,
265                 variant_index: state_disc,
266             },
267         }
268     }
269
270     // Create a statement which reads the discriminant into a temporary
271     fn get_discr(&self, body: &mut Body<'tcx>) -> (Statement<'tcx>, Place<'tcx>) {
272         let temp_decl = LocalDecl::new_internal(self.tcx.types.isize, body.span);
273         let local_decls_len = body.local_decls.push(temp_decl);
274         let temp = Place::from(local_decls_len);
275
276         let self_place = Place::from(self_arg());
277         let assign = Statement {
278             source_info: source_info(body),
279             kind: StatementKind::Assign(box(temp.clone(), Rvalue::Discriminant(self_place))),
280         };
281         (assign, temp)
282     }
283 }
284
285 impl MutVisitor<'tcx> for TransformVisitor<'tcx> {
286     fn tcx(&self) -> TyCtxt<'tcx> {
287         self.tcx
288     }
289
290     fn visit_local(&mut self,
291                    local: &mut Local,
292                    _: PlaceContext,
293                    _: Location) {
294         assert_eq!(self.remap.get(local), None);
295     }
296
297     fn visit_place(
298         &mut self,
299         place: &mut Place<'tcx>,
300         context: PlaceContext,
301         location: Location,
302     ) {
303         if let PlaceBase::Local(l) = place.base {
304             // Replace an Local in the remap with a generator struct access
305             if let Some(&(ty, variant_index, idx)) = self.remap.get(&l) {
306                 replace_base(place, self.make_field(variant_index, idx, ty), self.tcx);
307             }
308         } else {
309             self.visit_place_base(&mut place.base, context, location);
310
311             for elem in place.projection.iter() {
312                 if let PlaceElem::Index(local) = elem {
313                     assert_ne!(*local, self_arg());
314                 }
315             }
316         }
317     }
318
319     fn visit_basic_block_data(&mut self,
320                               block: BasicBlock,
321                               data: &mut BasicBlockData<'tcx>) {
322         // Remove StorageLive and StorageDead statements for remapped locals
323         data.retain_statements(|s| {
324             match s.kind {
325                 StatementKind::StorageLive(l) | StatementKind::StorageDead(l) => {
326                     !self.remap.contains_key(&l)
327                 }
328                 _ => true
329             }
330         });
331
332         let ret_val = match data.terminator().kind {
333             TerminatorKind::Return => Some((VariantIdx::new(1),
334                 None,
335                 Operand::Move(Place::from(self.new_ret_local)),
336                 None)),
337             TerminatorKind::Yield { ref value, resume, drop } => Some((VariantIdx::new(0),
338                 Some(resume),
339                 value.clone(),
340                 drop)),
341             _ => None
342         };
343
344         if let Some((state_idx, resume, v, drop)) = ret_val {
345             let source_info = data.terminator().source_info;
346             // We must assign the value first in case it gets declared dead below
347             data.statements.push(Statement {
348                 source_info,
349                 kind: StatementKind::Assign(
350                     box(
351                         Place::return_place(),
352                         self.make_state(state_idx, v)
353                     )
354                 ),
355             });
356             let state = if let Some(resume) = resume { // Yield
357                 let state = 3 + self.suspension_points.len();
358
359                 self.suspension_points.push(SuspensionPoint {
360                     state,
361                     resume,
362                     drop,
363                     storage_liveness: self.storage_liveness.get(&block).unwrap().clone(),
364                 });
365
366                 VariantIdx::new(state)
367             } else { // Return
368                 VariantIdx::new(RETURNED) // state for returned
369             };
370             data.statements.push(self.set_discr(state, source_info));
371             data.terminator.as_mut().unwrap().kind = TerminatorKind::Return;
372         }
373
374         self.super_basic_block_data(block, data);
375     }
376 }
377
378 fn make_generator_state_argument_indirect<'tcx>(
379     tcx: TyCtxt<'tcx>,
380     def_id: DefId,
381     body: &mut Body<'tcx>,
382 ) {
383     let gen_ty = body.local_decls.raw[1].ty;
384
385     let region = ty::ReFree(ty::FreeRegion {
386         scope: def_id,
387         bound_region: ty::BoundRegion::BrEnv,
388     });
389
390     let region = tcx.mk_region(region);
391
392     let ref_gen_ty = tcx.mk_ref(region, ty::TypeAndMut {
393         ty: gen_ty,
394         mutbl: hir::Mutability::Mutable
395     });
396
397     // Replace the by value generator argument
398     body.local_decls.raw[1].ty = ref_gen_ty;
399
400     // Add a deref to accesses of the generator state
401     DerefArgVisitor { tcx }.visit_body(body);
402 }
403
404 fn make_generator_state_argument_pinned<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
405     let ref_gen_ty = body.local_decls.raw[1].ty;
406
407     let pin_did = tcx.lang_items().pin_type().unwrap();
408     let pin_adt_ref = tcx.adt_def(pin_did);
409     let substs = tcx.intern_substs(&[ref_gen_ty.into()]);
410     let pin_ref_gen_ty = tcx.mk_adt(pin_adt_ref, substs);
411
412     // Replace the by ref generator argument
413     body.local_decls.raw[1].ty = pin_ref_gen_ty;
414
415     // Add the Pin field access to accesses of the generator state
416     PinArgVisitor { ref_gen_ty, tcx }.visit_body(body);
417 }
418
419 fn replace_result_variable<'tcx>(
420     ret_ty: Ty<'tcx>,
421     body: &mut Body<'tcx>,
422     tcx: TyCtxt<'tcx>,
423 ) -> Local {
424     let source_info = source_info(body);
425     let new_ret = LocalDecl {
426         mutability: Mutability::Mut,
427         ty: ret_ty,
428         user_ty: UserTypeProjections::none(),
429         source_info,
430         internal: false,
431         is_block_tail: None,
432         local_info: LocalInfo::Other
433     };
434     let new_ret_local = Local::new(body.local_decls.len());
435     body.local_decls.push(new_ret);
436     body.local_decls.swap(RETURN_PLACE, new_ret_local);
437
438     RenameLocalVisitor {
439         from: RETURN_PLACE,
440         to: new_ret_local,
441         tcx,
442     }.visit_body(body);
443
444     new_ret_local
445 }
446
447 struct StorageIgnored(liveness::LiveVarSet);
448
449 impl<'tcx> Visitor<'tcx> for StorageIgnored {
450     fn visit_statement(&mut self,
451                        statement: &Statement<'tcx>,
452                        _location: Location) {
453         match statement.kind {
454             StatementKind::StorageLive(l) |
455             StatementKind::StorageDead(l) => { self.0.remove(l); }
456             _ => (),
457         }
458     }
459 }
460
461 struct LivenessInfo {
462     /// Which locals are live across any suspension point.
463     ///
464     /// GeneratorSavedLocal is indexed in terms of the elements in this set;
465     /// i.e. GeneratorSavedLocal::new(1) corresponds to the second local
466     /// included in this set.
467     live_locals: liveness::LiveVarSet,
468
469     /// The set of saved locals live at each suspension point.
470     live_locals_at_suspension_points: Vec<BitSet<GeneratorSavedLocal>>,
471
472     /// For every saved local, the set of other saved locals that are
473     /// storage-live at the same time as this local. We cannot overlap locals in
474     /// the layout which have conflicting storage.
475     storage_conflicts: BitMatrix<GeneratorSavedLocal, GeneratorSavedLocal>,
476
477     /// For every suspending block, the locals which are storage-live across
478     /// that suspension point.
479     storage_liveness: FxHashMap<BasicBlock, liveness::LiveVarSet>,
480 }
481
482 fn locals_live_across_suspend_points(
483     tcx: TyCtxt<'tcx>,
484     body: &Body<'tcx>,
485     source: MirSource<'tcx>,
486     movable: bool,
487 ) -> LivenessInfo {
488     let dead_unwinds = BitSet::new_empty(body.basic_blocks().len());
489     let def_id = source.def_id();
490
491     // Calculate when MIR locals have live storage. This gives us an upper bound of their
492     // lifetimes.
493     let storage_live_analysis = MaybeStorageLive::new(body);
494     let storage_live_results =
495         do_dataflow(tcx, body, def_id, &[], &dead_unwinds, storage_live_analysis,
496                     |bd, p| DebugFormatted::new(&bd.body().local_decls[p]));
497     let mut storage_live_cursor = DataflowResultsCursor::new(&storage_live_results, body);
498
499     // Find the MIR locals which do not use StorageLive/StorageDead statements.
500     // The storage of these locals are always live.
501     let mut ignored = StorageIgnored(BitSet::new_filled(body.local_decls.len()));
502     ignored.visit_body(body);
503
504     // Calculate the MIR locals which have been previously
505     // borrowed (even if they are still active).
506     let borrowed_locals_analysis = HaveBeenBorrowedLocals::new(body);
507     let borrowed_locals_results =
508         do_dataflow(tcx, body, def_id, &[], &dead_unwinds, borrowed_locals_analysis,
509                     |bd, p| DebugFormatted::new(&bd.body().local_decls[p]));
510     let mut borrowed_locals_cursor = DataflowResultsCursor::new(&borrowed_locals_results, body);
511
512     // Calculate the MIR locals that we actually need to keep storage around
513     // for.
514     let requires_storage_analysis = RequiresStorage::new(body, &borrowed_locals_results);
515     let requires_storage_results =
516         do_dataflow(tcx, body, def_id, &[], &dead_unwinds, requires_storage_analysis,
517                     |bd, p| DebugFormatted::new(&bd.body().local_decls[p]));
518     let mut requires_storage_cursor = DataflowResultsCursor::new(&requires_storage_results, body);
519
520     // Calculate the liveness of MIR locals ignoring borrows.
521     let mut live_locals = liveness::LiveVarSet::new_empty(body.local_decls.len());
522     let mut liveness = liveness::liveness_of_locals(
523         body,
524     );
525     liveness::dump_mir(
526         tcx,
527         "generator_liveness",
528         source,
529         body,
530         &liveness,
531     );
532
533     let mut storage_liveness_map = FxHashMap::default();
534     let mut live_locals_at_suspension_points = Vec::new();
535
536     for (block, data) in body.basic_blocks().iter_enumerated() {
537         if let TerminatorKind::Yield { .. } = data.terminator().kind {
538             let loc = Location {
539                 block: block,
540                 statement_index: data.statements.len(),
541             };
542
543             if !movable {
544                 // The `liveness` variable contains the liveness of MIR locals ignoring borrows.
545                 // This is correct for movable generators since borrows cannot live across
546                 // suspension points. However for immovable generators we need to account for
547                 // borrows, so we conseratively assume that all borrowed locals are live until
548                 // we find a StorageDead statement referencing the locals.
549                 // To do this we just union our `liveness` result with `borrowed_locals`, which
550                 // contains all the locals which has been borrowed before this suspension point.
551                 // If a borrow is converted to a raw reference, we must also assume that it lives
552                 // forever. Note that the final liveness is still bounded by the storage liveness
553                 // of the local, which happens using the `intersect` operation below.
554                 borrowed_locals_cursor.seek(loc);
555                 liveness.outs[block].union(borrowed_locals_cursor.get());
556             }
557
558             storage_live_cursor.seek(loc);
559             let storage_liveness = storage_live_cursor.get();
560
561             // Store the storage liveness for later use so we can restore the state
562             // after a suspension point
563             storage_liveness_map.insert(block, storage_liveness.clone());
564
565             requires_storage_cursor.seek(loc);
566             let storage_required = requires_storage_cursor.get().clone();
567
568             // Locals live are live at this point only if they are used across
569             // suspension points (the `liveness` variable)
570             // and their storage is required (the `storage_required` variable)
571             let mut live_locals_here = storage_required;
572             live_locals_here.intersect(&liveness.outs[block]);
573
574             // The generator argument is ignored
575             live_locals_here.remove(self_arg());
576
577             debug!("loc = {:?}, live_locals_here = {:?}", loc, live_locals_here);
578
579             // Add the locals live at this suspension point to the set of locals which live across
580             // any suspension points
581             live_locals.union(&live_locals_here);
582
583             live_locals_at_suspension_points.push(live_locals_here);
584         }
585     }
586     debug!("live_locals = {:?}", live_locals);
587
588     // Renumber our liveness_map bitsets to include only the locals we are
589     // saving.
590     let live_locals_at_suspension_points = live_locals_at_suspension_points
591         .iter()
592         .map(|live_here| renumber_bitset(&live_here, &live_locals))
593         .collect();
594
595     let storage_conflicts = compute_storage_conflicts(
596         body,
597         &live_locals,
598         &ignored,
599         requires_storage_results);
600
601     LivenessInfo {
602         live_locals,
603         live_locals_at_suspension_points,
604         storage_conflicts,
605         storage_liveness: storage_liveness_map,
606     }
607 }
608
609 /// Renumbers the items present in `stored_locals` and applies the renumbering
610 /// to 'input`.
611 ///
612 /// For example, if `stored_locals = [1, 3, 5]`, this would be renumbered to
613 /// `[0, 1, 2]`. Thus, if `input = [3, 5]` we would return `[1, 2]`.
614 fn renumber_bitset(input: &BitSet<Local>, stored_locals: &liveness::LiveVarSet)
615 -> BitSet<GeneratorSavedLocal> {
616     assert!(stored_locals.superset(&input), "{:?} not a superset of {:?}", stored_locals, input);
617     let mut out = BitSet::new_empty(stored_locals.count());
618     for (idx, local) in stored_locals.iter().enumerate() {
619         let saved_local = GeneratorSavedLocal::from(idx);
620         if input.contains(local) {
621             out.insert(saved_local);
622         }
623     }
624     debug!("renumber_bitset({:?}, {:?}) => {:?}", input, stored_locals, out);
625     out
626 }
627
628 /// For every saved local, looks for which locals are StorageLive at the same
629 /// time. Generates a bitset for every local of all the other locals that may be
630 /// StorageLive simultaneously with that local. This is used in the layout
631 /// computation; see `GeneratorLayout` for more.
632 fn compute_storage_conflicts(
633     body: &'mir Body<'tcx>,
634     stored_locals: &liveness::LiveVarSet,
635     ignored: &StorageIgnored,
636     requires_storage: DataflowResults<'tcx, RequiresStorage<'mir, 'tcx>>,
637 ) -> BitMatrix<GeneratorSavedLocal, GeneratorSavedLocal> {
638     assert_eq!(body.local_decls.len(), ignored.0.domain_size());
639     assert_eq!(body.local_decls.len(), stored_locals.domain_size());
640     debug!("compute_storage_conflicts({:?})", body.span);
641     debug!("ignored = {:?}", ignored.0);
642
643     // Storage ignored locals are not eligible for overlap, since their storage
644     // is always live.
645     let mut ineligible_locals = ignored.0.clone();
646     ineligible_locals.intersect(&stored_locals);
647
648     // Compute the storage conflicts for all eligible locals.
649     let mut visitor = StorageConflictVisitor {
650         body,
651         stored_locals: &stored_locals,
652         local_conflicts: BitMatrix::from_row_n(&ineligible_locals, body.local_decls.len()),
653     };
654     let mut state = FlowAtLocation::new(requires_storage);
655     visitor.analyze_results(&mut state);
656     let local_conflicts = visitor.local_conflicts;
657
658     // Compress the matrix using only stored locals (Local -> GeneratorSavedLocal).
659     //
660     // NOTE: Today we store a full conflict bitset for every local. Technically
661     // this is twice as many bits as we need, since the relation is symmetric.
662     // However, in practice these bitsets are not usually large. The layout code
663     // also needs to keep track of how many conflicts each local has, so it's
664     // simpler to keep it this way for now.
665     let mut storage_conflicts = BitMatrix::new(stored_locals.count(), stored_locals.count());
666     for (idx_a, local_a) in stored_locals.iter().enumerate() {
667         let saved_local_a = GeneratorSavedLocal::new(idx_a);
668         if ineligible_locals.contains(local_a) {
669             // Conflicts with everything.
670             storage_conflicts.insert_all_into_row(saved_local_a);
671         } else {
672             // Keep overlap information only for stored locals.
673             for (idx_b, local_b) in stored_locals.iter().enumerate() {
674                 let saved_local_b = GeneratorSavedLocal::new(idx_b);
675                 if local_conflicts.contains(local_a, local_b) {
676                     storage_conflicts.insert(saved_local_a, saved_local_b);
677                 }
678             }
679         }
680     }
681     storage_conflicts
682 }
683
684 struct StorageConflictVisitor<'body, 'tcx, 's> {
685     body: &'body Body<'tcx>,
686     stored_locals: &'s liveness::LiveVarSet,
687     // FIXME(tmandry): Consider using sparse bitsets here once we have good
688     // benchmarks for generators.
689     local_conflicts: BitMatrix<Local, Local>,
690 }
691
692 impl<'body, 'tcx, 's> DataflowResultsConsumer<'body, 'tcx>
693     for StorageConflictVisitor<'body, 'tcx, 's>
694 {
695     type FlowState = FlowAtLocation<'tcx, RequiresStorage<'body, 'tcx>>;
696
697     fn body(&self) -> &'body Body<'tcx> {
698         self.body
699     }
700
701     fn visit_block_entry(&mut self,
702                          block: BasicBlock,
703                          flow_state: &Self::FlowState) {
704         // statement_index is only used for logging, so this is fine.
705         self.apply_state(flow_state, Location { block, statement_index: 0 });
706     }
707
708     fn visit_statement_entry(&mut self,
709                              loc: Location,
710                              _stmt: &Statement<'tcx>,
711                              flow_state: &Self::FlowState) {
712         self.apply_state(flow_state, loc);
713     }
714
715     fn visit_terminator_entry(&mut self,
716                               loc: Location,
717                               _term: &Terminator<'tcx>,
718                               flow_state: &Self::FlowState) {
719         self.apply_state(flow_state, loc);
720     }
721 }
722
723 impl<'body, 'tcx, 's> StorageConflictVisitor<'body, 'tcx, 's> {
724     fn apply_state(&mut self,
725                    flow_state: &FlowAtLocation<'tcx, RequiresStorage<'body, 'tcx>>,
726                    loc: Location) {
727         // Ignore unreachable blocks.
728         match self.body.basic_blocks()[loc.block].terminator().kind {
729             TerminatorKind::Unreachable => return,
730             _ => (),
731         };
732
733         let mut eligible_storage_live = flow_state.as_dense().clone();
734         eligible_storage_live.intersect(&self.stored_locals);
735
736         for local in eligible_storage_live.iter() {
737             self.local_conflicts.union_row_with(&eligible_storage_live, local);
738         }
739
740         if eligible_storage_live.count() > 1 {
741             trace!("at {:?}, eligible_storage_live={:?}", loc, eligible_storage_live);
742         }
743     }
744 }
745
746 fn compute_layout<'tcx>(
747     tcx: TyCtxt<'tcx>,
748     source: MirSource<'tcx>,
749     upvars: &Vec<Ty<'tcx>>,
750     interior: Ty<'tcx>,
751     movable: bool,
752     body: &mut Body<'tcx>,
753 ) -> (
754     FxHashMap<Local, (Ty<'tcx>, VariantIdx, usize)>,
755     GeneratorLayout<'tcx>,
756     FxHashMap<BasicBlock, liveness::LiveVarSet>,
757 ) {
758     // Use a liveness analysis to compute locals which are live across a suspension point
759     let LivenessInfo {
760         live_locals, live_locals_at_suspension_points, storage_conflicts, storage_liveness
761     } = locals_live_across_suspend_points(tcx, body, source, movable);
762
763     // Erase regions from the types passed in from typeck so we can compare them with
764     // MIR types
765     let allowed_upvars = tcx.erase_regions(upvars);
766     let allowed = match interior.kind {
767         ty::GeneratorWitness(s) => tcx.erase_late_bound_regions(&s),
768         _ => bug!(),
769     };
770
771     for (local, decl) in body.local_decls.iter_enumerated() {
772         // Ignore locals which are internal or not live
773         if !live_locals.contains(local) || decl.internal {
774             continue;
775         }
776
777         // Sanity check that typeck knows about the type of locals which are
778         // live across a suspension point
779         if !allowed.contains(&decl.ty) && !allowed_upvars.contains(&decl.ty) {
780             span_bug!(body.span,
781                       "Broken MIR: generator contains type {} in MIR, \
782                        but typeck only knows about {}",
783                       decl.ty,
784                       interior);
785         }
786     }
787
788     // Gather live local types and their indices.
789     let mut locals = IndexVec::<GeneratorSavedLocal, _>::new();
790     let mut tys = IndexVec::<GeneratorSavedLocal, _>::new();
791     for (idx, local) in live_locals.iter().enumerate() {
792         locals.push(local);
793         tys.push(body.local_decls[local].ty);
794         debug!("generator saved local {:?} => {:?}", GeneratorSavedLocal::from(idx), local);
795     }
796
797     // Leave empty variants for the UNRESUMED, RETURNED, and POISONED states.
798     const RESERVED_VARIANTS: usize = 3;
799
800     // Build the generator variant field list.
801     // Create a map from local indices to generator struct indices.
802     let mut variant_fields: IndexVec<VariantIdx, IndexVec<Field, GeneratorSavedLocal>> =
803         iter::repeat(IndexVec::new()).take(RESERVED_VARIANTS).collect();
804     let mut remap = FxHashMap::default();
805     for (suspension_point_idx, live_locals) in live_locals_at_suspension_points.iter().enumerate() {
806         let variant_index = VariantIdx::from(RESERVED_VARIANTS + suspension_point_idx);
807         let mut fields = IndexVec::new();
808         for (idx, saved_local) in live_locals.iter().enumerate() {
809             fields.push(saved_local);
810             // Note that if a field is included in multiple variants, we will
811             // just use the first one here. That's fine; fields do not move
812             // around inside generators, so it doesn't matter which variant
813             // index we access them by.
814             remap.entry(locals[saved_local]).or_insert((tys[saved_local], variant_index, idx));
815         }
816         variant_fields.push(fields);
817     }
818     debug!("generator variant_fields = {:?}", variant_fields);
819     debug!("generator storage_conflicts = {:#?}", storage_conflicts);
820
821     let layout = GeneratorLayout {
822         field_tys: tys,
823         variant_fields,
824         storage_conflicts,
825     };
826
827     (remap, layout, storage_liveness)
828 }
829
830 fn insert_switch<'tcx>(
831     body: &mut Body<'tcx>,
832     cases: Vec<(usize, BasicBlock)>,
833     transform: &TransformVisitor<'tcx>,
834     default: TerminatorKind<'tcx>,
835 ) {
836     let default_block = insert_term_block(body, default);
837     let (assign, discr) = transform.get_discr(body);
838     let switch = TerminatorKind::SwitchInt {
839         discr: Operand::Move(discr),
840         switch_ty: transform.discr_ty,
841         values: Cow::from(cases.iter().map(|&(i, _)| i as u128).collect::<Vec<_>>()),
842         targets: cases.iter().map(|&(_, d)| d).chain(iter::once(default_block)).collect(),
843     };
844
845     let source_info = source_info(body);
846     body.basic_blocks_mut().raw.insert(0, BasicBlockData {
847         statements: vec![assign],
848         terminator: Some(Terminator {
849             source_info,
850             kind: switch,
851         }),
852         is_cleanup: false,
853     });
854
855     let blocks = body.basic_blocks_mut().iter_mut();
856
857     for target in blocks.flat_map(|b| b.terminator_mut().successors_mut()) {
858         *target = BasicBlock::new(target.index() + 1);
859     }
860 }
861
862 fn elaborate_generator_drops<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, body: &mut Body<'tcx>) {
863     use crate::util::elaborate_drops::{elaborate_drop, Unwind};
864     use crate::util::patch::MirPatch;
865     use crate::shim::DropShimElaborator;
866
867     // Note that `elaborate_drops` only drops the upvars of a generator, and
868     // this is ok because `open_drop` can only be reached within that own
869     // generator's resume function.
870
871     let param_env = tcx.param_env(def_id);
872     let gen = self_arg();
873
874     let mut elaborator = DropShimElaborator {
875         body: body,
876         patch: MirPatch::new(body),
877         tcx,
878         param_env
879     };
880
881     for (block, block_data) in body.basic_blocks().iter_enumerated() {
882         let (target, unwind, source_info) = match block_data.terminator() {
883             Terminator {
884                 source_info,
885                 kind: TerminatorKind::Drop {
886                     location,
887                     target,
888                     unwind
889                 }
890             } => {
891                 if let Some(local) = location.as_local() {
892                     if local == gen {
893                         (target, unwind, source_info)
894                     } else {
895                         continue;
896                     }
897                 } else {
898                     continue;
899                 }
900             }
901             _ => continue,
902         };
903         let unwind = if block_data.is_cleanup {
904             Unwind::InCleanup
905         } else {
906             Unwind::To(unwind.unwrap_or_else(|| elaborator.patch.resume_block()))
907         };
908         elaborate_drop(
909             &mut elaborator,
910             *source_info,
911             &Place::from(gen),
912             (),
913             *target,
914             unwind,
915             block,
916         );
917     }
918     elaborator.patch.apply(body);
919 }
920
921 fn create_generator_drop_shim<'tcx>(
922     tcx: TyCtxt<'tcx>,
923     transform: &TransformVisitor<'tcx>,
924     def_id: DefId,
925     source: MirSource<'tcx>,
926     gen_ty: Ty<'tcx>,
927     body: &Body<'tcx>,
928     drop_clean: BasicBlock,
929 ) -> Body<'tcx> {
930     let mut body = body.clone();
931
932     let source_info = source_info(&body);
933
934     let mut cases = create_cases(&mut body, transform, |point| point.drop);
935
936     cases.insert(0, (UNRESUMED, drop_clean));
937
938     // The returned state and the poisoned state fall through to the default
939     // case which is just to return
940
941     insert_switch(&mut body, cases, &transform, TerminatorKind::Return);
942
943     for block in body.basic_blocks_mut() {
944         let kind = &mut block.terminator_mut().kind;
945         if let TerminatorKind::GeneratorDrop = *kind {
946             *kind = TerminatorKind::Return;
947         }
948     }
949
950     // Replace the return variable
951     body.local_decls[RETURN_PLACE] = LocalDecl {
952         mutability: Mutability::Mut,
953         ty: tcx.mk_unit(),
954         user_ty: UserTypeProjections::none(),
955         source_info,
956         internal: false,
957         is_block_tail: None,
958         local_info: LocalInfo::Other
959     };
960
961     make_generator_state_argument_indirect(tcx, def_id, &mut body);
962
963     // Change the generator argument from &mut to *mut
964     body.local_decls[self_arg()] = LocalDecl {
965         mutability: Mutability::Mut,
966         ty: tcx.mk_ptr(ty::TypeAndMut {
967             ty: gen_ty,
968             mutbl: hir::Mutability::Mutable,
969         }),
970         user_ty: UserTypeProjections::none(),
971         source_info,
972         internal: false,
973         is_block_tail: None,
974         local_info: LocalInfo::Other
975     };
976     if tcx.sess.opts.debugging_opts.mir_emit_retag {
977         // Alias tracking must know we changed the type
978         body.basic_blocks_mut()[START_BLOCK].statements.insert(0, Statement {
979             source_info,
980             kind: StatementKind::Retag(RetagKind::Raw, box Place::from(self_arg())),
981         })
982     }
983
984     no_landing_pads(tcx, &mut body);
985
986     // Make sure we remove dead blocks to remove
987     // unrelated code from the resume part of the function
988     simplify::remove_dead_blocks(&mut body);
989
990     dump_mir(tcx, None, "generator_drop", &0, source, &mut body, |_, _| Ok(()) );
991
992     body
993 }
994
995 fn insert_term_block<'tcx>(body: &mut Body<'tcx>, kind: TerminatorKind<'tcx>) -> BasicBlock {
996     let term_block = BasicBlock::new(body.basic_blocks().len());
997     let source_info = source_info(body);
998     body.basic_blocks_mut().push(BasicBlockData {
999         statements: Vec::new(),
1000         terminator: Some(Terminator {
1001             source_info,
1002             kind,
1003         }),
1004         is_cleanup: false,
1005     });
1006     term_block
1007 }
1008
1009 fn insert_panic_block<'tcx>(
1010     tcx: TyCtxt<'tcx>,
1011     body: &mut Body<'tcx>,
1012     message: AssertMessage<'tcx>,
1013 ) -> BasicBlock {
1014     let assert_block = BasicBlock::new(body.basic_blocks().len());
1015     let term = TerminatorKind::Assert {
1016         cond: Operand::Constant(box Constant {
1017             span: body.span,
1018             user_ty: None,
1019             literal: ty::Const::from_bool(tcx, false),
1020         }),
1021         expected: true,
1022         msg: message,
1023         target: assert_block,
1024         cleanup: None,
1025     };
1026
1027     let source_info = source_info(body);
1028     body.basic_blocks_mut().push(BasicBlockData {
1029         statements: Vec::new(),
1030         terminator: Some(Terminator {
1031             source_info,
1032             kind: term,
1033         }),
1034         is_cleanup: false,
1035     });
1036
1037     assert_block
1038 }
1039
1040 fn create_generator_resume_function<'tcx>(
1041     tcx: TyCtxt<'tcx>,
1042     transform: TransformVisitor<'tcx>,
1043     def_id: DefId,
1044     source: MirSource<'tcx>,
1045     body: &mut Body<'tcx>,
1046 ) {
1047     // Poison the generator when it unwinds
1048     for block in body.basic_blocks_mut() {
1049         let source_info = block.terminator().source_info;
1050         if let &TerminatorKind::Resume = &block.terminator().kind {
1051             block.statements.push(
1052                 transform.set_discr(VariantIdx::new(POISONED), source_info));
1053         }
1054     }
1055
1056     let mut cases = create_cases(body, &transform, |point| Some(point.resume));
1057
1058     use rustc::mir::interpret::PanicInfo::{
1059         ResumedAfterPanic,
1060         ResumedAfterReturn,
1061     };
1062
1063     // Jump to the entry point on the unresumed
1064     cases.insert(0, (UNRESUMED, BasicBlock::new(0)));
1065
1066     // Panic when resumed on the returned or poisoned state
1067     if let Some(generator_kind) = body.generator_kind {
1068         cases.insert(1, (RETURNED, insert_panic_block(tcx, body, ResumedAfterReturn(generator_kind))));
1069         cases.insert(2, (POISONED, insert_panic_block(tcx, body, ResumedAfterPanic(generator_kind))));
1070     };
1071
1072     insert_switch(body, cases, &transform, TerminatorKind::Unreachable);
1073
1074     make_generator_state_argument_indirect(tcx, def_id, body);
1075     make_generator_state_argument_pinned(tcx, body);
1076
1077     no_landing_pads(tcx, body);
1078
1079     // Make sure we remove dead blocks to remove
1080     // unrelated code from the drop part of the function
1081     simplify::remove_dead_blocks(body);
1082
1083     dump_mir(tcx, None, "generator_resume", &0, source, body, |_, _| Ok(()) );
1084 }
1085
1086 fn source_info(body: &Body<'_>) -> SourceInfo {
1087     SourceInfo {
1088         span: body.span,
1089         scope: OUTERMOST_SOURCE_SCOPE,
1090     }
1091 }
1092
1093 fn insert_clean_drop(body: &mut Body<'_>) -> BasicBlock {
1094     let return_block = insert_term_block(body, TerminatorKind::Return);
1095
1096     // Create a block to destroy an unresumed generators. This can only destroy upvars.
1097     let drop_clean = BasicBlock::new(body.basic_blocks().len());
1098     let term = TerminatorKind::Drop {
1099         location: Place::from(self_arg()),
1100         target: return_block,
1101         unwind: None,
1102     };
1103     let source_info = source_info(body);
1104     body.basic_blocks_mut().push(BasicBlockData {
1105         statements: Vec::new(),
1106         terminator: Some(Terminator {
1107             source_info,
1108             kind: term,
1109         }),
1110         is_cleanup: false,
1111     });
1112
1113     drop_clean
1114 }
1115
1116 fn create_cases<'tcx, F>(
1117     body: &mut Body<'tcx>,
1118     transform: &TransformVisitor<'tcx>,
1119     target: F,
1120 ) -> Vec<(usize, BasicBlock)>
1121 where
1122     F: Fn(&SuspensionPoint) -> Option<BasicBlock>,
1123 {
1124     let source_info = source_info(body);
1125
1126     transform.suspension_points.iter().filter_map(|point| {
1127         // Find the target for this suspension point, if applicable
1128         target(point).map(|target| {
1129             let block = BasicBlock::new(body.basic_blocks().len());
1130             let mut statements = Vec::new();
1131
1132             // Create StorageLive instructions for locals with live storage
1133             for i in 0..(body.local_decls.len()) {
1134                 let l = Local::new(i);
1135                 if point.storage_liveness.contains(l) && !transform.remap.contains_key(&l) {
1136                     statements.push(Statement {
1137                         source_info,
1138                         kind: StatementKind::StorageLive(l),
1139                     });
1140                 }
1141             }
1142
1143             // Then jump to the real target
1144             body.basic_blocks_mut().push(BasicBlockData {
1145                 statements,
1146                 terminator: Some(Terminator {
1147                     source_info,
1148                     kind: TerminatorKind::Goto {
1149                         target,
1150                     },
1151                 }),
1152                 is_cleanup: false,
1153             });
1154
1155             (point.state, block)
1156         })
1157     }).collect()
1158 }
1159
1160 impl<'tcx> MirPass<'tcx> for StateTransform {
1161     fn run_pass(&self, tcx: TyCtxt<'tcx>, source: MirSource<'tcx>, body: &mut Body<'tcx>) {
1162         let yield_ty = if let Some(yield_ty) = body.yield_ty {
1163             yield_ty
1164         } else {
1165             // This only applies to generators
1166             return
1167         };
1168
1169         assert!(body.generator_drop.is_none());
1170
1171         let def_id = source.def_id();
1172
1173         // The first argument is the generator type passed by value
1174         let gen_ty = body.local_decls.raw[1].ty;
1175
1176         // Get the interior types and substs which typeck computed
1177         let (upvars, interior, discr_ty, movable) = match gen_ty.kind {
1178             ty::Generator(_, substs, movability) => {
1179                 let substs = substs.as_generator();
1180                 (substs.upvar_tys(def_id, tcx).collect(),
1181                  substs.witness(def_id, tcx),
1182                  substs.discr_ty(tcx),
1183                  movability == hir::Movability::Movable)
1184             }
1185             _ => bug!(),
1186         };
1187
1188         // Compute GeneratorState<yield_ty, return_ty>
1189         let state_did = tcx.lang_items().gen_state().unwrap();
1190         let state_adt_ref = tcx.adt_def(state_did);
1191         let state_substs = tcx.intern_substs(&[
1192             yield_ty.into(),
1193             body.return_ty().into(),
1194         ]);
1195         let ret_ty = tcx.mk_adt(state_adt_ref, state_substs);
1196
1197         // We rename RETURN_PLACE which has type mir.return_ty to new_ret_local
1198         // RETURN_PLACE then is a fresh unused local with type ret_ty.
1199         let new_ret_local = replace_result_variable(ret_ty, body, tcx);
1200
1201         // Extract locals which are live across suspension point into `layout`
1202         // `remap` gives a mapping from local indices onto generator struct indices
1203         // `storage_liveness` tells us which locals have live storage at suspension points
1204         let (remap, layout, storage_liveness) = compute_layout(
1205             tcx,
1206             source,
1207             &upvars,
1208             interior,
1209             movable,
1210             body);
1211
1212         // Run the transformation which converts Places from Local to generator struct
1213         // accesses for locals in `remap`.
1214         // It also rewrites `return x` and `yield y` as writing a new generator state and returning
1215         // GeneratorState::Complete(x) and GeneratorState::Yielded(y) respectively.
1216         let mut transform = TransformVisitor {
1217             tcx,
1218             state_adt_ref,
1219             state_substs,
1220             remap,
1221             storage_liveness,
1222             suspension_points: Vec::new(),
1223             new_ret_local,
1224             discr_ty,
1225         };
1226         transform.visit_body(body);
1227
1228         // Update our MIR struct to reflect the changed we've made
1229         body.yield_ty = None;
1230         body.arg_count = 1;
1231         body.spread_arg = None;
1232         body.generator_layout = Some(layout);
1233
1234         // Insert `drop(generator_struct)` which is used to drop upvars for generators in
1235         // the unresumed state.
1236         // This is expanded to a drop ladder in `elaborate_generator_drops`.
1237         let drop_clean = insert_clean_drop(body);
1238
1239         dump_mir(tcx, None, "generator_pre-elab", &0, source, body, |_, _| Ok(()) );
1240
1241         // Expand `drop(generator_struct)` to a drop ladder which destroys upvars.
1242         // If any upvars are moved out of, drop elaboration will handle upvar destruction.
1243         // However we need to also elaborate the code generated by `insert_clean_drop`.
1244         elaborate_generator_drops(tcx, def_id, body);
1245
1246         dump_mir(tcx, None, "generator_post-transform", &0, source, body, |_, _| Ok(()) );
1247
1248         // Create a copy of our MIR and use it to create the drop shim for the generator
1249         let drop_shim = create_generator_drop_shim(tcx,
1250             &transform,
1251             def_id,
1252             source,
1253             gen_ty,
1254             &body,
1255             drop_clean);
1256
1257         body.generator_drop = Some(box drop_shim);
1258
1259         // Create the Generator::resume function
1260         create_generator_resume_function(tcx, transform, def_id, source, body);
1261     }
1262 }