1 //! This is the implementation of the pass which transforms generators into state machines.
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.
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.
22 //! struct Generator {
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
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.
39 //! The pass creates two functions which have a switch on the generator state giving
40 //! the action to take.
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.
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.
52 use crate::dataflow::impls::{
53 MaybeBorrowedLocals, MaybeLiveLocals, MaybeRequiresStorage, MaybeStorageLive,
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::storage;
61 use rustc_data_structures::fx::FxHashMap;
63 use rustc_hir::def_id::DefId;
64 use rustc_hir::lang_items::{GeneratorStateLangItem, PinTypeLangItem};
65 use rustc_index::bit_set::{BitMatrix, BitSet};
66 use rustc_index::vec::{Idx, IndexVec};
67 use rustc_middle::mir::visit::{MutVisitor, PlaceContext, Visitor};
68 use rustc_middle::mir::*;
69 use rustc_middle::ty::subst::SubstsRef;
70 use rustc_middle::ty::GeneratorSubsts;
71 use rustc_middle::ty::{self, AdtDef, Ty, TyCtxt};
72 use rustc_target::abi::VariantIdx;
73 use rustc_target::spec::PanicStrategy;
77 pub struct StateTransform;
79 struct RenameLocalVisitor<'tcx> {
85 impl<'tcx> MutVisitor<'tcx> for RenameLocalVisitor<'tcx> {
86 fn tcx(&self) -> TyCtxt<'tcx> {
90 fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
91 if *local == self.from {
96 fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, location: Location) {
97 match terminator.kind {
98 TerminatorKind::Return => {
99 // Do not replace the implicit `_0` access here, as that's not possible. The
100 // transform already handles `return` correctly.
102 _ => self.super_terminator(terminator, location),
107 struct DerefArgVisitor<'tcx> {
111 impl<'tcx> MutVisitor<'tcx> for DerefArgVisitor<'tcx> {
112 fn tcx(&self) -> TyCtxt<'tcx> {
116 fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
117 assert_ne!(*local, SELF_ARG);
120 fn visit_place(&mut self, place: &mut Place<'tcx>, context: PlaceContext, location: Location) {
121 if place.local == SELF_ARG {
126 projection: self.tcx().intern_place_elems(&[ProjectionElem::Deref]),
131 self.visit_local(&mut place.local, context, location);
133 for elem in place.projection.iter() {
134 if let PlaceElem::Index(local) = elem {
135 assert_ne!(local, SELF_ARG);
142 struct PinArgVisitor<'tcx> {
143 ref_gen_ty: Ty<'tcx>,
147 impl<'tcx> MutVisitor<'tcx> for PinArgVisitor<'tcx> {
148 fn tcx(&self) -> TyCtxt<'tcx> {
152 fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
153 assert_ne!(*local, SELF_ARG);
156 fn visit_place(&mut self, place: &mut Place<'tcx>, context: PlaceContext, location: Location) {
157 if place.local == SELF_ARG {
162 projection: self.tcx().intern_place_elems(&[ProjectionElem::Field(
170 self.visit_local(&mut place.local, context, location);
172 for elem in place.projection.iter() {
173 if let PlaceElem::Index(local) = elem {
174 assert_ne!(local, SELF_ARG);
181 fn replace_base<'tcx>(place: &mut Place<'tcx>, new_base: Place<'tcx>, tcx: TyCtxt<'tcx>) {
182 place.local = new_base.local;
184 let mut new_projection = new_base.projection.to_vec();
185 new_projection.append(&mut place.projection.to_vec());
187 place.projection = tcx.intern_place_elems(&new_projection);
190 const SELF_ARG: Local = Local::from_u32(1);
192 /// Generator has not been resumed yet.
193 const UNRESUMED: usize = GeneratorSubsts::UNRESUMED;
194 /// Generator has returned / is completed.
195 const RETURNED: usize = GeneratorSubsts::RETURNED;
196 /// Generator has panicked and is poisoned.
197 const POISONED: usize = GeneratorSubsts::POISONED;
199 /// A `yield` point in the generator.
200 struct SuspensionPoint<'tcx> {
201 /// State discriminant used when suspending or resuming at this point.
203 /// The block to jump to after resumption.
205 /// Where to move the resume argument after resumption.
206 resume_arg: Place<'tcx>,
207 /// Which block to jump to if the generator is dropped in this state.
208 drop: Option<BasicBlock>,
209 /// Set of locals that have live storage while at this suspension point.
210 storage_liveness: BitSet<Local>,
213 struct TransformVisitor<'tcx> {
215 state_adt_ref: &'tcx AdtDef,
216 state_substs: SubstsRef<'tcx>,
218 // The type of the discriminant in the generator struct
221 // Mapping from Local to (type of local, generator struct index)
222 // FIXME(eddyb) This should use `IndexVec<Local, Option<_>>`.
223 remap: FxHashMap<Local, (Ty<'tcx>, VariantIdx, usize)>,
225 // A map from a suspension point in a block to the locals which have live storage at that point
226 storage_liveness: IndexVec<BasicBlock, Option<BitSet<Local>>>,
228 // A list of suspension points, generated during the transform
229 suspension_points: Vec<SuspensionPoint<'tcx>>,
231 // The set of locals that have no `StorageLive`/`StorageDead` annotations.
232 always_live_locals: storage::AlwaysLiveLocals,
234 // The original RETURN_PLACE local
235 new_ret_local: Local,
238 impl TransformVisitor<'tcx> {
239 // Make a GeneratorState rvalue
240 fn make_state(&self, idx: VariantIdx, val: Operand<'tcx>) -> Rvalue<'tcx> {
241 let adt = AggregateKind::Adt(self.state_adt_ref, idx, self.state_substs, None, None);
242 Rvalue::Aggregate(box adt, vec![val])
245 // Create a Place referencing a generator struct field
246 fn make_field(&self, variant_index: VariantIdx, idx: usize, ty: Ty<'tcx>) -> Place<'tcx> {
247 let self_place = Place::from(SELF_ARG);
248 let base = self.tcx.mk_place_downcast_unnamed(self_place, variant_index);
249 let mut projection = base.projection.to_vec();
250 projection.push(ProjectionElem::Field(Field::new(idx), ty));
252 Place { local: base.local, projection: self.tcx.intern_place_elems(&projection) }
255 // Create a statement which changes the discriminant
256 fn set_discr(&self, state_disc: VariantIdx, source_info: SourceInfo) -> Statement<'tcx> {
257 let self_place = Place::from(SELF_ARG);
260 kind: StatementKind::SetDiscriminant {
261 place: box self_place,
262 variant_index: state_disc,
267 // Create a statement which reads the discriminant into a temporary
268 fn get_discr(&self, body: &mut Body<'tcx>) -> (Statement<'tcx>, Place<'tcx>) {
269 let temp_decl = LocalDecl::new(self.discr_ty, body.span).internal();
270 let local_decls_len = body.local_decls.push(temp_decl);
271 let temp = Place::from(local_decls_len);
273 let self_place = Place::from(SELF_ARG);
274 let assign = Statement {
275 source_info: SourceInfo::outermost(body.span),
276 kind: StatementKind::Assign(box (temp, Rvalue::Discriminant(self_place))),
282 impl MutVisitor<'tcx> for TransformVisitor<'tcx> {
283 fn tcx(&self) -> TyCtxt<'tcx> {
287 fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
288 assert_eq!(self.remap.get(local), None);
293 place: &mut Place<'tcx>,
294 _context: PlaceContext,
297 // Replace an Local in the remap with a generator struct access
298 if let Some(&(ty, variant_index, idx)) = self.remap.get(&place.local) {
299 replace_base(place, self.make_field(variant_index, idx, ty), self.tcx);
303 fn visit_basic_block_data(&mut self, block: BasicBlock, data: &mut BasicBlockData<'tcx>) {
304 // Remove StorageLive and StorageDead statements for remapped locals
305 data.retain_statements(|s| match s.kind {
306 StatementKind::StorageLive(l) | StatementKind::StorageDead(l) => {
307 !self.remap.contains_key(&l)
312 let ret_val = match data.terminator().kind {
313 TerminatorKind::Return => Some((
316 Operand::Move(Place::from(self.new_ret_local)),
319 TerminatorKind::Yield { ref value, resume, resume_arg, drop } => {
320 Some((VariantIdx::new(0), Some((resume, resume_arg)), value.clone(), drop))
325 if let Some((state_idx, resume, v, drop)) = ret_val {
326 let source_info = data.terminator().source_info;
327 // We must assign the value first in case it gets declared dead below
328 data.statements.push(Statement {
330 kind: StatementKind::Assign(box (
331 Place::return_place(),
332 self.make_state(state_idx, v),
335 let state = if let Some((resume, resume_arg)) = resume {
337 let state = 3 + self.suspension_points.len();
339 // The resume arg target location might itself be remapped if its base local is
340 // live across a yield.
342 if let Some(&(ty, variant, idx)) = self.remap.get(&resume_arg.local) {
343 self.make_field(variant, idx, ty)
348 self.suspension_points.push(SuspensionPoint {
353 storage_liveness: self.storage_liveness[block].clone().unwrap(),
356 VariantIdx::new(state)
359 VariantIdx::new(RETURNED) // state for returned
361 data.statements.push(self.set_discr(state, source_info));
362 data.terminator_mut().kind = TerminatorKind::Return;
365 self.super_basic_block_data(block, data);
369 fn make_generator_state_argument_indirect<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
370 let gen_ty = body.local_decls.raw[1].ty;
373 tcx.mk_ref(tcx.lifetimes.re_erased, ty::TypeAndMut { ty: gen_ty, mutbl: Mutability::Mut });
375 // Replace the by value generator argument
376 body.local_decls.raw[1].ty = ref_gen_ty;
378 // Add a deref to accesses of the generator state
379 DerefArgVisitor { tcx }.visit_body(body);
382 fn make_generator_state_argument_pinned<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
383 let ref_gen_ty = body.local_decls.raw[1].ty;
385 let pin_did = tcx.require_lang_item(PinTypeLangItem, Some(body.span));
386 let pin_adt_ref = tcx.adt_def(pin_did);
387 let substs = tcx.intern_substs(&[ref_gen_ty.into()]);
388 let pin_ref_gen_ty = tcx.mk_adt(pin_adt_ref, substs);
390 // Replace the by ref generator argument
391 body.local_decls.raw[1].ty = pin_ref_gen_ty;
393 // Add the Pin field access to accesses of the generator state
394 PinArgVisitor { ref_gen_ty, tcx }.visit_body(body);
397 /// Allocates a new local and replaces all references of `local` with it. Returns the new local.
399 /// `local` will be changed to a new local decl with type `ty`.
401 /// Note that the new local will be uninitialized. It is the caller's responsibility to assign some
402 /// valid value to it before its first use.
403 fn replace_local<'tcx>(
406 body: &mut Body<'tcx>,
409 let new_decl = LocalDecl::new(ty, body.span);
410 let new_local = body.local_decls.push(new_decl);
411 body.local_decls.swap(local, new_local);
413 RenameLocalVisitor { from: local, to: new_local, tcx }.visit_body(body);
418 struct LivenessInfo {
419 /// Which locals are live across any suspension point.
420 saved_locals: GeneratorSavedLocals,
422 /// The set of saved locals live at each suspension point.
423 live_locals_at_suspension_points: Vec<BitSet<GeneratorSavedLocal>>,
425 /// Parallel vec to the above with SourceInfo for each yield terminator.
426 source_info_at_suspension_points: Vec<SourceInfo>,
428 /// For every saved local, the set of other saved locals that are
429 /// storage-live at the same time as this local. We cannot overlap locals in
430 /// the layout which have conflicting storage.
431 storage_conflicts: BitMatrix<GeneratorSavedLocal, GeneratorSavedLocal>,
433 /// For every suspending block, the locals which are storage-live across
434 /// that suspension point.
435 storage_liveness: IndexVec<BasicBlock, Option<BitSet<Local>>>,
438 fn locals_live_across_suspend_points(
441 source: MirSource<'tcx>,
442 always_live_locals: &storage::AlwaysLiveLocals,
445 let def_id = source.def_id();
446 let body_ref: &Body<'_> = &body;
448 // Calculate when MIR locals have live storage. This gives us an upper bound of their
450 let mut storage_live = MaybeStorageLive::new(always_live_locals.clone())
451 .into_engine(tcx, body_ref, def_id)
452 .iterate_to_fixpoint()
453 .into_results_cursor(body_ref);
455 // Calculate the MIR locals which have been previously
456 // borrowed (even if they are still active).
457 let borrowed_locals_results =
458 MaybeBorrowedLocals::all_borrows().into_engine(tcx, body_ref, def_id).iterate_to_fixpoint();
460 let mut borrowed_locals_cursor =
461 dataflow::ResultsCursor::new(body_ref, &borrowed_locals_results);
463 // Calculate the MIR locals that we actually need to keep storage around
465 let requires_storage_results = MaybeRequiresStorage::new(body, &borrowed_locals_results)
466 .into_engine(tcx, body_ref, def_id)
467 .iterate_to_fixpoint();
468 let mut requires_storage_cursor =
469 dataflow::ResultsCursor::new(body_ref, &requires_storage_results);
471 // Calculate the liveness of MIR locals ignoring borrows.
472 let mut liveness = MaybeLiveLocals
473 .into_engine(tcx, body_ref, def_id)
474 .iterate_to_fixpoint()
475 .into_results_cursor(body_ref);
477 let mut storage_liveness_map = IndexVec::from_elem(None, body.basic_blocks());
478 let mut live_locals_at_suspension_points = Vec::new();
479 let mut source_info_at_suspension_points = Vec::new();
480 let mut live_locals_at_any_suspension_point = BitSet::new_empty(body.local_decls.len());
482 for (block, data) in body.basic_blocks().iter_enumerated() {
483 if let TerminatorKind::Yield { .. } = data.terminator().kind {
484 let loc = Location { block, statement_index: data.statements.len() };
486 liveness.seek_to_block_end(block);
487 let mut live_locals = liveness.get().clone();
490 // The `liveness` variable contains the liveness of MIR locals ignoring borrows.
491 // This is correct for movable generators since borrows cannot live across
492 // suspension points. However for immovable generators we need to account for
493 // borrows, so we conseratively assume that all borrowed locals are live until
494 // we find a StorageDead statement referencing the locals.
495 // To do this we just union our `liveness` result with `borrowed_locals`, which
496 // contains all the locals which has been borrowed before this suspension point.
497 // If a borrow is converted to a raw reference, we must also assume that it lives
498 // forever. Note that the final liveness is still bounded by the storage liveness
499 // of the local, which happens using the `intersect` operation below.
500 borrowed_locals_cursor.seek_before_primary_effect(loc);
501 live_locals.union(borrowed_locals_cursor.get());
504 // Store the storage liveness for later use so we can restore the state
505 // after a suspension point
506 storage_live.seek_before_primary_effect(loc);
507 storage_liveness_map[block] = Some(storage_live.get().clone());
509 // Locals live are live at this point only if they are used across
510 // suspension points (the `liveness` variable)
511 // and their storage is required (the `storage_required` variable)
512 requires_storage_cursor.seek_before_primary_effect(loc);
513 live_locals.intersect(requires_storage_cursor.get());
515 // The generator argument is ignored.
516 live_locals.remove(SELF_ARG);
518 debug!("loc = {:?}, live_locals = {:?}", loc, live_locals);
520 // Add the locals live at this suspension point to the set of locals which live across
521 // any suspension points
522 live_locals_at_any_suspension_point.union(&live_locals);
524 live_locals_at_suspension_points.push(live_locals);
525 source_info_at_suspension_points.push(data.terminator().source_info);
529 debug!("live_locals_anywhere = {:?}", live_locals_at_any_suspension_point);
530 let saved_locals = GeneratorSavedLocals(live_locals_at_any_suspension_point);
532 // Renumber our liveness_map bitsets to include only the locals we are
534 let live_locals_at_suspension_points = live_locals_at_suspension_points
536 .map(|live_here| saved_locals.renumber_bitset(&live_here))
539 let storage_conflicts = compute_storage_conflicts(
542 always_live_locals.clone(),
543 requires_storage_results,
548 live_locals_at_suspension_points,
549 source_info_at_suspension_points,
551 storage_liveness: storage_liveness_map,
555 /// The set of `Local`s that must be saved across yield points.
557 /// `GeneratorSavedLocal` is indexed in terms of the elements in this set;
558 /// i.e. `GeneratorSavedLocal::new(1)` corresponds to the second local
559 /// included in this set.
560 struct GeneratorSavedLocals(BitSet<Local>);
562 impl GeneratorSavedLocals {
563 /// Returns an iterator over each `GeneratorSavedLocal` along with the `Local` it corresponds
565 fn iter_enumerated(&self) -> impl '_ + Iterator<Item = (GeneratorSavedLocal, Local)> {
566 self.iter().enumerate().map(|(i, l)| (GeneratorSavedLocal::from(i), l))
569 /// Transforms a `BitSet<Local>` that contains only locals saved across yield points to the
570 /// equivalent `BitSet<GeneratorSavedLocal>`.
571 fn renumber_bitset(&self, input: &BitSet<Local>) -> BitSet<GeneratorSavedLocal> {
572 assert!(self.superset(&input), "{:?} not a superset of {:?}", self.0, input);
573 let mut out = BitSet::new_empty(self.count());
574 for (saved_local, local) in self.iter_enumerated() {
575 if input.contains(local) {
576 out.insert(saved_local);
582 fn get(&self, local: Local) -> Option<GeneratorSavedLocal> {
583 if !self.contains(local) {
587 let idx = self.iter().take_while(|&l| l < local).count();
588 Some(GeneratorSavedLocal::new(idx))
592 impl ops::Deref for GeneratorSavedLocals {
593 type Target = BitSet<Local>;
595 fn deref(&self) -> &Self::Target {
600 /// For every saved local, looks for which locals are StorageLive at the same
601 /// time. Generates a bitset for every local of all the other locals that may be
602 /// StorageLive simultaneously with that local. This is used in the layout
603 /// computation; see `GeneratorLayout` for more.
604 fn compute_storage_conflicts(
605 body: &'mir Body<'tcx>,
606 saved_locals: &GeneratorSavedLocals,
607 always_live_locals: storage::AlwaysLiveLocals,
608 requires_storage: dataflow::Results<'tcx, MaybeRequiresStorage<'mir, 'tcx>>,
609 ) -> BitMatrix<GeneratorSavedLocal, GeneratorSavedLocal> {
610 assert_eq!(body.local_decls.len(), saved_locals.domain_size());
612 debug!("compute_storage_conflicts({:?})", body.span);
613 debug!("always_live = {:?}", always_live_locals);
615 // Locals that are always live or ones that need to be stored across
616 // suspension points are not eligible for overlap.
617 let mut ineligible_locals = always_live_locals.into_inner();
618 ineligible_locals.intersect(saved_locals);
620 // Compute the storage conflicts for all eligible locals.
621 let mut visitor = StorageConflictVisitor {
623 saved_locals: &saved_locals,
624 local_conflicts: BitMatrix::from_row_n(&ineligible_locals, body.local_decls.len()),
627 requires_storage.visit_reachable_with(body, &mut visitor);
629 let local_conflicts = visitor.local_conflicts;
631 // Compress the matrix using only stored locals (Local -> GeneratorSavedLocal).
633 // NOTE: Today we store a full conflict bitset for every local. Technically
634 // this is twice as many bits as we need, since the relation is symmetric.
635 // However, in practice these bitsets are not usually large. The layout code
636 // also needs to keep track of how many conflicts each local has, so it's
637 // simpler to keep it this way for now.
638 let mut storage_conflicts = BitMatrix::new(saved_locals.count(), saved_locals.count());
639 for (saved_local_a, local_a) in saved_locals.iter_enumerated() {
640 if ineligible_locals.contains(local_a) {
641 // Conflicts with everything.
642 storage_conflicts.insert_all_into_row(saved_local_a);
644 // Keep overlap information only for stored locals.
645 for (saved_local_b, local_b) in saved_locals.iter_enumerated() {
646 if local_conflicts.contains(local_a, local_b) {
647 storage_conflicts.insert(saved_local_a, saved_local_b);
655 struct StorageConflictVisitor<'mir, 'tcx, 's> {
656 body: &'mir Body<'tcx>,
657 saved_locals: &'s GeneratorSavedLocals,
658 // FIXME(tmandry): Consider using sparse bitsets here once we have good
659 // benchmarks for generators.
660 local_conflicts: BitMatrix<Local, Local>,
663 impl dataflow::ResultsVisitor<'mir, 'tcx> for StorageConflictVisitor<'mir, 'tcx, '_> {
664 type FlowState = BitSet<Local>;
666 fn visit_statement_before_primary_effect(
668 state: &Self::FlowState,
669 _statement: &'mir Statement<'tcx>,
672 self.apply_state(state, loc);
675 fn visit_terminator_before_primary_effect(
677 state: &Self::FlowState,
678 _terminator: &'mir Terminator<'tcx>,
681 self.apply_state(state, loc);
685 impl<'body, 'tcx, 's> StorageConflictVisitor<'body, 'tcx, 's> {
686 fn apply_state(&mut self, flow_state: &BitSet<Local>, loc: Location) {
687 // Ignore unreachable blocks.
688 if self.body.basic_blocks()[loc.block].terminator().kind == TerminatorKind::Unreachable {
692 let mut eligible_storage_live = flow_state.clone();
693 eligible_storage_live.intersect(&self.saved_locals);
695 for local in eligible_storage_live.iter() {
696 self.local_conflicts.union_row_with(&eligible_storage_live, local);
699 if eligible_storage_live.count() > 1 {
700 trace!("at {:?}, eligible_storage_live={:?}", loc, eligible_storage_live);
705 /// Validates the typeck view of the generator against the actual set of types saved between
707 fn sanitize_witness<'tcx>(
712 upvars: &Vec<Ty<'tcx>>,
713 saved_locals: &GeneratorSavedLocals,
715 let allowed_upvars = tcx.erase_regions(upvars);
716 let allowed = match witness.kind {
717 ty::GeneratorWitness(s) => tcx.erase_late_bound_regions(&s),
719 tcx.sess.delay_span_bug(
721 &format!("unexpected generator witness type {:?}", witness.kind),
727 let param_env = tcx.param_env(did);
729 for (local, decl) in body.local_decls.iter_enumerated() {
730 // Ignore locals which are internal or not saved between yields.
731 if !saved_locals.contains(local) || decl.internal {
734 let decl_ty = tcx.normalize_erasing_regions(param_env, decl.ty);
736 // Sanity check that typeck knows about the type of locals which are
737 // live across a suspension point
738 if !allowed.contains(&decl_ty) && !allowed_upvars.contains(&decl_ty) {
741 "Broken MIR: generator contains type {} in MIR, \
742 but typeck only knows about {}",
750 fn compute_layout<'tcx>(
751 liveness: LivenessInfo,
752 body: &mut Body<'tcx>,
754 FxHashMap<Local, (Ty<'tcx>, VariantIdx, usize)>,
755 GeneratorLayout<'tcx>,
756 IndexVec<BasicBlock, Option<BitSet<Local>>>,
760 live_locals_at_suspension_points,
761 source_info_at_suspension_points,
766 // Gather live local types and their indices.
767 let mut locals = IndexVec::<GeneratorSavedLocal, _>::new();
768 let mut tys = IndexVec::<GeneratorSavedLocal, _>::new();
769 for (saved_local, local) in saved_locals.iter_enumerated() {
771 tys.push(body.local_decls[local].ty);
772 debug!("generator saved local {:?} => {:?}", saved_local, local);
775 // Leave empty variants for the UNRESUMED, RETURNED, and POISONED states.
776 // In debuginfo, these will correspond to the beginning (UNRESUMED) or end
777 // (RETURNED, POISONED) of the function.
778 const RESERVED_VARIANTS: usize = 3;
779 let body_span = body.source_scopes[OUTERMOST_SOURCE_SCOPE].span;
780 let mut variant_source_info: IndexVec<VariantIdx, SourceInfo> = [
781 SourceInfo::outermost(body_span.shrink_to_lo()),
782 SourceInfo::outermost(body_span.shrink_to_hi()),
783 SourceInfo::outermost(body_span.shrink_to_hi()),
789 // Build the generator variant field list.
790 // Create a map from local indices to generator struct indices.
791 let mut variant_fields: IndexVec<VariantIdx, IndexVec<Field, GeneratorSavedLocal>> =
792 iter::repeat(IndexVec::new()).take(RESERVED_VARIANTS).collect();
793 let mut remap = FxHashMap::default();
794 for (suspension_point_idx, live_locals) in live_locals_at_suspension_points.iter().enumerate() {
795 let variant_index = VariantIdx::from(RESERVED_VARIANTS + suspension_point_idx);
796 let mut fields = IndexVec::new();
797 for (idx, saved_local) in live_locals.iter().enumerate() {
798 fields.push(saved_local);
799 // Note that if a field is included in multiple variants, we will
800 // just use the first one here. That's fine; fields do not move
801 // around inside generators, so it doesn't matter which variant
802 // index we access them by.
803 remap.entry(locals[saved_local]).or_insert((tys[saved_local], variant_index, idx));
805 variant_fields.push(fields);
806 variant_source_info.push(source_info_at_suspension_points[suspension_point_idx]);
808 debug!("generator variant_fields = {:?}", variant_fields);
809 debug!("generator storage_conflicts = {:#?}", storage_conflicts);
812 GeneratorLayout { field_tys: tys, variant_fields, variant_source_info, storage_conflicts };
814 (remap, layout, storage_liveness)
817 /// Replaces the entry point of `body` with a block that switches on the generator discriminant and
818 /// dispatches to blocks according to `cases`.
820 /// After this function, the former entry point of the function will be bb1.
821 fn insert_switch<'tcx>(
822 body: &mut Body<'tcx>,
823 cases: Vec<(usize, BasicBlock)>,
824 transform: &TransformVisitor<'tcx>,
825 default: TerminatorKind<'tcx>,
827 let default_block = insert_term_block(body, default);
828 let (assign, discr) = transform.get_discr(body);
829 let switch = TerminatorKind::SwitchInt {
830 discr: Operand::Move(discr),
831 switch_ty: transform.discr_ty,
832 values: Cow::from(cases.iter().map(|&(i, _)| i as u128).collect::<Vec<_>>()),
833 targets: cases.iter().map(|&(_, d)| d).chain(iter::once(default_block)).collect(),
836 let source_info = SourceInfo::outermost(body.span);
837 body.basic_blocks_mut().raw.insert(
840 statements: vec![assign],
841 terminator: Some(Terminator { source_info, kind: switch }),
846 let blocks = body.basic_blocks_mut().iter_mut();
848 for target in blocks.flat_map(|b| b.terminator_mut().successors_mut()) {
849 *target = BasicBlock::new(target.index() + 1);
853 fn elaborate_generator_drops<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, body: &mut Body<'tcx>) {
854 use crate::shim::DropShimElaborator;
855 use crate::util::elaborate_drops::{elaborate_drop, Unwind};
856 use crate::util::patch::MirPatch;
858 // Note that `elaborate_drops` only drops the upvars of a generator, and
859 // this is ok because `open_drop` can only be reached within that own
860 // generator's resume function.
862 let param_env = tcx.param_env(def_id);
864 let mut elaborator = DropShimElaborator { body, patch: MirPatch::new(body), tcx, param_env };
866 for (block, block_data) in body.basic_blocks().iter_enumerated() {
867 let (target, unwind, source_info) = match block_data.terminator() {
868 Terminator { source_info, kind: TerminatorKind::Drop { place, target, unwind } } => {
869 if let Some(local) = place.as_local() {
870 if local == SELF_ARG {
871 (target, unwind, source_info)
881 let unwind = if block_data.is_cleanup {
884 Unwind::To(unwind.unwrap_or_else(|| elaborator.patch.resume_block()))
889 Place::from(SELF_ARG),
896 elaborator.patch.apply(body);
899 fn create_generator_drop_shim<'tcx>(
901 transform: &TransformVisitor<'tcx>,
902 source: MirSource<'tcx>,
904 body: &mut Body<'tcx>,
905 drop_clean: BasicBlock,
907 let mut body = body.clone();
908 body.arg_count = 1; // make sure the resume argument is not included here
910 let source_info = SourceInfo::outermost(body.span);
912 let mut cases = create_cases(&mut body, transform, Operation::Drop);
914 cases.insert(0, (UNRESUMED, drop_clean));
916 // The returned state and the poisoned state fall through to the default
917 // case which is just to return
919 insert_switch(&mut body, cases, &transform, TerminatorKind::Return);
921 for block in body.basic_blocks_mut() {
922 let kind = &mut block.terminator_mut().kind;
923 if let TerminatorKind::GeneratorDrop = *kind {
924 *kind = TerminatorKind::Return;
928 // Replace the return variable
929 body.local_decls[RETURN_PLACE] = LocalDecl::with_source_info(tcx.mk_unit(), source_info);
931 make_generator_state_argument_indirect(tcx, &mut body);
933 // Change the generator argument from &mut to *mut
934 body.local_decls[SELF_ARG] = LocalDecl::with_source_info(
935 tcx.mk_ptr(ty::TypeAndMut { ty: gen_ty, mutbl: hir::Mutability::Mut }),
938 if tcx.sess.opts.debugging_opts.mir_emit_retag {
939 // Alias tracking must know we changed the type
940 body.basic_blocks_mut()[START_BLOCK].statements.insert(
944 kind: StatementKind::Retag(RetagKind::Raw, box Place::from(SELF_ARG)),
949 no_landing_pads(tcx, &mut body);
951 // Make sure we remove dead blocks to remove
952 // unrelated code from the resume part of the function
953 simplify::remove_dead_blocks(&mut body);
955 dump_mir(tcx, None, "generator_drop", &0, source, &body, |_, _| Ok(()));
960 fn insert_term_block<'tcx>(body: &mut Body<'tcx>, kind: TerminatorKind<'tcx>) -> BasicBlock {
961 let source_info = SourceInfo::outermost(body.span);
962 body.basic_blocks_mut().push(BasicBlockData {
963 statements: Vec::new(),
964 terminator: Some(Terminator { source_info, kind }),
969 fn insert_panic_block<'tcx>(
971 body: &mut Body<'tcx>,
972 message: AssertMessage<'tcx>,
974 let assert_block = BasicBlock::new(body.basic_blocks().len());
975 let term = TerminatorKind::Assert {
976 cond: Operand::Constant(box Constant {
979 literal: ty::Const::from_bool(tcx, false),
983 target: assert_block,
987 let source_info = SourceInfo::outermost(body.span);
988 body.basic_blocks_mut().push(BasicBlockData {
989 statements: Vec::new(),
990 terminator: Some(Terminator { source_info, kind: term }),
997 fn can_return<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>) -> bool {
998 // Returning from a function with an uninhabited return type is undefined behavior.
999 if body.return_ty().conservative_is_privately_uninhabited(tcx) {
1003 // If there's a return terminator the function may return.
1004 for block in body.basic_blocks() {
1005 if let TerminatorKind::Return = block.terminator().kind {
1010 // Otherwise the function can't return.
1014 fn can_unwind<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>) -> bool {
1015 // Nothing can unwind when landing pads are off.
1016 if tcx.sess.panic_strategy() == PanicStrategy::Abort {
1020 // Unwinds can only start at certain terminators.
1021 for block in body.basic_blocks() {
1022 match block.terminator().kind {
1023 // These never unwind.
1024 TerminatorKind::Goto { .. }
1025 | TerminatorKind::SwitchInt { .. }
1026 | TerminatorKind::Abort
1027 | TerminatorKind::Return
1028 | TerminatorKind::Unreachable
1029 | TerminatorKind::GeneratorDrop
1030 | TerminatorKind::FalseEdge { .. }
1031 | TerminatorKind::FalseUnwind { .. }
1032 | TerminatorKind::InlineAsm { .. } => {}
1034 // Resume will *continue* unwinding, but if there's no other unwinding terminator it
1035 // will never be reached.
1036 TerminatorKind::Resume => {}
1038 TerminatorKind::Yield { .. } => {
1039 unreachable!("`can_unwind` called before generator transform")
1042 // These may unwind.
1043 TerminatorKind::Drop { .. }
1044 | TerminatorKind::DropAndReplace { .. }
1045 | TerminatorKind::Call { .. }
1046 | TerminatorKind::Assert { .. } => return true,
1050 // If we didn't find an unwinding terminator, the function cannot unwind.
1054 fn create_generator_resume_function<'tcx>(
1056 transform: TransformVisitor<'tcx>,
1057 source: MirSource<'tcx>,
1058 body: &mut Body<'tcx>,
1061 let can_unwind = can_unwind(tcx, body);
1063 // Poison the generator when it unwinds
1065 let source_info = SourceInfo::outermost(body.span);
1066 let poison_block = body.basic_blocks_mut().push(BasicBlockData {
1067 statements: vec![transform.set_discr(VariantIdx::new(POISONED), source_info)],
1068 terminator: Some(Terminator { source_info, kind: TerminatorKind::Resume }),
1072 for (idx, block) in body.basic_blocks_mut().iter_enumerated_mut() {
1073 let source_info = block.terminator().source_info;
1075 if let TerminatorKind::Resume = block.terminator().kind {
1076 // An existing `Resume` terminator is redirected to jump to our dedicated
1077 // "poisoning block" above.
1078 if idx != poison_block {
1079 *block.terminator_mut() = Terminator {
1081 kind: TerminatorKind::Goto { target: poison_block },
1084 } else if !block.is_cleanup {
1085 // Any terminators that *can* unwind but don't have an unwind target set are also
1086 // pointed at our poisoning block (unless they're part of the cleanup path).
1087 if let Some(unwind @ None) = block.terminator_mut().unwind_mut() {
1088 *unwind = Some(poison_block);
1094 let mut cases = create_cases(body, &transform, Operation::Resume);
1096 use rustc_middle::mir::AssertKind::{ResumedAfterPanic, ResumedAfterReturn};
1098 // Jump to the entry point on the unresumed
1099 cases.insert(0, (UNRESUMED, BasicBlock::new(0)));
1101 // Panic when resumed on the returned or poisoned state
1102 let generator_kind = body.generator_kind.unwrap();
1107 (POISONED, insert_panic_block(tcx, body, ResumedAfterPanic(generator_kind))),
1114 (RETURNED, insert_panic_block(tcx, body, ResumedAfterReturn(generator_kind))),
1118 insert_switch(body, cases, &transform, TerminatorKind::Unreachable);
1120 make_generator_state_argument_indirect(tcx, body);
1121 make_generator_state_argument_pinned(tcx, body);
1123 no_landing_pads(tcx, body);
1125 // Make sure we remove dead blocks to remove
1126 // unrelated code from the drop part of the function
1127 simplify::remove_dead_blocks(body);
1129 dump_mir(tcx, None, "generator_resume", &0, source, body, |_, _| Ok(()));
1132 fn insert_clean_drop(body: &mut Body<'_>) -> BasicBlock {
1133 let return_block = insert_term_block(body, TerminatorKind::Return);
1136 TerminatorKind::Drop { place: Place::from(SELF_ARG), target: return_block, unwind: None };
1137 let source_info = SourceInfo::outermost(body.span);
1139 // Create a block to destroy an unresumed generators. This can only destroy upvars.
1140 body.basic_blocks_mut().push(BasicBlockData {
1141 statements: Vec::new(),
1142 terminator: Some(Terminator { source_info, kind: term }),
1147 /// An operation that can be performed on a generator.
1148 #[derive(PartialEq, Copy, Clone)]
1155 fn target_block(self, point: &SuspensionPoint<'_>) -> Option<BasicBlock> {
1157 Operation::Resume => Some(point.resume),
1158 Operation::Drop => point.drop,
1163 fn create_cases<'tcx>(
1164 body: &mut Body<'tcx>,
1165 transform: &TransformVisitor<'tcx>,
1166 operation: Operation,
1167 ) -> Vec<(usize, BasicBlock)> {
1168 let source_info = SourceInfo::outermost(body.span);
1173 .filter_map(|point| {
1174 // Find the target for this suspension point, if applicable
1175 operation.target_block(point).map(|target| {
1176 let mut statements = Vec::new();
1178 // Create StorageLive instructions for locals with live storage
1179 for i in 0..(body.local_decls.len()) {
1181 // The resume argument is live on function entry. Don't insert a
1182 // `StorageLive`, or the following `Assign` will read from uninitialized
1187 let l = Local::new(i);
1188 let needs_storage_live = point.storage_liveness.contains(l)
1189 && !transform.remap.contains_key(&l)
1190 && !transform.always_live_locals.contains(l);
1191 if needs_storage_live {
1193 .push(Statement { source_info, kind: StatementKind::StorageLive(l) });
1197 if operation == Operation::Resume {
1198 // Move the resume argument to the destination place of the `Yield` terminator
1199 let resume_arg = Local::new(2); // 0 = return, 1 = self
1200 statements.push(Statement {
1202 kind: StatementKind::Assign(box (
1204 Rvalue::Use(Operand::Move(resume_arg.into())),
1209 // Then jump to the real target
1210 let block = body.basic_blocks_mut().push(BasicBlockData {
1212 terminator: Some(Terminator {
1214 kind: TerminatorKind::Goto { target },
1219 (point.state, block)
1225 impl<'tcx> MirPass<'tcx> for StateTransform {
1226 fn run_pass(&self, tcx: TyCtxt<'tcx>, source: MirSource<'tcx>, body: &mut Body<'tcx>) {
1227 let yield_ty = if let Some(yield_ty) = body.yield_ty {
1230 // This only applies to generators
1234 assert!(body.generator_drop.is_none());
1236 let def_id = source.def_id();
1238 // The first argument is the generator type passed by value
1239 let gen_ty = body.local_decls.raw[1].ty;
1241 // Get the interior types and substs which typeck computed
1242 let (upvars, interior, discr_ty, movable) = match gen_ty.kind {
1243 ty::Generator(_, substs, movability) => {
1244 let substs = substs.as_generator();
1246 substs.upvar_tys().collect(),
1248 substs.discr_ty(tcx),
1249 movability == hir::Movability::Movable,
1254 .delay_span_bug(body.span, &format!("unexpected generator type {}", gen_ty));
1259 // Compute GeneratorState<yield_ty, return_ty>
1260 let state_did = tcx.require_lang_item(GeneratorStateLangItem, None);
1261 let state_adt_ref = tcx.adt_def(state_did);
1262 let state_substs = tcx.intern_substs(&[yield_ty.into(), body.return_ty().into()]);
1263 let ret_ty = tcx.mk_adt(state_adt_ref, state_substs);
1265 // We rename RETURN_PLACE which has type mir.return_ty to new_ret_local
1266 // RETURN_PLACE then is a fresh unused local with type ret_ty.
1267 let new_ret_local = replace_local(RETURN_PLACE, ret_ty, body, tcx);
1269 // We also replace the resume argument and insert an `Assign`.
1270 // This is needed because the resume argument `_2` might be live across a `yield`, in which
1271 // case there is no `Assign` to it that the transform can turn into a store to the generator
1272 // state. After the yield the slot in the generator state would then be uninitialized.
1273 let resume_local = Local::new(2);
1274 let new_resume_local =
1275 replace_local(resume_local, body.local_decls[resume_local].ty, body, tcx);
1277 // When first entering the generator, move the resume argument into its new local.
1278 let source_info = SourceInfo::outermost(body.span);
1279 let stmts = &mut body.basic_blocks_mut()[BasicBlock::new(0)].statements;
1284 kind: StatementKind::Assign(box (
1285 new_resume_local.into(),
1286 Rvalue::Use(Operand::Move(resume_local.into())),
1291 let always_live_locals = storage::AlwaysLiveLocals::new(&body);
1294 locals_live_across_suspend_points(tcx, body, source, &always_live_locals, movable);
1296 sanitize_witness(tcx, body, def_id, interior, &upvars, &liveness_info.saved_locals);
1298 if tcx.sess.opts.debugging_opts.validate_mir {
1299 let mut vis = EnsureGeneratorFieldAssignmentsNeverAlias {
1300 assigned_local: None,
1301 saved_locals: &liveness_info.saved_locals,
1302 storage_conflicts: &liveness_info.storage_conflicts,
1305 vis.visit_body(body);
1308 // Extract locals which are live across suspension point into `layout`
1309 // `remap` gives a mapping from local indices onto generator struct indices
1310 // `storage_liveness` tells us which locals have live storage at suspension points
1311 let (remap, layout, storage_liveness) = compute_layout(liveness_info, body);
1313 let can_return = can_return(tcx, body);
1315 // Run the transformation which converts Places from Local to generator struct
1316 // accesses for locals in `remap`.
1317 // It also rewrites `return x` and `yield y` as writing a new generator state and returning
1318 // GeneratorState::Complete(x) and GeneratorState::Yielded(y) respectively.
1319 let mut transform = TransformVisitor {
1326 suspension_points: Vec::new(),
1330 transform.visit_body(body);
1332 // Update our MIR struct to reflect the changes we've made
1333 body.yield_ty = None;
1334 body.arg_count = 2; // self, resume arg
1335 body.spread_arg = None;
1336 body.generator_layout = Some(layout);
1338 // Insert `drop(generator_struct)` which is used to drop upvars for generators in
1339 // the unresumed state.
1340 // This is expanded to a drop ladder in `elaborate_generator_drops`.
1341 let drop_clean = insert_clean_drop(body);
1343 dump_mir(tcx, None, "generator_pre-elab", &0, source, body, |_, _| Ok(()));
1345 // Expand `drop(generator_struct)` to a drop ladder which destroys upvars.
1346 // If any upvars are moved out of, drop elaboration will handle upvar destruction.
1347 // However we need to also elaborate the code generated by `insert_clean_drop`.
1348 elaborate_generator_drops(tcx, def_id, body);
1350 dump_mir(tcx, None, "generator_post-transform", &0, source, body, |_, _| Ok(()));
1352 // Create a copy of our MIR and use it to create the drop shim for the generator
1354 create_generator_drop_shim(tcx, &transform, source, gen_ty, body, drop_clean);
1356 body.generator_drop = Some(box drop_shim);
1358 // Create the Generator::resume function
1359 create_generator_resume_function(tcx, transform, source, body, can_return);
1363 /// Looks for any assignments between locals (e.g., `_4 = _5`) that will both be converted to fields
1364 /// in the generator state machine but whose storage is not marked as conflicting
1366 /// Validation needs to happen immediately *before* `TransformVisitor` is invoked, not after.
1368 /// This condition would arise when the assignment is the last use of `_5` but the initial
1369 /// definition of `_4` if we weren't extra careful to mark all locals used inside a statement as
1370 /// conflicting. Non-conflicting generator saved locals may be stored at the same location within
1371 /// the generator state machine, which would result in ill-formed MIR: the left-hand and right-hand
1372 /// sides of an assignment may not alias. This caused a miscompilation in [#73137].
1374 /// [#73137]: https://github.com/rust-lang/rust/issues/73137
1375 struct EnsureGeneratorFieldAssignmentsNeverAlias<'a> {
1376 saved_locals: &'a GeneratorSavedLocals,
1377 storage_conflicts: &'a BitMatrix<GeneratorSavedLocal, GeneratorSavedLocal>,
1378 assigned_local: Option<GeneratorSavedLocal>,
1381 impl EnsureGeneratorFieldAssignmentsNeverAlias<'_> {
1382 fn saved_local_for_direct_place(&self, place: Place<'_>) -> Option<GeneratorSavedLocal> {
1383 if place.is_indirect() {
1387 self.saved_locals.get(place.local)
1390 fn check_assigned_place(&mut self, place: Place<'tcx>, f: impl FnOnce(&mut Self)) {
1391 if let Some(assigned_local) = self.saved_local_for_direct_place(place) {
1392 assert!(self.assigned_local.is_none(), "`check_assigned_place` must not recurse");
1394 self.assigned_local = Some(assigned_local);
1396 self.assigned_local = None;
1401 impl Visitor<'tcx> for EnsureGeneratorFieldAssignmentsNeverAlias<'_> {
1402 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
1403 let lhs = match self.assigned_local {
1406 // This visitor only invokes `visit_place` for the right-hand side of an assignment
1407 // and only after setting `self.assigned_local`. However, the default impl of
1408 // `Visitor::super_body` may call `visit_place` with a `NonUseContext` for places
1409 // with debuginfo. Ignore them here.
1410 assert!(!context.is_use());
1415 let rhs = match self.saved_local_for_direct_place(*place) {
1420 if !self.storage_conflicts.contains(lhs, rhs) {
1422 "Assignment between generator saved locals whose storage is not \
1423 marked as conflicting: {:?}: {:?} = {:?}",
1431 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
1432 match &statement.kind {
1433 StatementKind::Assign(box (lhs, rhs)) => {
1434 self.check_assigned_place(*lhs, |this| this.visit_rvalue(rhs, location));
1437 // FIXME: Does `llvm_asm!` have any aliasing requirements?
1438 StatementKind::LlvmInlineAsm(_) => {}
1440 StatementKind::FakeRead(..)
1441 | StatementKind::SetDiscriminant { .. }
1442 | StatementKind::StorageLive(_)
1443 | StatementKind::StorageDead(_)
1444 | StatementKind::Retag(..)
1445 | StatementKind::AscribeUserType(..)
1446 | StatementKind::Coverage(..)
1447 | StatementKind::Nop => {}
1451 fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
1452 // Checking for aliasing in terminators is probably overkill, but until we have actual
1453 // semantics, we should be conservative here.
1454 match &terminator.kind {
1455 TerminatorKind::Call {
1458 destination: Some((dest, _)),
1463 self.check_assigned_place(*dest, |this| {
1464 this.visit_operand(func, location);
1466 this.visit_operand(arg, location);
1471 TerminatorKind::Yield { value, resume: _, resume_arg, drop: _ } => {
1472 self.check_assigned_place(*resume_arg, |this| this.visit_operand(value, location));
1475 // FIXME: Does `asm!` have any aliasing requirements?
1476 TerminatorKind::InlineAsm { .. } => {}
1478 TerminatorKind::Call { .. }
1479 | TerminatorKind::Goto { .. }
1480 | TerminatorKind::SwitchInt { .. }
1481 | TerminatorKind::Resume
1482 | TerminatorKind::Abort
1483 | TerminatorKind::Return
1484 | TerminatorKind::Unreachable
1485 | TerminatorKind::Drop { .. }
1486 | TerminatorKind::DropAndReplace { .. }
1487 | TerminatorKind::Assert { .. }
1488 | TerminatorKind::GeneratorDrop
1489 | TerminatorKind::FalseEdge { .. }
1490 | TerminatorKind::FalseUnwind { .. } => {}