]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_mir/src/transform/generator.rs
New upstream version 1.48.0~beta.8+dfsg1
[rustc.git] / compiler / rustc_mir / src / 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 crate::dataflow::impls::{
53 MaybeBorrowedLocals, MaybeLiveLocals, MaybeRequiresStorage, MaybeStorageLive,
54 };
55 use crate::dataflow::{self, Analysis};
56 use crate::transform::no_landing_pads::no_landing_pads;
57 use crate::transform::simplify;
58 use crate::transform::{MirPass, MirSource};
59 use crate::util::dump_mir;
60 use crate::util::expand_aggregate;
61 use crate::util::storage;
62 use rustc_data_structures::fx::FxHashMap;
63 use rustc_hir as hir;
64 use rustc_hir::def_id::DefId;
65 use rustc_hir::lang_items::LangItem;
66 use rustc_index::bit_set::{BitMatrix, BitSet};
67 use rustc_index::vec::{Idx, IndexVec};
68 use rustc_middle::mir::visit::{MutVisitor, PlaceContext, Visitor};
69 use rustc_middle::mir::*;
70 use rustc_middle::ty::subst::{Subst, SubstsRef};
71 use rustc_middle::ty::GeneratorSubsts;
72 use rustc_middle::ty::{self, AdtDef, Ty, TyCtxt};
73 use rustc_target::abi::VariantIdx;
74 use rustc_target::spec::PanicStrategy;
75 use std::borrow::Cow;
76 use std::{iter, ops};
77
78 pub struct StateTransform;
79
80 struct RenameLocalVisitor<'tcx> {
81 from: Local,
82 to: Local,
83 tcx: TyCtxt<'tcx>,
84 }
85
86 impl<'tcx> MutVisitor<'tcx> for RenameLocalVisitor<'tcx> {
87 fn tcx(&self) -> TyCtxt<'tcx> {
88 self.tcx
89 }
90
91 fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
92 if *local == self.from {
93 *local = self.to;
94 }
95 }
96
97 fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, location: Location) {
98 match terminator.kind {
99 TerminatorKind::Return => {
100 // Do not replace the implicit `_0` access here, as that's not possible. The
101 // transform already handles `return` correctly.
102 }
103 _ => self.super_terminator(terminator, location),
104 }
105 }
106 }
107
108 struct DerefArgVisitor<'tcx> {
109 tcx: TyCtxt<'tcx>,
110 }
111
112 impl<'tcx> MutVisitor<'tcx> for DerefArgVisitor<'tcx> {
113 fn tcx(&self) -> TyCtxt<'tcx> {
114 self.tcx
115 }
116
117 fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
118 assert_ne!(*local, SELF_ARG);
119 }
120
121 fn visit_place(&mut self, place: &mut Place<'tcx>, context: PlaceContext, location: Location) {
122 if place.local == SELF_ARG {
123 replace_base(
124 place,
125 Place {
126 local: SELF_ARG,
127 projection: self.tcx().intern_place_elems(&[ProjectionElem::Deref]),
128 },
129 self.tcx,
130 );
131 } else {
132 self.visit_local(&mut place.local, context, location);
133
134 for elem in place.projection.iter() {
135 if let PlaceElem::Index(local) = elem {
136 assert_ne!(local, SELF_ARG);
137 }
138 }
139 }
140 }
141 }
142
143 struct PinArgVisitor<'tcx> {
144 ref_gen_ty: Ty<'tcx>,
145 tcx: TyCtxt<'tcx>,
146 }
147
148 impl<'tcx> MutVisitor<'tcx> for PinArgVisitor<'tcx> {
149 fn tcx(&self) -> TyCtxt<'tcx> {
150 self.tcx
151 }
152
153 fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
154 assert_ne!(*local, SELF_ARG);
155 }
156
157 fn visit_place(&mut self, place: &mut Place<'tcx>, context: PlaceContext, location: Location) {
158 if place.local == SELF_ARG {
159 replace_base(
160 place,
161 Place {
162 local: SELF_ARG,
163 projection: self.tcx().intern_place_elems(&[ProjectionElem::Field(
164 Field::new(0),
165 self.ref_gen_ty,
166 )]),
167 },
168 self.tcx,
169 );
170 } else {
171 self.visit_local(&mut place.local, context, location);
172
173 for elem in place.projection.iter() {
174 if let PlaceElem::Index(local) = elem {
175 assert_ne!(local, SELF_ARG);
176 }
177 }
178 }
179 }
180 }
181
182 fn replace_base<'tcx>(place: &mut Place<'tcx>, new_base: Place<'tcx>, tcx: TyCtxt<'tcx>) {
183 place.local = new_base.local;
184
185 let mut new_projection = new_base.projection.to_vec();
186 new_projection.append(&mut place.projection.to_vec());
187
188 place.projection = tcx.intern_place_elems(&new_projection);
189 }
190
191 const SELF_ARG: Local = Local::from_u32(1);
192
193 /// Generator has not been resumed yet.
194 const UNRESUMED: usize = GeneratorSubsts::UNRESUMED;
195 /// Generator has returned / is completed.
196 const RETURNED: usize = GeneratorSubsts::RETURNED;
197 /// Generator has panicked and is poisoned.
198 const POISONED: usize = GeneratorSubsts::POISONED;
199
200 /// A `yield` point in the generator.
201 struct SuspensionPoint<'tcx> {
202 /// State discriminant used when suspending or resuming at this point.
203 state: usize,
204 /// The block to jump to after resumption.
205 resume: BasicBlock,
206 /// Where to move the resume argument after resumption.
207 resume_arg: Place<'tcx>,
208 /// Which block to jump to if the generator is dropped in this state.
209 drop: Option<BasicBlock>,
210 /// Set of locals that have live storage while at this suspension point.
211 storage_liveness: BitSet<Local>,
212 }
213
214 struct TransformVisitor<'tcx> {
215 tcx: TyCtxt<'tcx>,
216 state_adt_ref: &'tcx AdtDef,
217 state_substs: SubstsRef<'tcx>,
218
219 // The type of the discriminant in the generator struct
220 discr_ty: Ty<'tcx>,
221
222 // Mapping from Local to (type of local, generator struct index)
223 // FIXME(eddyb) This should use `IndexVec<Local, Option<_>>`.
224 remap: FxHashMap<Local, (Ty<'tcx>, VariantIdx, usize)>,
225
226 // A map from a suspension point in a block to the locals which have live storage at that point
227 storage_liveness: IndexVec<BasicBlock, Option<BitSet<Local>>>,
228
229 // A list of suspension points, generated during the transform
230 suspension_points: Vec<SuspensionPoint<'tcx>>,
231
232 // The set of locals that have no `StorageLive`/`StorageDead` annotations.
233 always_live_locals: storage::AlwaysLiveLocals,
234
235 // The original RETURN_PLACE local
236 new_ret_local: Local,
237 }
238
239 impl TransformVisitor<'tcx> {
240 // Make a GeneratorState variant assignment. `core::ops::GeneratorState` only has single
241 // element tuple variants, so we can just write to the downcasted first field and then set the
242 // discriminant to the appropriate variant.
243 fn make_state(
244 &self,
245 idx: VariantIdx,
246 val: Operand<'tcx>,
247 source_info: SourceInfo,
248 ) -> impl Iterator<Item = Statement<'tcx>> {
249 let kind = AggregateKind::Adt(self.state_adt_ref, idx, self.state_substs, None, None);
250 assert_eq!(self.state_adt_ref.variants[idx].fields.len(), 1);
251 let ty = self
252 .tcx
253 .type_of(self.state_adt_ref.variants[idx].fields[0].did)
254 .subst(self.tcx, self.state_substs);
255 expand_aggregate(
256 Place::return_place(),
257 std::iter::once((val, ty)),
258 kind,
259 source_info,
260 self.tcx,
261 )
262 }
263
264 // Create a Place referencing a generator struct field
265 fn make_field(&self, variant_index: VariantIdx, idx: usize, ty: Ty<'tcx>) -> Place<'tcx> {
266 let self_place = Place::from(SELF_ARG);
267 let base = self.tcx.mk_place_downcast_unnamed(self_place, variant_index);
268 let mut projection = base.projection.to_vec();
269 projection.push(ProjectionElem::Field(Field::new(idx), ty));
270
271 Place { local: base.local, projection: self.tcx.intern_place_elems(&projection) }
272 }
273
274 // Create a statement which changes the discriminant
275 fn set_discr(&self, state_disc: VariantIdx, source_info: SourceInfo) -> Statement<'tcx> {
276 let self_place = Place::from(SELF_ARG);
277 Statement {
278 source_info,
279 kind: StatementKind::SetDiscriminant {
280 place: box self_place,
281 variant_index: state_disc,
282 },
283 }
284 }
285
286 // Create a statement which reads the discriminant into a temporary
287 fn get_discr(&self, body: &mut Body<'tcx>) -> (Statement<'tcx>, Place<'tcx>) {
288 let temp_decl = LocalDecl::new(self.discr_ty, body.span).internal();
289 let local_decls_len = body.local_decls.push(temp_decl);
290 let temp = Place::from(local_decls_len);
291
292 let self_place = Place::from(SELF_ARG);
293 let assign = Statement {
294 source_info: SourceInfo::outermost(body.span),
295 kind: StatementKind::Assign(box (temp, Rvalue::Discriminant(self_place))),
296 };
297 (assign, temp)
298 }
299 }
300
301 impl MutVisitor<'tcx> for TransformVisitor<'tcx> {
302 fn tcx(&self) -> TyCtxt<'tcx> {
303 self.tcx
304 }
305
306 fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
307 assert_eq!(self.remap.get(local), None);
308 }
309
310 fn visit_place(
311 &mut self,
312 place: &mut Place<'tcx>,
313 _context: PlaceContext,
314 _location: Location,
315 ) {
316 // Replace an Local in the remap with a generator struct access
317 if let Some(&(ty, variant_index, idx)) = self.remap.get(&place.local) {
318 replace_base(place, self.make_field(variant_index, idx, ty), self.tcx);
319 }
320 }
321
322 fn visit_basic_block_data(&mut self, block: BasicBlock, data: &mut BasicBlockData<'tcx>) {
323 // Remove StorageLive and StorageDead statements for remapped locals
324 data.retain_statements(|s| match s.kind {
325 StatementKind::StorageLive(l) | StatementKind::StorageDead(l) => {
326 !self.remap.contains_key(&l)
327 }
328 _ => true,
329 });
330
331 let ret_val = match data.terminator().kind {
332 TerminatorKind::Return => Some((
333 VariantIdx::new(1),
334 None,
335 Operand::Move(Place::from(self.new_ret_local)),
336 None,
337 )),
338 TerminatorKind::Yield { ref value, resume, resume_arg, drop } => {
339 Some((VariantIdx::new(0), Some((resume, resume_arg)), value.clone(), drop))
340 }
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.extend(self.make_state(state_idx, v, source_info));
348 let state = if let Some((resume, resume_arg)) = resume {
349 // Yield
350 let state = 3 + self.suspension_points.len();
351
352 // The resume arg target location might itself be remapped if its base local is
353 // live across a yield.
354 let resume_arg =
355 if let Some(&(ty, variant, idx)) = self.remap.get(&resume_arg.local) {
356 self.make_field(variant, idx, ty)
357 } else {
358 resume_arg
359 };
360
361 self.suspension_points.push(SuspensionPoint {
362 state,
363 resume,
364 resume_arg,
365 drop,
366 storage_liveness: self.storage_liveness[block].clone().unwrap(),
367 });
368
369 VariantIdx::new(state)
370 } else {
371 // Return
372 VariantIdx::new(RETURNED) // state for returned
373 };
374 data.statements.push(self.set_discr(state, source_info));
375 data.terminator_mut().kind = TerminatorKind::Return;
376 }
377
378 self.super_basic_block_data(block, data);
379 }
380 }
381
382 fn make_generator_state_argument_indirect<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
383 let gen_ty = body.local_decls.raw[1].ty;
384
385 let ref_gen_ty =
386 tcx.mk_ref(tcx.lifetimes.re_erased, ty::TypeAndMut { ty: gen_ty, mutbl: Mutability::Mut });
387
388 // Replace the by value generator argument
389 body.local_decls.raw[1].ty = ref_gen_ty;
390
391 // Add a deref to accesses of the generator state
392 DerefArgVisitor { tcx }.visit_body(body);
393 }
394
395 fn make_generator_state_argument_pinned<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
396 let ref_gen_ty = body.local_decls.raw[1].ty;
397
398 let pin_did = tcx.require_lang_item(LangItem::Pin, Some(body.span));
399 let pin_adt_ref = tcx.adt_def(pin_did);
400 let substs = tcx.intern_substs(&[ref_gen_ty.into()]);
401 let pin_ref_gen_ty = tcx.mk_adt(pin_adt_ref, substs);
402
403 // Replace the by ref generator argument
404 body.local_decls.raw[1].ty = pin_ref_gen_ty;
405
406 // Add the Pin field access to accesses of the generator state
407 PinArgVisitor { ref_gen_ty, tcx }.visit_body(body);
408 }
409
410 /// Allocates a new local and replaces all references of `local` with it. Returns the new local.
411 ///
412 /// `local` will be changed to a new local decl with type `ty`.
413 ///
414 /// Note that the new local will be uninitialized. It is the caller's responsibility to assign some
415 /// valid value to it before its first use.
416 fn replace_local<'tcx>(
417 local: Local,
418 ty: Ty<'tcx>,
419 body: &mut Body<'tcx>,
420 tcx: TyCtxt<'tcx>,
421 ) -> Local {
422 let new_decl = LocalDecl::new(ty, body.span);
423 let new_local = body.local_decls.push(new_decl);
424 body.local_decls.swap(local, new_local);
425
426 RenameLocalVisitor { from: local, to: new_local, tcx }.visit_body(body);
427
428 new_local
429 }
430
431 struct LivenessInfo {
432 /// Which locals are live across any suspension point.
433 saved_locals: GeneratorSavedLocals,
434
435 /// The set of saved locals live at each suspension point.
436 live_locals_at_suspension_points: Vec<BitSet<GeneratorSavedLocal>>,
437
438 /// Parallel vec to the above with SourceInfo for each yield terminator.
439 source_info_at_suspension_points: Vec<SourceInfo>,
440
441 /// For every saved local, the set of other saved locals that are
442 /// storage-live at the same time as this local. We cannot overlap locals in
443 /// the layout which have conflicting storage.
444 storage_conflicts: BitMatrix<GeneratorSavedLocal, GeneratorSavedLocal>,
445
446 /// For every suspending block, the locals which are storage-live across
447 /// that suspension point.
448 storage_liveness: IndexVec<BasicBlock, Option<BitSet<Local>>>,
449 }
450
451 fn locals_live_across_suspend_points(
452 tcx: TyCtxt<'tcx>,
453 body: &Body<'tcx>,
454 source: MirSource<'tcx>,
455 always_live_locals: &storage::AlwaysLiveLocals,
456 movable: bool,
457 ) -> LivenessInfo {
458 let def_id = source.def_id();
459 let body_ref: &Body<'_> = &body;
460
461 // Calculate when MIR locals have live storage. This gives us an upper bound of their
462 // lifetimes.
463 let mut storage_live = MaybeStorageLive::new(always_live_locals.clone())
464 .into_engine(tcx, body_ref, def_id)
465 .iterate_to_fixpoint()
466 .into_results_cursor(body_ref);
467
468 // Calculate the MIR locals which have been previously
469 // borrowed (even if they are still active).
470 let borrowed_locals_results = MaybeBorrowedLocals::all_borrows()
471 .into_engine(tcx, body_ref, def_id)
472 .pass_name("generator")
473 .iterate_to_fixpoint();
474
475 let mut borrowed_locals_cursor =
476 dataflow::ResultsCursor::new(body_ref, &borrowed_locals_results);
477
478 // Calculate the MIR locals that we actually need to keep storage around
479 // for.
480 let requires_storage_results = MaybeRequiresStorage::new(body, &borrowed_locals_results)
481 .into_engine(tcx, body_ref, def_id)
482 .iterate_to_fixpoint();
483 let mut requires_storage_cursor =
484 dataflow::ResultsCursor::new(body_ref, &requires_storage_results);
485
486 // Calculate the liveness of MIR locals ignoring borrows.
487 let mut liveness = MaybeLiveLocals
488 .into_engine(tcx, body_ref, def_id)
489 .pass_name("generator")
490 .iterate_to_fixpoint()
491 .into_results_cursor(body_ref);
492
493 let mut storage_liveness_map = IndexVec::from_elem(None, body.basic_blocks());
494 let mut live_locals_at_suspension_points = Vec::new();
495 let mut source_info_at_suspension_points = Vec::new();
496 let mut live_locals_at_any_suspension_point = BitSet::new_empty(body.local_decls.len());
497
498 for (block, data) in body.basic_blocks().iter_enumerated() {
499 if let TerminatorKind::Yield { .. } = data.terminator().kind {
500 let loc = Location { block, statement_index: data.statements.len() };
501
502 liveness.seek_to_block_end(block);
503 let mut live_locals = liveness.get().clone();
504
505 if !movable {
506 // The `liveness` variable contains the liveness of MIR locals ignoring borrows.
507 // This is correct for movable generators since borrows cannot live across
508 // suspension points. However for immovable generators we need to account for
509 // borrows, so we conseratively assume that all borrowed locals are live until
510 // we find a StorageDead statement referencing the locals.
511 // To do this we just union our `liveness` result with `borrowed_locals`, which
512 // contains all the locals which has been borrowed before this suspension point.
513 // If a borrow is converted to a raw reference, we must also assume that it lives
514 // forever. Note that the final liveness is still bounded by the storage liveness
515 // of the local, which happens using the `intersect` operation below.
516 borrowed_locals_cursor.seek_before_primary_effect(loc);
517 live_locals.union(borrowed_locals_cursor.get());
518 }
519
520 // Store the storage liveness for later use so we can restore the state
521 // after a suspension point
522 storage_live.seek_before_primary_effect(loc);
523 storage_liveness_map[block] = Some(storage_live.get().clone());
524
525 // Locals live are live at this point only if they are used across
526 // suspension points (the `liveness` variable)
527 // and their storage is required (the `storage_required` variable)
528 requires_storage_cursor.seek_before_primary_effect(loc);
529 live_locals.intersect(requires_storage_cursor.get());
530
531 // The generator argument is ignored.
532 live_locals.remove(SELF_ARG);
533
534 debug!("loc = {:?}, live_locals = {:?}", loc, live_locals);
535
536 // Add the locals live at this suspension point to the set of locals which live across
537 // any suspension points
538 live_locals_at_any_suspension_point.union(&live_locals);
539
540 live_locals_at_suspension_points.push(live_locals);
541 source_info_at_suspension_points.push(data.terminator().source_info);
542 }
543 }
544
545 debug!("live_locals_anywhere = {:?}", live_locals_at_any_suspension_point);
546 let saved_locals = GeneratorSavedLocals(live_locals_at_any_suspension_point);
547
548 // Renumber our liveness_map bitsets to include only the locals we are
549 // saving.
550 let live_locals_at_suspension_points = live_locals_at_suspension_points
551 .iter()
552 .map(|live_here| saved_locals.renumber_bitset(&live_here))
553 .collect();
554
555 let storage_conflicts = compute_storage_conflicts(
556 body_ref,
557 &saved_locals,
558 always_live_locals.clone(),
559 requires_storage_results,
560 );
561
562 LivenessInfo {
563 saved_locals,
564 live_locals_at_suspension_points,
565 source_info_at_suspension_points,
566 storage_conflicts,
567 storage_liveness: storage_liveness_map,
568 }
569 }
570
571 /// The set of `Local`s that must be saved across yield points.
572 ///
573 /// `GeneratorSavedLocal` is indexed in terms of the elements in this set;
574 /// i.e. `GeneratorSavedLocal::new(1)` corresponds to the second local
575 /// included in this set.
576 struct GeneratorSavedLocals(BitSet<Local>);
577
578 impl GeneratorSavedLocals {
579 /// Returns an iterator over each `GeneratorSavedLocal` along with the `Local` it corresponds
580 /// to.
581 fn iter_enumerated(&self) -> impl '_ + Iterator<Item = (GeneratorSavedLocal, Local)> {
582 self.iter().enumerate().map(|(i, l)| (GeneratorSavedLocal::from(i), l))
583 }
584
585 /// Transforms a `BitSet<Local>` that contains only locals saved across yield points to the
586 /// equivalent `BitSet<GeneratorSavedLocal>`.
587 fn renumber_bitset(&self, input: &BitSet<Local>) -> BitSet<GeneratorSavedLocal> {
588 assert!(self.superset(&input), "{:?} not a superset of {:?}", self.0, input);
589 let mut out = BitSet::new_empty(self.count());
590 for (saved_local, local) in self.iter_enumerated() {
591 if input.contains(local) {
592 out.insert(saved_local);
593 }
594 }
595 out
596 }
597
598 fn get(&self, local: Local) -> Option<GeneratorSavedLocal> {
599 if !self.contains(local) {
600 return None;
601 }
602
603 let idx = self.iter().take_while(|&l| l < local).count();
604 Some(GeneratorSavedLocal::new(idx))
605 }
606 }
607
608 impl ops::Deref for GeneratorSavedLocals {
609 type Target = BitSet<Local>;
610
611 fn deref(&self) -> &Self::Target {
612 &self.0
613 }
614 }
615
616 /// For every saved local, looks for which locals are StorageLive at the same
617 /// time. Generates a bitset for every local of all the other locals that may be
618 /// StorageLive simultaneously with that local. This is used in the layout
619 /// computation; see `GeneratorLayout` for more.
620 fn compute_storage_conflicts(
621 body: &'mir Body<'tcx>,
622 saved_locals: &GeneratorSavedLocals,
623 always_live_locals: storage::AlwaysLiveLocals,
624 requires_storage: dataflow::Results<'tcx, MaybeRequiresStorage<'mir, 'tcx>>,
625 ) -> BitMatrix<GeneratorSavedLocal, GeneratorSavedLocal> {
626 assert_eq!(body.local_decls.len(), saved_locals.domain_size());
627
628 debug!("compute_storage_conflicts({:?})", body.span);
629 debug!("always_live = {:?}", always_live_locals);
630
631 // Locals that are always live or ones that need to be stored across
632 // suspension points are not eligible for overlap.
633 let mut ineligible_locals = always_live_locals.into_inner();
634 ineligible_locals.intersect(saved_locals);
635
636 // Compute the storage conflicts for all eligible locals.
637 let mut visitor = StorageConflictVisitor {
638 body,
639 saved_locals: &saved_locals,
640 local_conflicts: BitMatrix::from_row_n(&ineligible_locals, body.local_decls.len()),
641 };
642
643 requires_storage.visit_reachable_with(body, &mut visitor);
644
645 let local_conflicts = visitor.local_conflicts;
646
647 // Compress the matrix using only stored locals (Local -> GeneratorSavedLocal).
648 //
649 // NOTE: Today we store a full conflict bitset for every local. Technically
650 // this is twice as many bits as we need, since the relation is symmetric.
651 // However, in practice these bitsets are not usually large. The layout code
652 // also needs to keep track of how many conflicts each local has, so it's
653 // simpler to keep it this way for now.
654 let mut storage_conflicts = BitMatrix::new(saved_locals.count(), saved_locals.count());
655 for (saved_local_a, local_a) in saved_locals.iter_enumerated() {
656 if ineligible_locals.contains(local_a) {
657 // Conflicts with everything.
658 storage_conflicts.insert_all_into_row(saved_local_a);
659 } else {
660 // Keep overlap information only for stored locals.
661 for (saved_local_b, local_b) in saved_locals.iter_enumerated() {
662 if local_conflicts.contains(local_a, local_b) {
663 storage_conflicts.insert(saved_local_a, saved_local_b);
664 }
665 }
666 }
667 }
668 storage_conflicts
669 }
670
671 struct StorageConflictVisitor<'mir, 'tcx, 's> {
672 body: &'mir Body<'tcx>,
673 saved_locals: &'s GeneratorSavedLocals,
674 // FIXME(tmandry): Consider using sparse bitsets here once we have good
675 // benchmarks for generators.
676 local_conflicts: BitMatrix<Local, Local>,
677 }
678
679 impl dataflow::ResultsVisitor<'mir, 'tcx> for StorageConflictVisitor<'mir, 'tcx, '_> {
680 type FlowState = BitSet<Local>;
681
682 fn visit_statement_before_primary_effect(
683 &mut self,
684 state: &Self::FlowState,
685 _statement: &'mir Statement<'tcx>,
686 loc: Location,
687 ) {
688 self.apply_state(state, loc);
689 }
690
691 fn visit_terminator_before_primary_effect(
692 &mut self,
693 state: &Self::FlowState,
694 _terminator: &'mir Terminator<'tcx>,
695 loc: Location,
696 ) {
697 self.apply_state(state, loc);
698 }
699 }
700
701 impl<'body, 'tcx, 's> StorageConflictVisitor<'body, 'tcx, 's> {
702 fn apply_state(&mut self, flow_state: &BitSet<Local>, loc: Location) {
703 // Ignore unreachable blocks.
704 if self.body.basic_blocks()[loc.block].terminator().kind == TerminatorKind::Unreachable {
705 return;
706 }
707
708 let mut eligible_storage_live = flow_state.clone();
709 eligible_storage_live.intersect(&self.saved_locals);
710
711 for local in eligible_storage_live.iter() {
712 self.local_conflicts.union_row_with(&eligible_storage_live, local);
713 }
714
715 if eligible_storage_live.count() > 1 {
716 trace!("at {:?}, eligible_storage_live={:?}", loc, eligible_storage_live);
717 }
718 }
719 }
720
721 /// Validates the typeck view of the generator against the actual set of types saved between
722 /// yield points.
723 fn sanitize_witness<'tcx>(
724 tcx: TyCtxt<'tcx>,
725 body: &Body<'tcx>,
726 did: DefId,
727 witness: Ty<'tcx>,
728 upvars: &Vec<Ty<'tcx>>,
729 saved_locals: &GeneratorSavedLocals,
730 ) {
731 let allowed_upvars = tcx.erase_regions(upvars);
732 let allowed = match witness.kind() {
733 ty::GeneratorWitness(s) => tcx.erase_late_bound_regions(&s),
734 _ => {
735 tcx.sess.delay_span_bug(
736 body.span,
737 &format!("unexpected generator witness type {:?}", witness.kind()),
738 );
739 return;
740 }
741 };
742
743 let param_env = tcx.param_env(did);
744
745 for (local, decl) in body.local_decls.iter_enumerated() {
746 // Ignore locals which are internal or not saved between yields.
747 if !saved_locals.contains(local) || decl.internal {
748 continue;
749 }
750 let decl_ty = tcx.normalize_erasing_regions(param_env, decl.ty);
751
752 // Sanity check that typeck knows about the type of locals which are
753 // live across a suspension point
754 if !allowed.contains(&decl_ty) && !allowed_upvars.contains(&decl_ty) {
755 span_bug!(
756 body.span,
757 "Broken MIR: generator contains type {} in MIR, \
758 but typeck only knows about {}",
759 decl.ty,
760 witness,
761 );
762 }
763 }
764 }
765
766 fn compute_layout<'tcx>(
767 liveness: LivenessInfo,
768 body: &mut Body<'tcx>,
769 ) -> (
770 FxHashMap<Local, (Ty<'tcx>, VariantIdx, usize)>,
771 GeneratorLayout<'tcx>,
772 IndexVec<BasicBlock, Option<BitSet<Local>>>,
773 ) {
774 let LivenessInfo {
775 saved_locals,
776 live_locals_at_suspension_points,
777 source_info_at_suspension_points,
778 storage_conflicts,
779 storage_liveness,
780 } = liveness;
781
782 // Gather live local types and their indices.
783 let mut locals = IndexVec::<GeneratorSavedLocal, _>::new();
784 let mut tys = IndexVec::<GeneratorSavedLocal, _>::new();
785 for (saved_local, local) in saved_locals.iter_enumerated() {
786 locals.push(local);
787 tys.push(body.local_decls[local].ty);
788 debug!("generator saved local {:?} => {:?}", saved_local, local);
789 }
790
791 // Leave empty variants for the UNRESUMED, RETURNED, and POISONED states.
792 // In debuginfo, these will correspond to the beginning (UNRESUMED) or end
793 // (RETURNED, POISONED) of the function.
794 const RESERVED_VARIANTS: usize = 3;
795 let body_span = body.source_scopes[OUTERMOST_SOURCE_SCOPE].span;
796 let mut variant_source_info: IndexVec<VariantIdx, SourceInfo> = [
797 SourceInfo::outermost(body_span.shrink_to_lo()),
798 SourceInfo::outermost(body_span.shrink_to_hi()),
799 SourceInfo::outermost(body_span.shrink_to_hi()),
800 ]
801 .iter()
802 .copied()
803 .collect();
804
805 // Build the generator variant field list.
806 // Create a map from local indices to generator struct indices.
807 let mut variant_fields: IndexVec<VariantIdx, IndexVec<Field, GeneratorSavedLocal>> =
808 iter::repeat(IndexVec::new()).take(RESERVED_VARIANTS).collect();
809 let mut remap = FxHashMap::default();
810 for (suspension_point_idx, live_locals) in live_locals_at_suspension_points.iter().enumerate() {
811 let variant_index = VariantIdx::from(RESERVED_VARIANTS + suspension_point_idx);
812 let mut fields = IndexVec::new();
813 for (idx, saved_local) in live_locals.iter().enumerate() {
814 fields.push(saved_local);
815 // Note that if a field is included in multiple variants, we will
816 // just use the first one here. That's fine; fields do not move
817 // around inside generators, so it doesn't matter which variant
818 // index we access them by.
819 remap.entry(locals[saved_local]).or_insert((tys[saved_local], variant_index, idx));
820 }
821 variant_fields.push(fields);
822 variant_source_info.push(source_info_at_suspension_points[suspension_point_idx]);
823 }
824 debug!("generator variant_fields = {:?}", variant_fields);
825 debug!("generator storage_conflicts = {:#?}", storage_conflicts);
826
827 let layout =
828 GeneratorLayout { field_tys: tys, variant_fields, variant_source_info, storage_conflicts };
829
830 (remap, layout, storage_liveness)
831 }
832
833 /// Replaces the entry point of `body` with a block that switches on the generator discriminant and
834 /// dispatches to blocks according to `cases`.
835 ///
836 /// After this function, the former entry point of the function will be bb1.
837 fn insert_switch<'tcx>(
838 body: &mut Body<'tcx>,
839 cases: Vec<(usize, BasicBlock)>,
840 transform: &TransformVisitor<'tcx>,
841 default: TerminatorKind<'tcx>,
842 ) {
843 let default_block = insert_term_block(body, default);
844 let (assign, discr) = transform.get_discr(body);
845 let switch = TerminatorKind::SwitchInt {
846 discr: Operand::Move(discr),
847 switch_ty: transform.discr_ty,
848 values: Cow::from(cases.iter().map(|&(i, _)| i as u128).collect::<Vec<_>>()),
849 targets: cases.iter().map(|&(_, d)| d).chain(iter::once(default_block)).collect(),
850 };
851
852 let source_info = SourceInfo::outermost(body.span);
853 body.basic_blocks_mut().raw.insert(
854 0,
855 BasicBlockData {
856 statements: vec![assign],
857 terminator: Some(Terminator { source_info, kind: switch }),
858 is_cleanup: false,
859 },
860 );
861
862 let blocks = body.basic_blocks_mut().iter_mut();
863
864 for target in blocks.flat_map(|b| b.terminator_mut().successors_mut()) {
865 *target = BasicBlock::new(target.index() + 1);
866 }
867 }
868
869 fn elaborate_generator_drops<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, body: &mut Body<'tcx>) {
870 use crate::shim::DropShimElaborator;
871 use crate::util::elaborate_drops::{elaborate_drop, Unwind};
872 use crate::util::patch::MirPatch;
873
874 // Note that `elaborate_drops` only drops the upvars of a generator, and
875 // this is ok because `open_drop` can only be reached within that own
876 // generator's resume function.
877
878 let param_env = tcx.param_env(def_id);
879
880 let mut elaborator = DropShimElaborator { body, patch: MirPatch::new(body), tcx, param_env };
881
882 for (block, block_data) in body.basic_blocks().iter_enumerated() {
883 let (target, unwind, source_info) = match block_data.terminator() {
884 Terminator { source_info, kind: TerminatorKind::Drop { place, target, unwind } } => {
885 if let Some(local) = place.as_local() {
886 if local == SELF_ARG {
887 (target, unwind, source_info)
888 } else {
889 continue;
890 }
891 } else {
892 continue;
893 }
894 }
895 _ => continue,
896 };
897 let unwind = if block_data.is_cleanup {
898 Unwind::InCleanup
899 } else {
900 Unwind::To(unwind.unwrap_or_else(|| elaborator.patch.resume_block()))
901 };
902 elaborate_drop(
903 &mut elaborator,
904 *source_info,
905 Place::from(SELF_ARG),
906 (),
907 *target,
908 unwind,
909 block,
910 );
911 }
912 elaborator.patch.apply(body);
913 }
914
915 fn create_generator_drop_shim<'tcx>(
916 tcx: TyCtxt<'tcx>,
917 transform: &TransformVisitor<'tcx>,
918 source: MirSource<'tcx>,
919 gen_ty: Ty<'tcx>,
920 body: &mut Body<'tcx>,
921 drop_clean: BasicBlock,
922 ) -> Body<'tcx> {
923 let mut body = body.clone();
924 body.arg_count = 1; // make sure the resume argument is not included here
925
926 let source_info = SourceInfo::outermost(body.span);
927
928 let mut cases = create_cases(&mut body, transform, Operation::Drop);
929
930 cases.insert(0, (UNRESUMED, drop_clean));
931
932 // The returned state and the poisoned state fall through to the default
933 // case which is just to return
934
935 insert_switch(&mut body, cases, &transform, TerminatorKind::Return);
936
937 for block in body.basic_blocks_mut() {
938 let kind = &mut block.terminator_mut().kind;
939 if let TerminatorKind::GeneratorDrop = *kind {
940 *kind = TerminatorKind::Return;
941 }
942 }
943
944 // Replace the return variable
945 body.local_decls[RETURN_PLACE] = LocalDecl::with_source_info(tcx.mk_unit(), source_info);
946
947 make_generator_state_argument_indirect(tcx, &mut body);
948
949 // Change the generator argument from &mut to *mut
950 body.local_decls[SELF_ARG] = LocalDecl::with_source_info(
951 tcx.mk_ptr(ty::TypeAndMut { ty: gen_ty, mutbl: hir::Mutability::Mut }),
952 source_info,
953 );
954 if tcx.sess.opts.debugging_opts.mir_emit_retag {
955 // Alias tracking must know we changed the type
956 body.basic_blocks_mut()[START_BLOCK].statements.insert(
957 0,
958 Statement {
959 source_info,
960 kind: StatementKind::Retag(RetagKind::Raw, box Place::from(SELF_ARG)),
961 },
962 )
963 }
964
965 no_landing_pads(tcx, &mut body);
966
967 // Make sure we remove dead blocks to remove
968 // unrelated code from the resume part of the function
969 simplify::remove_dead_blocks(&mut body);
970
971 dump_mir(tcx, None, "generator_drop", &0, source, &body, |_, _| Ok(()));
972
973 body
974 }
975
976 fn insert_term_block<'tcx>(body: &mut Body<'tcx>, kind: TerminatorKind<'tcx>) -> BasicBlock {
977 let source_info = SourceInfo::outermost(body.span);
978 body.basic_blocks_mut().push(BasicBlockData {
979 statements: Vec::new(),
980 terminator: Some(Terminator { source_info, kind }),
981 is_cleanup: false,
982 })
983 }
984
985 fn insert_panic_block<'tcx>(
986 tcx: TyCtxt<'tcx>,
987 body: &mut Body<'tcx>,
988 message: AssertMessage<'tcx>,
989 ) -> BasicBlock {
990 let assert_block = BasicBlock::new(body.basic_blocks().len());
991 let term = TerminatorKind::Assert {
992 cond: Operand::Constant(box Constant {
993 span: body.span,
994 user_ty: None,
995 literal: ty::Const::from_bool(tcx, false),
996 }),
997 expected: true,
998 msg: message,
999 target: assert_block,
1000 cleanup: None,
1001 };
1002
1003 let source_info = SourceInfo::outermost(body.span);
1004 body.basic_blocks_mut().push(BasicBlockData {
1005 statements: Vec::new(),
1006 terminator: Some(Terminator { source_info, kind: term }),
1007 is_cleanup: false,
1008 });
1009
1010 assert_block
1011 }
1012
1013 fn can_return<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>) -> bool {
1014 // Returning from a function with an uninhabited return type is undefined behavior.
1015 if body.return_ty().conservative_is_privately_uninhabited(tcx) {
1016 return false;
1017 }
1018
1019 // If there's a return terminator the function may return.
1020 for block in body.basic_blocks() {
1021 if let TerminatorKind::Return = block.terminator().kind {
1022 return true;
1023 }
1024 }
1025
1026 // Otherwise the function can't return.
1027 false
1028 }
1029
1030 fn can_unwind<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>) -> bool {
1031 // Nothing can unwind when landing pads are off.
1032 if tcx.sess.panic_strategy() == PanicStrategy::Abort {
1033 return false;
1034 }
1035
1036 // Unwinds can only start at certain terminators.
1037 for block in body.basic_blocks() {
1038 match block.terminator().kind {
1039 // These never unwind.
1040 TerminatorKind::Goto { .. }
1041 | TerminatorKind::SwitchInt { .. }
1042 | TerminatorKind::Abort
1043 | TerminatorKind::Return
1044 | TerminatorKind::Unreachable
1045 | TerminatorKind::GeneratorDrop
1046 | TerminatorKind::FalseEdge { .. }
1047 | TerminatorKind::FalseUnwind { .. }
1048 | TerminatorKind::InlineAsm { .. } => {}
1049
1050 // Resume will *continue* unwinding, but if there's no other unwinding terminator it
1051 // will never be reached.
1052 TerminatorKind::Resume => {}
1053
1054 TerminatorKind::Yield { .. } => {
1055 unreachable!("`can_unwind` called before generator transform")
1056 }
1057
1058 // These may unwind.
1059 TerminatorKind::Drop { .. }
1060 | TerminatorKind::DropAndReplace { .. }
1061 | TerminatorKind::Call { .. }
1062 | TerminatorKind::Assert { .. } => return true,
1063 }
1064 }
1065
1066 // If we didn't find an unwinding terminator, the function cannot unwind.
1067 false
1068 }
1069
1070 fn create_generator_resume_function<'tcx>(
1071 tcx: TyCtxt<'tcx>,
1072 transform: TransformVisitor<'tcx>,
1073 source: MirSource<'tcx>,
1074 body: &mut Body<'tcx>,
1075 can_return: bool,
1076 ) {
1077 let can_unwind = can_unwind(tcx, body);
1078
1079 // Poison the generator when it unwinds
1080 if can_unwind {
1081 let source_info = SourceInfo::outermost(body.span);
1082 let poison_block = body.basic_blocks_mut().push(BasicBlockData {
1083 statements: vec![transform.set_discr(VariantIdx::new(POISONED), source_info)],
1084 terminator: Some(Terminator { source_info, kind: TerminatorKind::Resume }),
1085 is_cleanup: true,
1086 });
1087
1088 for (idx, block) in body.basic_blocks_mut().iter_enumerated_mut() {
1089 let source_info = block.terminator().source_info;
1090
1091 if let TerminatorKind::Resume = block.terminator().kind {
1092 // An existing `Resume` terminator is redirected to jump to our dedicated
1093 // "poisoning block" above.
1094 if idx != poison_block {
1095 *block.terminator_mut() = Terminator {
1096 source_info,
1097 kind: TerminatorKind::Goto { target: poison_block },
1098 };
1099 }
1100 } else if !block.is_cleanup {
1101 // Any terminators that *can* unwind but don't have an unwind target set are also
1102 // pointed at our poisoning block (unless they're part of the cleanup path).
1103 if let Some(unwind @ None) = block.terminator_mut().unwind_mut() {
1104 *unwind = Some(poison_block);
1105 }
1106 }
1107 }
1108 }
1109
1110 let mut cases = create_cases(body, &transform, Operation::Resume);
1111
1112 use rustc_middle::mir::AssertKind::{ResumedAfterPanic, ResumedAfterReturn};
1113
1114 // Jump to the entry point on the unresumed
1115 cases.insert(0, (UNRESUMED, BasicBlock::new(0)));
1116
1117 // Panic when resumed on the returned or poisoned state
1118 let generator_kind = body.generator_kind.unwrap();
1119
1120 if can_unwind {
1121 cases.insert(
1122 1,
1123 (POISONED, insert_panic_block(tcx, body, ResumedAfterPanic(generator_kind))),
1124 );
1125 }
1126
1127 if can_return {
1128 cases.insert(
1129 1,
1130 (RETURNED, insert_panic_block(tcx, body, ResumedAfterReturn(generator_kind))),
1131 );
1132 }
1133
1134 insert_switch(body, cases, &transform, TerminatorKind::Unreachable);
1135
1136 make_generator_state_argument_indirect(tcx, body);
1137 make_generator_state_argument_pinned(tcx, body);
1138
1139 no_landing_pads(tcx, body);
1140
1141 // Make sure we remove dead blocks to remove
1142 // unrelated code from the drop part of the function
1143 simplify::remove_dead_blocks(body);
1144
1145 dump_mir(tcx, None, "generator_resume", &0, source, body, |_, _| Ok(()));
1146 }
1147
1148 fn insert_clean_drop(body: &mut Body<'_>) -> BasicBlock {
1149 let return_block = insert_term_block(body, TerminatorKind::Return);
1150
1151 let term =
1152 TerminatorKind::Drop { place: Place::from(SELF_ARG), target: return_block, unwind: None };
1153 let source_info = SourceInfo::outermost(body.span);
1154
1155 // Create a block to destroy an unresumed generators. This can only destroy upvars.
1156 body.basic_blocks_mut().push(BasicBlockData {
1157 statements: Vec::new(),
1158 terminator: Some(Terminator { source_info, kind: term }),
1159 is_cleanup: false,
1160 })
1161 }
1162
1163 /// An operation that can be performed on a generator.
1164 #[derive(PartialEq, Copy, Clone)]
1165 enum Operation {
1166 Resume,
1167 Drop,
1168 }
1169
1170 impl Operation {
1171 fn target_block(self, point: &SuspensionPoint<'_>) -> Option<BasicBlock> {
1172 match self {
1173 Operation::Resume => Some(point.resume),
1174 Operation::Drop => point.drop,
1175 }
1176 }
1177 }
1178
1179 fn create_cases<'tcx>(
1180 body: &mut Body<'tcx>,
1181 transform: &TransformVisitor<'tcx>,
1182 operation: Operation,
1183 ) -> Vec<(usize, BasicBlock)> {
1184 let source_info = SourceInfo::outermost(body.span);
1185
1186 transform
1187 .suspension_points
1188 .iter()
1189 .filter_map(|point| {
1190 // Find the target for this suspension point, if applicable
1191 operation.target_block(point).map(|target| {
1192 let mut statements = Vec::new();
1193
1194 // Create StorageLive instructions for locals with live storage
1195 for i in 0..(body.local_decls.len()) {
1196 if i == 2 {
1197 // The resume argument is live on function entry. Don't insert a
1198 // `StorageLive`, or the following `Assign` will read from uninitialized
1199 // memory.
1200 continue;
1201 }
1202
1203 let l = Local::new(i);
1204 let needs_storage_live = point.storage_liveness.contains(l)
1205 && !transform.remap.contains_key(&l)
1206 && !transform.always_live_locals.contains(l);
1207 if needs_storage_live {
1208 statements
1209 .push(Statement { source_info, kind: StatementKind::StorageLive(l) });
1210 }
1211 }
1212
1213 if operation == Operation::Resume {
1214 // Move the resume argument to the destination place of the `Yield` terminator
1215 let resume_arg = Local::new(2); // 0 = return, 1 = self
1216 statements.push(Statement {
1217 source_info,
1218 kind: StatementKind::Assign(box (
1219 point.resume_arg,
1220 Rvalue::Use(Operand::Move(resume_arg.into())),
1221 )),
1222 });
1223 }
1224
1225 // Then jump to the real target
1226 let block = body.basic_blocks_mut().push(BasicBlockData {
1227 statements,
1228 terminator: Some(Terminator {
1229 source_info,
1230 kind: TerminatorKind::Goto { target },
1231 }),
1232 is_cleanup: false,
1233 });
1234
1235 (point.state, block)
1236 })
1237 })
1238 .collect()
1239 }
1240
1241 impl<'tcx> MirPass<'tcx> for StateTransform {
1242 fn run_pass(&self, tcx: TyCtxt<'tcx>, source: MirSource<'tcx>, body: &mut Body<'tcx>) {
1243 let yield_ty = if let Some(yield_ty) = body.yield_ty {
1244 yield_ty
1245 } else {
1246 // This only applies to generators
1247 return;
1248 };
1249
1250 assert!(body.generator_drop.is_none());
1251
1252 let def_id = source.def_id();
1253
1254 // The first argument is the generator type passed by value
1255 let gen_ty = body.local_decls.raw[1].ty;
1256
1257 // Get the interior types and substs which typeck computed
1258 let (upvars, interior, discr_ty, movable) = match *gen_ty.kind() {
1259 ty::Generator(_, substs, movability) => {
1260 let substs = substs.as_generator();
1261 (
1262 substs.upvar_tys().collect(),
1263 substs.witness(),
1264 substs.discr_ty(tcx),
1265 movability == hir::Movability::Movable,
1266 )
1267 }
1268 _ => {
1269 tcx.sess
1270 .delay_span_bug(body.span, &format!("unexpected generator type {}", gen_ty));
1271 return;
1272 }
1273 };
1274
1275 // Compute GeneratorState<yield_ty, return_ty>
1276 let state_did = tcx.require_lang_item(LangItem::GeneratorState, None);
1277 let state_adt_ref = tcx.adt_def(state_did);
1278 let state_substs = tcx.intern_substs(&[yield_ty.into(), body.return_ty().into()]);
1279 let ret_ty = tcx.mk_adt(state_adt_ref, state_substs);
1280
1281 // We rename RETURN_PLACE which has type mir.return_ty to new_ret_local
1282 // RETURN_PLACE then is a fresh unused local with type ret_ty.
1283 let new_ret_local = replace_local(RETURN_PLACE, ret_ty, body, tcx);
1284
1285 // We also replace the resume argument and insert an `Assign`.
1286 // This is needed because the resume argument `_2` might be live across a `yield`, in which
1287 // case there is no `Assign` to it that the transform can turn into a store to the generator
1288 // state. After the yield the slot in the generator state would then be uninitialized.
1289 let resume_local = Local::new(2);
1290 let new_resume_local =
1291 replace_local(resume_local, body.local_decls[resume_local].ty, body, tcx);
1292
1293 // When first entering the generator, move the resume argument into its new local.
1294 let source_info = SourceInfo::outermost(body.span);
1295 let stmts = &mut body.basic_blocks_mut()[BasicBlock::new(0)].statements;
1296 stmts.insert(
1297 0,
1298 Statement {
1299 source_info,
1300 kind: StatementKind::Assign(box (
1301 new_resume_local.into(),
1302 Rvalue::Use(Operand::Move(resume_local.into())),
1303 )),
1304 },
1305 );
1306
1307 let always_live_locals = storage::AlwaysLiveLocals::new(&body);
1308
1309 let liveness_info =
1310 locals_live_across_suspend_points(tcx, body, source, &always_live_locals, movable);
1311
1312 sanitize_witness(tcx, body, def_id, interior, &upvars, &liveness_info.saved_locals);
1313
1314 if tcx.sess.opts.debugging_opts.validate_mir {
1315 let mut vis = EnsureGeneratorFieldAssignmentsNeverAlias {
1316 assigned_local: None,
1317 saved_locals: &liveness_info.saved_locals,
1318 storage_conflicts: &liveness_info.storage_conflicts,
1319 };
1320
1321 vis.visit_body(body);
1322 }
1323
1324 // Extract locals which are live across suspension point into `layout`
1325 // `remap` gives a mapping from local indices onto generator struct indices
1326 // `storage_liveness` tells us which locals have live storage at suspension points
1327 let (remap, layout, storage_liveness) = compute_layout(liveness_info, body);
1328
1329 let can_return = can_return(tcx, body);
1330
1331 // Run the transformation which converts Places from Local to generator struct
1332 // accesses for locals in `remap`.
1333 // It also rewrites `return x` and `yield y` as writing a new generator state and returning
1334 // GeneratorState::Complete(x) and GeneratorState::Yielded(y) respectively.
1335 let mut transform = TransformVisitor {
1336 tcx,
1337 state_adt_ref,
1338 state_substs,
1339 remap,
1340 storage_liveness,
1341 always_live_locals,
1342 suspension_points: Vec::new(),
1343 new_ret_local,
1344 discr_ty,
1345 };
1346 transform.visit_body(body);
1347
1348 // Update our MIR struct to reflect the changes we've made
1349 body.yield_ty = None;
1350 body.arg_count = 2; // self, resume arg
1351 body.spread_arg = None;
1352 body.generator_layout = Some(layout);
1353
1354 // Insert `drop(generator_struct)` which is used to drop upvars for generators in
1355 // the unresumed state.
1356 // This is expanded to a drop ladder in `elaborate_generator_drops`.
1357 let drop_clean = insert_clean_drop(body);
1358
1359 dump_mir(tcx, None, "generator_pre-elab", &0, source, body, |_, _| Ok(()));
1360
1361 // Expand `drop(generator_struct)` to a drop ladder which destroys upvars.
1362 // If any upvars are moved out of, drop elaboration will handle upvar destruction.
1363 // However we need to also elaborate the code generated by `insert_clean_drop`.
1364 elaborate_generator_drops(tcx, def_id, body);
1365
1366 dump_mir(tcx, None, "generator_post-transform", &0, source, body, |_, _| Ok(()));
1367
1368 // Create a copy of our MIR and use it to create the drop shim for the generator
1369 let drop_shim =
1370 create_generator_drop_shim(tcx, &transform, source, gen_ty, body, drop_clean);
1371
1372 body.generator_drop = Some(box drop_shim);
1373
1374 // Create the Generator::resume function
1375 create_generator_resume_function(tcx, transform, source, body, can_return);
1376 }
1377 }
1378
1379 /// Looks for any assignments between locals (e.g., `_4 = _5`) that will both be converted to fields
1380 /// in the generator state machine but whose storage is not marked as conflicting
1381 ///
1382 /// Validation needs to happen immediately *before* `TransformVisitor` is invoked, not after.
1383 ///
1384 /// This condition would arise when the assignment is the last use of `_5` but the initial
1385 /// definition of `_4` if we weren't extra careful to mark all locals used inside a statement as
1386 /// conflicting. Non-conflicting generator saved locals may be stored at the same location within
1387 /// the generator state machine, which would result in ill-formed MIR: the left-hand and right-hand
1388 /// sides of an assignment may not alias. This caused a miscompilation in [#73137].
1389 ///
1390 /// [#73137]: https://github.com/rust-lang/rust/issues/73137
1391 struct EnsureGeneratorFieldAssignmentsNeverAlias<'a> {
1392 saved_locals: &'a GeneratorSavedLocals,
1393 storage_conflicts: &'a BitMatrix<GeneratorSavedLocal, GeneratorSavedLocal>,
1394 assigned_local: Option<GeneratorSavedLocal>,
1395 }
1396
1397 impl EnsureGeneratorFieldAssignmentsNeverAlias<'_> {
1398 fn saved_local_for_direct_place(&self, place: Place<'_>) -> Option<GeneratorSavedLocal> {
1399 if place.is_indirect() {
1400 return None;
1401 }
1402
1403 self.saved_locals.get(place.local)
1404 }
1405
1406 fn check_assigned_place(&mut self, place: Place<'tcx>, f: impl FnOnce(&mut Self)) {
1407 if let Some(assigned_local) = self.saved_local_for_direct_place(place) {
1408 assert!(self.assigned_local.is_none(), "`check_assigned_place` must not recurse");
1409
1410 self.assigned_local = Some(assigned_local);
1411 f(self);
1412 self.assigned_local = None;
1413 }
1414 }
1415 }
1416
1417 impl Visitor<'tcx> for EnsureGeneratorFieldAssignmentsNeverAlias<'_> {
1418 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
1419 let lhs = match self.assigned_local {
1420 Some(l) => l,
1421 None => {
1422 // This visitor only invokes `visit_place` for the right-hand side of an assignment
1423 // and only after setting `self.assigned_local`. However, the default impl of
1424 // `Visitor::super_body` may call `visit_place` with a `NonUseContext` for places
1425 // with debuginfo. Ignore them here.
1426 assert!(!context.is_use());
1427 return;
1428 }
1429 };
1430
1431 let rhs = match self.saved_local_for_direct_place(*place) {
1432 Some(l) => l,
1433 None => return,
1434 };
1435
1436 if !self.storage_conflicts.contains(lhs, rhs) {
1437 bug!(
1438 "Assignment between generator saved locals whose storage is not \
1439 marked as conflicting: {:?}: {:?} = {:?}",
1440 location,
1441 lhs,
1442 rhs,
1443 );
1444 }
1445 }
1446
1447 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
1448 match &statement.kind {
1449 StatementKind::Assign(box (lhs, rhs)) => {
1450 self.check_assigned_place(*lhs, |this| this.visit_rvalue(rhs, location));
1451 }
1452
1453 // FIXME: Does `llvm_asm!` have any aliasing requirements?
1454 StatementKind::LlvmInlineAsm(_) => {}
1455
1456 StatementKind::FakeRead(..)
1457 | StatementKind::SetDiscriminant { .. }
1458 | StatementKind::StorageLive(_)
1459 | StatementKind::StorageDead(_)
1460 | StatementKind::Retag(..)
1461 | StatementKind::AscribeUserType(..)
1462 | StatementKind::Coverage(..)
1463 | StatementKind::Nop => {}
1464 }
1465 }
1466
1467 fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
1468 // Checking for aliasing in terminators is probably overkill, but until we have actual
1469 // semantics, we should be conservative here.
1470 match &terminator.kind {
1471 TerminatorKind::Call {
1472 func,
1473 args,
1474 destination: Some((dest, _)),
1475 cleanup: _,
1476 from_hir_call: _,
1477 fn_span: _,
1478 } => {
1479 self.check_assigned_place(*dest, |this| {
1480 this.visit_operand(func, location);
1481 for arg in args {
1482 this.visit_operand(arg, location);
1483 }
1484 });
1485 }
1486
1487 TerminatorKind::Yield { value, resume: _, resume_arg, drop: _ } => {
1488 self.check_assigned_place(*resume_arg, |this| this.visit_operand(value, location));
1489 }
1490
1491 // FIXME: Does `asm!` have any aliasing requirements?
1492 TerminatorKind::InlineAsm { .. } => {}
1493
1494 TerminatorKind::Call { .. }
1495 | TerminatorKind::Goto { .. }
1496 | TerminatorKind::SwitchInt { .. }
1497 | TerminatorKind::Resume
1498 | TerminatorKind::Abort
1499 | TerminatorKind::Return
1500 | TerminatorKind::Unreachable
1501 | TerminatorKind::Drop { .. }
1502 | TerminatorKind::DropAndReplace { .. }
1503 | TerminatorKind::Assert { .. }
1504 | TerminatorKind::GeneratorDrop
1505 | TerminatorKind::FalseEdge { .. }
1506 | TerminatorKind::FalseUnwind { .. } => {}
1507 }
1508 }
1509 }