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