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;
59 use crate::util::dump_mir;
60 use crate::util::expand_aggregate;
61 use crate::util::storage;
62 use rustc_data_structures::fx::FxHashMap;
64 use rustc_hir::lang_items::LangItem;
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::{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 variant assignment. `core::ops::GeneratorState` only has single
240 // element tuple variants, so we can just write to the downcasted first field and then set the
241 // discriminant to the appropriate variant.
246 source_info: SourceInfo,
247 ) -> impl Iterator<Item = Statement<'tcx>> {
248 let kind = AggregateKind::Adt(self.state_adt_ref, idx, self.state_substs, None, None);
249 assert_eq!(self.state_adt_ref.variants[idx].fields.len(), 1);
252 .type_of(self.state_adt_ref.variants[idx].fields[0].did)
253 .subst(self.tcx, self.state_substs);
255 Place::return_place(),
256 std::iter::once((val, ty)),
263 // Create a Place referencing a generator struct field
264 fn make_field(&self, variant_index: VariantIdx, idx: usize, ty: Ty<'tcx>) -> Place<'tcx> {
265 let self_place = Place::from(SELF_ARG);
266 let base = self.tcx.mk_place_downcast_unnamed(self_place, variant_index);
267 let mut projection = base.projection.to_vec();
268 projection.push(ProjectionElem::Field(Field::new(idx), ty));
270 Place { local: base.local, projection: self.tcx.intern_place_elems(&projection) }
273 // Create a statement which changes the discriminant
274 fn set_discr(&self, state_disc: VariantIdx, source_info: SourceInfo) -> Statement<'tcx> {
275 let self_place = Place::from(SELF_ARG);
278 kind: StatementKind::SetDiscriminant {
279 place: box self_place,
280 variant_index: state_disc,
285 // Create a statement which reads the discriminant into a temporary
286 fn get_discr(&self, body: &mut Body<'tcx>) -> (Statement<'tcx>, Place<'tcx>) {
287 let temp_decl = LocalDecl::new(self.discr_ty, body.span).internal();
288 let local_decls_len = body.local_decls.push(temp_decl);
289 let temp = Place::from(local_decls_len);
291 let self_place = Place::from(SELF_ARG);
292 let assign = Statement {
293 source_info: SourceInfo::outermost(body.span),
294 kind: StatementKind::Assign(box (temp, Rvalue::Discriminant(self_place))),
300 impl MutVisitor<'tcx> for TransformVisitor<'tcx> {
301 fn tcx(&self) -> TyCtxt<'tcx> {
305 fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
306 assert_eq!(self.remap.get(local), None);
311 place: &mut Place<'tcx>,
312 _context: PlaceContext,
315 // Replace an Local in the remap with a generator struct access
316 if let Some(&(ty, variant_index, idx)) = self.remap.get(&place.local) {
317 replace_base(place, self.make_field(variant_index, idx, ty), self.tcx);
321 fn visit_basic_block_data(&mut self, block: BasicBlock, data: &mut BasicBlockData<'tcx>) {
322 // Remove StorageLive and StorageDead statements for remapped locals
323 data.retain_statements(|s| match s.kind {
324 StatementKind::StorageLive(l) | StatementKind::StorageDead(l) => {
325 !self.remap.contains_key(&l)
330 let ret_val = match data.terminator().kind {
331 TerminatorKind::Return => Some((
334 Operand::Move(Place::from(self.new_ret_local)),
337 TerminatorKind::Yield { ref value, resume, resume_arg, drop } => {
338 Some((VariantIdx::new(0), Some((resume, resume_arg)), value.clone(), drop))
343 if let Some((state_idx, resume, v, drop)) = ret_val {
344 let source_info = data.terminator().source_info;
345 // We must assign the value first in case it gets declared dead below
346 data.statements.extend(self.make_state(state_idx, v, source_info));
347 let state = if let Some((resume, resume_arg)) = resume {
349 let state = 3 + self.suspension_points.len();
351 // The resume arg target location might itself be remapped if its base local is
352 // live across a yield.
354 if let Some(&(ty, variant, idx)) = self.remap.get(&resume_arg.local) {
355 self.make_field(variant, idx, ty)
360 self.suspension_points.push(SuspensionPoint {
365 storage_liveness: self.storage_liveness[block].clone().unwrap(),
368 VariantIdx::new(state)
371 VariantIdx::new(RETURNED) // state for returned
373 data.statements.push(self.set_discr(state, source_info));
374 data.terminator_mut().kind = TerminatorKind::Return;
377 self.super_basic_block_data(block, data);
381 fn make_generator_state_argument_indirect<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
382 let gen_ty = body.local_decls.raw[1].ty;
385 tcx.mk_ref(tcx.lifetimes.re_erased, ty::TypeAndMut { ty: gen_ty, mutbl: Mutability::Mut });
387 // Replace the by value generator argument
388 body.local_decls.raw[1].ty = ref_gen_ty;
390 // Add a deref to accesses of the generator state
391 DerefArgVisitor { tcx }.visit_body(body);
394 fn make_generator_state_argument_pinned<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
395 let ref_gen_ty = body.local_decls.raw[1].ty;
397 let pin_did = tcx.require_lang_item(LangItem::Pin, Some(body.span));
398 let pin_adt_ref = tcx.adt_def(pin_did);
399 let substs = tcx.intern_substs(&[ref_gen_ty.into()]);
400 let pin_ref_gen_ty = tcx.mk_adt(pin_adt_ref, substs);
402 // Replace the by ref generator argument
403 body.local_decls.raw[1].ty = pin_ref_gen_ty;
405 // Add the Pin field access to accesses of the generator state
406 PinArgVisitor { ref_gen_ty, tcx }.visit_body(body);
409 /// Allocates a new local and replaces all references of `local` with it. Returns the new local.
411 /// `local` will be changed to a new local decl with type `ty`.
413 /// Note that the new local will be uninitialized. It is the caller's responsibility to assign some
414 /// valid value to it before its first use.
415 fn replace_local<'tcx>(
418 body: &mut Body<'tcx>,
421 let new_decl = LocalDecl::new(ty, body.span);
422 let new_local = body.local_decls.push(new_decl);
423 body.local_decls.swap(local, new_local);
425 RenameLocalVisitor { from: local, to: new_local, tcx }.visit_body(body);
430 struct LivenessInfo {
431 /// Which locals are live across any suspension point.
432 saved_locals: GeneratorSavedLocals,
434 /// The set of saved locals live at each suspension point.
435 live_locals_at_suspension_points: Vec<BitSet<GeneratorSavedLocal>>,
437 /// Parallel vec to the above with SourceInfo for each yield terminator.
438 source_info_at_suspension_points: Vec<SourceInfo>,
440 /// For every saved local, the set of other saved locals that are
441 /// storage-live at the same time as this local. We cannot overlap locals in
442 /// the layout which have conflicting storage.
443 storage_conflicts: BitMatrix<GeneratorSavedLocal, GeneratorSavedLocal>,
445 /// For every suspending block, the locals which are storage-live across
446 /// that suspension point.
447 storage_liveness: IndexVec<BasicBlock, Option<BitSet<Local>>>,
450 fn locals_live_across_suspend_points(
453 always_live_locals: &storage::AlwaysLiveLocals,
456 let body_ref: &Body<'_> = &body;
458 // Calculate when MIR locals have live storage. This gives us an upper bound of their
460 let mut storage_live = MaybeStorageLive::new(always_live_locals.clone())
461 .into_engine(tcx, body_ref)
462 .iterate_to_fixpoint()
463 .into_results_cursor(body_ref);
465 // Calculate the MIR locals which have been previously
466 // borrowed (even if they are still active).
467 let borrowed_locals_results = MaybeBorrowedLocals::all_borrows()
468 .into_engine(tcx, body_ref)
469 .pass_name("generator")
470 .iterate_to_fixpoint();
472 let mut borrowed_locals_cursor =
473 dataflow::ResultsCursor::new(body_ref, &borrowed_locals_results);
475 // Calculate the MIR locals that we actually need to keep storage around
477 let requires_storage_results = MaybeRequiresStorage::new(body, &borrowed_locals_results)
478 .into_engine(tcx, body_ref)
479 .iterate_to_fixpoint();
480 let mut requires_storage_cursor =
481 dataflow::ResultsCursor::new(body_ref, &requires_storage_results);
483 // Calculate the liveness of MIR locals ignoring borrows.
484 let mut liveness = MaybeLiveLocals
485 .into_engine(tcx, body_ref)
486 .pass_name("generator")
487 .iterate_to_fixpoint()
488 .into_results_cursor(body_ref);
490 let mut storage_liveness_map = IndexVec::from_elem(None, body.basic_blocks());
491 let mut live_locals_at_suspension_points = Vec::new();
492 let mut source_info_at_suspension_points = Vec::new();
493 let mut live_locals_at_any_suspension_point = BitSet::new_empty(body.local_decls.len());
495 for (block, data) in body.basic_blocks().iter_enumerated() {
496 if let TerminatorKind::Yield { .. } = data.terminator().kind {
497 let loc = Location { block, statement_index: data.statements.len() };
499 liveness.seek_to_block_end(block);
500 let mut live_locals = liveness.get().clone();
503 // The `liveness` variable contains the liveness of MIR locals ignoring borrows.
504 // This is correct for movable generators since borrows cannot live across
505 // suspension points. However for immovable generators we need to account for
506 // borrows, so we conseratively assume that all borrowed locals are live until
507 // we find a StorageDead statement referencing the locals.
508 // To do this we just union our `liveness` result with `borrowed_locals`, which
509 // contains all the locals which has been borrowed before this suspension point.
510 // If a borrow is converted to a raw reference, we must also assume that it lives
511 // forever. Note that the final liveness is still bounded by the storage liveness
512 // of the local, which happens using the `intersect` operation below.
513 borrowed_locals_cursor.seek_before_primary_effect(loc);
514 live_locals.union(borrowed_locals_cursor.get());
517 // Store the storage liveness for later use so we can restore the state
518 // after a suspension point
519 storage_live.seek_before_primary_effect(loc);
520 storage_liveness_map[block] = Some(storage_live.get().clone());
522 // Locals live are live at this point only if they are used across
523 // suspension points (the `liveness` variable)
524 // and their storage is required (the `storage_required` variable)
525 requires_storage_cursor.seek_before_primary_effect(loc);
526 live_locals.intersect(requires_storage_cursor.get());
528 // The generator argument is ignored.
529 live_locals.remove(SELF_ARG);
531 debug!("loc = {:?}, live_locals = {:?}", loc, live_locals);
533 // Add the locals live at this suspension point to the set of locals which live across
534 // any suspension points
535 live_locals_at_any_suspension_point.union(&live_locals);
537 live_locals_at_suspension_points.push(live_locals);
538 source_info_at_suspension_points.push(data.terminator().source_info);
542 debug!("live_locals_anywhere = {:?}", live_locals_at_any_suspension_point);
543 let saved_locals = GeneratorSavedLocals(live_locals_at_any_suspension_point);
545 // Renumber our liveness_map bitsets to include only the locals we are
547 let live_locals_at_suspension_points = live_locals_at_suspension_points
549 .map(|live_here| saved_locals.renumber_bitset(&live_here))
552 let storage_conflicts = compute_storage_conflicts(
555 always_live_locals.clone(),
556 requires_storage_results,
561 live_locals_at_suspension_points,
562 source_info_at_suspension_points,
564 storage_liveness: storage_liveness_map,
568 /// The set of `Local`s that must be saved across yield points.
570 /// `GeneratorSavedLocal` is indexed in terms of the elements in this set;
571 /// i.e. `GeneratorSavedLocal::new(1)` corresponds to the second local
572 /// included in this set.
573 struct GeneratorSavedLocals(BitSet<Local>);
575 impl GeneratorSavedLocals {
576 /// Returns an iterator over each `GeneratorSavedLocal` along with the `Local` it corresponds
578 fn iter_enumerated(&self) -> impl '_ + Iterator<Item = (GeneratorSavedLocal, Local)> {
579 self.iter().enumerate().map(|(i, l)| (GeneratorSavedLocal::from(i), l))
582 /// Transforms a `BitSet<Local>` that contains only locals saved across yield points to the
583 /// equivalent `BitSet<GeneratorSavedLocal>`.
584 fn renumber_bitset(&self, input: &BitSet<Local>) -> BitSet<GeneratorSavedLocal> {
585 assert!(self.superset(&input), "{:?} not a superset of {:?}", self.0, input);
586 let mut out = BitSet::new_empty(self.count());
587 for (saved_local, local) in self.iter_enumerated() {
588 if input.contains(local) {
589 out.insert(saved_local);
595 fn get(&self, local: Local) -> Option<GeneratorSavedLocal> {
596 if !self.contains(local) {
600 let idx = self.iter().take_while(|&l| l < local).count();
601 Some(GeneratorSavedLocal::new(idx))
605 impl ops::Deref for GeneratorSavedLocals {
606 type Target = BitSet<Local>;
608 fn deref(&self) -> &Self::Target {
613 /// For every saved local, looks for which locals are StorageLive at the same
614 /// time. Generates a bitset for every local of all the other locals that may be
615 /// StorageLive simultaneously with that local. This is used in the layout
616 /// computation; see `GeneratorLayout` for more.
617 fn compute_storage_conflicts(
618 body: &'mir Body<'tcx>,
619 saved_locals: &GeneratorSavedLocals,
620 always_live_locals: storage::AlwaysLiveLocals,
621 requires_storage: dataflow::Results<'tcx, MaybeRequiresStorage<'mir, 'tcx>>,
622 ) -> BitMatrix<GeneratorSavedLocal, GeneratorSavedLocal> {
623 assert_eq!(body.local_decls.len(), saved_locals.domain_size());
625 debug!("compute_storage_conflicts({:?})", body.span);
626 debug!("always_live = {:?}", always_live_locals);
628 // Locals that are always live or ones that need to be stored across
629 // suspension points are not eligible for overlap.
630 let mut ineligible_locals = always_live_locals.into_inner();
631 ineligible_locals.intersect(saved_locals);
633 // Compute the storage conflicts for all eligible locals.
634 let mut visitor = StorageConflictVisitor {
636 saved_locals: &saved_locals,
637 local_conflicts: BitMatrix::from_row_n(&ineligible_locals, body.local_decls.len()),
640 requires_storage.visit_reachable_with(body, &mut visitor);
642 let local_conflicts = visitor.local_conflicts;
644 // Compress the matrix using only stored locals (Local -> GeneratorSavedLocal).
646 // NOTE: Today we store a full conflict bitset for every local. Technically
647 // this is twice as many bits as we need, since the relation is symmetric.
648 // However, in practice these bitsets are not usually large. The layout code
649 // also needs to keep track of how many conflicts each local has, so it's
650 // simpler to keep it this way for now.
651 let mut storage_conflicts = BitMatrix::new(saved_locals.count(), saved_locals.count());
652 for (saved_local_a, local_a) in saved_locals.iter_enumerated() {
653 if ineligible_locals.contains(local_a) {
654 // Conflicts with everything.
655 storage_conflicts.insert_all_into_row(saved_local_a);
657 // Keep overlap information only for stored locals.
658 for (saved_local_b, local_b) in saved_locals.iter_enumerated() {
659 if local_conflicts.contains(local_a, local_b) {
660 storage_conflicts.insert(saved_local_a, saved_local_b);
668 struct StorageConflictVisitor<'mir, 'tcx, 's> {
669 body: &'mir Body<'tcx>,
670 saved_locals: &'s GeneratorSavedLocals,
671 // FIXME(tmandry): Consider using sparse bitsets here once we have good
672 // benchmarks for generators.
673 local_conflicts: BitMatrix<Local, Local>,
676 impl dataflow::ResultsVisitor<'mir, 'tcx> for StorageConflictVisitor<'mir, 'tcx, '_> {
677 type FlowState = BitSet<Local>;
679 fn visit_statement_before_primary_effect(
681 state: &Self::FlowState,
682 _statement: &'mir Statement<'tcx>,
685 self.apply_state(state, loc);
688 fn visit_terminator_before_primary_effect(
690 state: &Self::FlowState,
691 _terminator: &'mir Terminator<'tcx>,
694 self.apply_state(state, loc);
698 impl<'body, 'tcx, 's> StorageConflictVisitor<'body, 'tcx, 's> {
699 fn apply_state(&mut self, flow_state: &BitSet<Local>, loc: Location) {
700 // Ignore unreachable blocks.
701 if self.body.basic_blocks()[loc.block].terminator().kind == TerminatorKind::Unreachable {
705 let mut eligible_storage_live = flow_state.clone();
706 eligible_storage_live.intersect(&self.saved_locals);
708 for local in eligible_storage_live.iter() {
709 self.local_conflicts.union_row_with(&eligible_storage_live, local);
712 if eligible_storage_live.count() > 1 {
713 trace!("at {:?}, eligible_storage_live={:?}", loc, eligible_storage_live);
718 /// Validates the typeck view of the generator against the actual set of types saved between
720 fn sanitize_witness<'tcx>(
724 upvars: &Vec<Ty<'tcx>>,
725 saved_locals: &GeneratorSavedLocals,
727 let did = body.source.def_id();
728 let allowed_upvars = tcx.erase_regions(upvars);
729 let allowed = match witness.kind() {
730 ty::GeneratorWitness(s) => tcx.erase_late_bound_regions(&s),
732 tcx.sess.delay_span_bug(
734 &format!("unexpected generator witness type {:?}", witness.kind()),
740 let param_env = tcx.param_env(did);
742 for (local, decl) in body.local_decls.iter_enumerated() {
743 // Ignore locals which are internal or not saved between yields.
744 if !saved_locals.contains(local) || decl.internal {
747 let decl_ty = tcx.normalize_erasing_regions(param_env, decl.ty);
749 // Sanity check that typeck knows about the type of locals which are
750 // live across a suspension point
751 if !allowed.contains(&decl_ty) && !allowed_upvars.contains(&decl_ty) {
754 "Broken MIR: generator contains type {} in MIR, \
755 but typeck only knows about {}",
763 fn compute_layout<'tcx>(
764 liveness: LivenessInfo,
765 body: &mut Body<'tcx>,
767 FxHashMap<Local, (Ty<'tcx>, VariantIdx, usize)>,
768 GeneratorLayout<'tcx>,
769 IndexVec<BasicBlock, Option<BitSet<Local>>>,
773 live_locals_at_suspension_points,
774 source_info_at_suspension_points,
779 // Gather live local types and their indices.
780 let mut locals = IndexVec::<GeneratorSavedLocal, _>::new();
781 let mut tys = IndexVec::<GeneratorSavedLocal, _>::new();
782 for (saved_local, local) in saved_locals.iter_enumerated() {
784 tys.push(body.local_decls[local].ty);
785 debug!("generator saved local {:?} => {:?}", saved_local, local);
788 // Leave empty variants for the UNRESUMED, RETURNED, and POISONED states.
789 // In debuginfo, these will correspond to the beginning (UNRESUMED) or end
790 // (RETURNED, POISONED) of the function.
791 const RESERVED_VARIANTS: usize = 3;
792 let body_span = body.source_scopes[OUTERMOST_SOURCE_SCOPE].span;
793 let mut variant_source_info: IndexVec<VariantIdx, SourceInfo> = [
794 SourceInfo::outermost(body_span.shrink_to_lo()),
795 SourceInfo::outermost(body_span.shrink_to_hi()),
796 SourceInfo::outermost(body_span.shrink_to_hi()),
802 // Build the generator variant field list.
803 // Create a map from local indices to generator struct indices.
804 let mut variant_fields: IndexVec<VariantIdx, IndexVec<Field, GeneratorSavedLocal>> =
805 iter::repeat(IndexVec::new()).take(RESERVED_VARIANTS).collect();
806 let mut remap = FxHashMap::default();
807 for (suspension_point_idx, live_locals) in live_locals_at_suspension_points.iter().enumerate() {
808 let variant_index = VariantIdx::from(RESERVED_VARIANTS + suspension_point_idx);
809 let mut fields = IndexVec::new();
810 for (idx, saved_local) in live_locals.iter().enumerate() {
811 fields.push(saved_local);
812 // Note that if a field is included in multiple variants, we will
813 // just use the first one here. That's fine; fields do not move
814 // around inside generators, so it doesn't matter which variant
815 // index we access them by.
816 remap.entry(locals[saved_local]).or_insert((tys[saved_local], variant_index, idx));
818 variant_fields.push(fields);
819 variant_source_info.push(source_info_at_suspension_points[suspension_point_idx]);
821 debug!("generator variant_fields = {:?}", variant_fields);
822 debug!("generator storage_conflicts = {:#?}", storage_conflicts);
825 GeneratorLayout { field_tys: tys, variant_fields, variant_source_info, storage_conflicts };
827 (remap, layout, storage_liveness)
830 /// Replaces the entry point of `body` with a block that switches on the generator discriminant and
831 /// dispatches to blocks according to `cases`.
833 /// After this function, the former entry point of the function will be bb1.
834 fn insert_switch<'tcx>(
835 body: &mut Body<'tcx>,
836 cases: Vec<(usize, BasicBlock)>,
837 transform: &TransformVisitor<'tcx>,
838 default: TerminatorKind<'tcx>,
840 let default_block = insert_term_block(body, default);
841 let (assign, discr) = transform.get_discr(body);
842 let switch = TerminatorKind::SwitchInt {
843 discr: Operand::Move(discr),
844 switch_ty: transform.discr_ty,
845 values: Cow::from(cases.iter().map(|&(i, _)| i as u128).collect::<Vec<_>>()),
846 targets: cases.iter().map(|&(_, d)| d).chain(iter::once(default_block)).collect(),
849 let source_info = SourceInfo::outermost(body.span);
850 body.basic_blocks_mut().raw.insert(
853 statements: vec![assign],
854 terminator: Some(Terminator { source_info, kind: switch }),
859 let blocks = body.basic_blocks_mut().iter_mut();
861 for target in blocks.flat_map(|b| b.terminator_mut().successors_mut()) {
862 *target = BasicBlock::new(target.index() + 1);
866 fn elaborate_generator_drops<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
867 use crate::shim::DropShimElaborator;
868 use crate::util::elaborate_drops::{elaborate_drop, Unwind};
869 use crate::util::patch::MirPatch;
871 // Note that `elaborate_drops` only drops the upvars of a generator, and
872 // this is ok because `open_drop` can only be reached within that own
873 // generator's resume function.
875 let def_id = body.source.def_id();
876 let param_env = tcx.param_env(def_id);
878 let mut elaborator = DropShimElaborator { body, patch: MirPatch::new(body), tcx, param_env };
880 for (block, block_data) in body.basic_blocks().iter_enumerated() {
881 let (target, unwind, source_info) = match block_data.terminator() {
882 Terminator { source_info, kind: TerminatorKind::Drop { place, target, unwind } } => {
883 if let Some(local) = place.as_local() {
884 if local == SELF_ARG {
885 (target, unwind, source_info)
895 let unwind = if block_data.is_cleanup {
898 Unwind::To(unwind.unwrap_or_else(|| elaborator.patch.resume_block()))
903 Place::from(SELF_ARG),
910 elaborator.patch.apply(body);
913 fn create_generator_drop_shim<'tcx>(
915 transform: &TransformVisitor<'tcx>,
917 body: &mut Body<'tcx>,
918 drop_clean: BasicBlock,
920 let mut body = body.clone();
921 body.arg_count = 1; // make sure the resume argument is not included here
923 let source_info = SourceInfo::outermost(body.span);
925 let mut cases = create_cases(&mut body, transform, Operation::Drop);
927 cases.insert(0, (UNRESUMED, drop_clean));
929 // The returned state and the poisoned state fall through to the default
930 // case which is just to return
932 insert_switch(&mut body, cases, &transform, TerminatorKind::Return);
934 for block in body.basic_blocks_mut() {
935 let kind = &mut block.terminator_mut().kind;
936 if let TerminatorKind::GeneratorDrop = *kind {
937 *kind = TerminatorKind::Return;
941 // Replace the return variable
942 body.local_decls[RETURN_PLACE] = LocalDecl::with_source_info(tcx.mk_unit(), source_info);
944 make_generator_state_argument_indirect(tcx, &mut body);
946 // Change the generator argument from &mut to *mut
947 body.local_decls[SELF_ARG] = LocalDecl::with_source_info(
948 tcx.mk_ptr(ty::TypeAndMut { ty: gen_ty, mutbl: hir::Mutability::Mut }),
951 if tcx.sess.opts.debugging_opts.mir_emit_retag {
952 // Alias tracking must know we changed the type
953 body.basic_blocks_mut()[START_BLOCK].statements.insert(
957 kind: StatementKind::Retag(RetagKind::Raw, box Place::from(SELF_ARG)),
962 no_landing_pads(tcx, &mut body);
964 // Make sure we remove dead blocks to remove
965 // unrelated code from the resume part of the function
966 simplify::remove_dead_blocks(&mut body);
968 dump_mir(tcx, None, "generator_drop", &0, &body, |_, _| Ok(()));
973 fn insert_term_block<'tcx>(body: &mut Body<'tcx>, kind: TerminatorKind<'tcx>) -> BasicBlock {
974 let source_info = SourceInfo::outermost(body.span);
975 body.basic_blocks_mut().push(BasicBlockData {
976 statements: Vec::new(),
977 terminator: Some(Terminator { source_info, kind }),
982 fn insert_panic_block<'tcx>(
984 body: &mut Body<'tcx>,
985 message: AssertMessage<'tcx>,
987 let assert_block = BasicBlock::new(body.basic_blocks().len());
988 let term = TerminatorKind::Assert {
989 cond: Operand::Constant(box Constant {
992 literal: ty::Const::from_bool(tcx, false),
996 target: assert_block,
1000 let source_info = SourceInfo::outermost(body.span);
1001 body.basic_blocks_mut().push(BasicBlockData {
1002 statements: Vec::new(),
1003 terminator: Some(Terminator { source_info, kind: term }),
1010 fn can_return<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>) -> bool {
1011 // Returning from a function with an uninhabited return type is undefined behavior.
1012 if body.return_ty().conservative_is_privately_uninhabited(tcx) {
1016 // If there's a return terminator the function may return.
1017 for block in body.basic_blocks() {
1018 if let TerminatorKind::Return = block.terminator().kind {
1023 // Otherwise the function can't return.
1027 fn can_unwind<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>) -> bool {
1028 // Nothing can unwind when landing pads are off.
1029 if tcx.sess.panic_strategy() == PanicStrategy::Abort {
1033 // Unwinds can only start at certain terminators.
1034 for block in body.basic_blocks() {
1035 match block.terminator().kind {
1036 // These never unwind.
1037 TerminatorKind::Goto { .. }
1038 | TerminatorKind::SwitchInt { .. }
1039 | TerminatorKind::Abort
1040 | TerminatorKind::Return
1041 | TerminatorKind::Unreachable
1042 | TerminatorKind::GeneratorDrop
1043 | TerminatorKind::FalseEdge { .. }
1044 | TerminatorKind::FalseUnwind { .. }
1045 | TerminatorKind::InlineAsm { .. } => {}
1047 // Resume will *continue* unwinding, but if there's no other unwinding terminator it
1048 // will never be reached.
1049 TerminatorKind::Resume => {}
1051 TerminatorKind::Yield { .. } => {
1052 unreachable!("`can_unwind` called before generator transform")
1055 // These may unwind.
1056 TerminatorKind::Drop { .. }
1057 | TerminatorKind::DropAndReplace { .. }
1058 | TerminatorKind::Call { .. }
1059 | TerminatorKind::Assert { .. } => return true,
1063 // If we didn't find an unwinding terminator, the function cannot unwind.
1067 fn create_generator_resume_function<'tcx>(
1069 transform: TransformVisitor<'tcx>,
1070 body: &mut Body<'tcx>,
1073 let can_unwind = can_unwind(tcx, body);
1075 // Poison the generator when it unwinds
1077 let source_info = SourceInfo::outermost(body.span);
1078 let poison_block = body.basic_blocks_mut().push(BasicBlockData {
1079 statements: vec![transform.set_discr(VariantIdx::new(POISONED), source_info)],
1080 terminator: Some(Terminator { source_info, kind: TerminatorKind::Resume }),
1084 for (idx, block) in body.basic_blocks_mut().iter_enumerated_mut() {
1085 let source_info = block.terminator().source_info;
1087 if let TerminatorKind::Resume = block.terminator().kind {
1088 // An existing `Resume` terminator is redirected to jump to our dedicated
1089 // "poisoning block" above.
1090 if idx != poison_block {
1091 *block.terminator_mut() = Terminator {
1093 kind: TerminatorKind::Goto { target: poison_block },
1096 } else if !block.is_cleanup {
1097 // Any terminators that *can* unwind but don't have an unwind target set are also
1098 // pointed at our poisoning block (unless they're part of the cleanup path).
1099 if let Some(unwind @ None) = block.terminator_mut().unwind_mut() {
1100 *unwind = Some(poison_block);
1106 let mut cases = create_cases(body, &transform, Operation::Resume);
1108 use rustc_middle::mir::AssertKind::{ResumedAfterPanic, ResumedAfterReturn};
1110 // Jump to the entry point on the unresumed
1111 cases.insert(0, (UNRESUMED, BasicBlock::new(0)));
1113 // Panic when resumed on the returned or poisoned state
1114 let generator_kind = body.generator_kind.unwrap();
1119 (POISONED, insert_panic_block(tcx, body, ResumedAfterPanic(generator_kind))),
1126 (RETURNED, insert_panic_block(tcx, body, ResumedAfterReturn(generator_kind))),
1130 insert_switch(body, cases, &transform, TerminatorKind::Unreachable);
1132 make_generator_state_argument_indirect(tcx, body);
1133 make_generator_state_argument_pinned(tcx, body);
1135 no_landing_pads(tcx, body);
1137 // Make sure we remove dead blocks to remove
1138 // unrelated code from the drop part of the function
1139 simplify::remove_dead_blocks(body);
1141 dump_mir(tcx, None, "generator_resume", &0, body, |_, _| Ok(()));
1144 fn insert_clean_drop(body: &mut Body<'_>) -> BasicBlock {
1145 let return_block = insert_term_block(body, TerminatorKind::Return);
1148 TerminatorKind::Drop { place: Place::from(SELF_ARG), target: return_block, unwind: None };
1149 let source_info = SourceInfo::outermost(body.span);
1151 // Create a block to destroy an unresumed generators. This can only destroy upvars.
1152 body.basic_blocks_mut().push(BasicBlockData {
1153 statements: Vec::new(),
1154 terminator: Some(Terminator { source_info, kind: term }),
1159 /// An operation that can be performed on a generator.
1160 #[derive(PartialEq, Copy, Clone)]
1167 fn target_block(self, point: &SuspensionPoint<'_>) -> Option<BasicBlock> {
1169 Operation::Resume => Some(point.resume),
1170 Operation::Drop => point.drop,
1175 fn create_cases<'tcx>(
1176 body: &mut Body<'tcx>,
1177 transform: &TransformVisitor<'tcx>,
1178 operation: Operation,
1179 ) -> Vec<(usize, BasicBlock)> {
1180 let source_info = SourceInfo::outermost(body.span);
1185 .filter_map(|point| {
1186 // Find the target for this suspension point, if applicable
1187 operation.target_block(point).map(|target| {
1188 let mut statements = Vec::new();
1190 // Create StorageLive instructions for locals with live storage
1191 for i in 0..(body.local_decls.len()) {
1193 // The resume argument is live on function entry. Don't insert a
1194 // `StorageLive`, or the following `Assign` will read from uninitialized
1199 let l = Local::new(i);
1200 let needs_storage_live = point.storage_liveness.contains(l)
1201 && !transform.remap.contains_key(&l)
1202 && !transform.always_live_locals.contains(l);
1203 if needs_storage_live {
1205 .push(Statement { source_info, kind: StatementKind::StorageLive(l) });
1209 if operation == Operation::Resume {
1210 // Move the resume argument to the destination place of the `Yield` terminator
1211 let resume_arg = Local::new(2); // 0 = return, 1 = self
1212 statements.push(Statement {
1214 kind: StatementKind::Assign(box (
1216 Rvalue::Use(Operand::Move(resume_arg.into())),
1221 // Then jump to the real target
1222 let block = body.basic_blocks_mut().push(BasicBlockData {
1224 terminator: Some(Terminator {
1226 kind: TerminatorKind::Goto { target },
1231 (point.state, block)
1237 impl<'tcx> MirPass<'tcx> for StateTransform {
1238 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
1239 let yield_ty = if let Some(yield_ty) = body.yield_ty {
1242 // This only applies to generators
1246 assert!(body.generator_drop.is_none());
1248 // The first argument is the generator type passed by value
1249 let gen_ty = body.local_decls.raw[1].ty;
1251 // Get the interior types and substs which typeck computed
1252 let (upvars, interior, discr_ty, movable) = match *gen_ty.kind() {
1253 ty::Generator(_, substs, movability) => {
1254 let substs = substs.as_generator();
1256 substs.upvar_tys().collect(),
1258 substs.discr_ty(tcx),
1259 movability == hir::Movability::Movable,
1264 .delay_span_bug(body.span, &format!("unexpected generator type {}", gen_ty));
1269 // Compute GeneratorState<yield_ty, return_ty>
1270 let state_did = tcx.require_lang_item(LangItem::GeneratorState, None);
1271 let state_adt_ref = tcx.adt_def(state_did);
1272 let state_substs = tcx.intern_substs(&[yield_ty.into(), body.return_ty().into()]);
1273 let ret_ty = tcx.mk_adt(state_adt_ref, state_substs);
1275 // We rename RETURN_PLACE which has type mir.return_ty to new_ret_local
1276 // RETURN_PLACE then is a fresh unused local with type ret_ty.
1277 let new_ret_local = replace_local(RETURN_PLACE, ret_ty, body, tcx);
1279 // We also replace the resume argument and insert an `Assign`.
1280 // This is needed because the resume argument `_2` might be live across a `yield`, in which
1281 // case there is no `Assign` to it that the transform can turn into a store to the generator
1282 // state. After the yield the slot in the generator state would then be uninitialized.
1283 let resume_local = Local::new(2);
1284 let new_resume_local =
1285 replace_local(resume_local, body.local_decls[resume_local].ty, body, tcx);
1287 // When first entering the generator, move the resume argument into its new local.
1288 let source_info = SourceInfo::outermost(body.span);
1289 let stmts = &mut body.basic_blocks_mut()[BasicBlock::new(0)].statements;
1294 kind: StatementKind::Assign(box (
1295 new_resume_local.into(),
1296 Rvalue::Use(Operand::Move(resume_local.into())),
1301 let always_live_locals = storage::AlwaysLiveLocals::new(&body);
1304 locals_live_across_suspend_points(tcx, body, &always_live_locals, movable);
1306 sanitize_witness(tcx, body, interior, &upvars, &liveness_info.saved_locals);
1308 if tcx.sess.opts.debugging_opts.validate_mir {
1309 let mut vis = EnsureGeneratorFieldAssignmentsNeverAlias {
1310 assigned_local: None,
1311 saved_locals: &liveness_info.saved_locals,
1312 storage_conflicts: &liveness_info.storage_conflicts,
1315 vis.visit_body(body);
1318 // Extract locals which are live across suspension point into `layout`
1319 // `remap` gives a mapping from local indices onto generator struct indices
1320 // `storage_liveness` tells us which locals have live storage at suspension points
1321 let (remap, layout, storage_liveness) = compute_layout(liveness_info, body);
1323 let can_return = can_return(tcx, body);
1325 // Run the transformation which converts Places from Local to generator struct
1326 // accesses for locals in `remap`.
1327 // It also rewrites `return x` and `yield y` as writing a new generator state and returning
1328 // GeneratorState::Complete(x) and GeneratorState::Yielded(y) respectively.
1329 let mut transform = TransformVisitor {
1336 suspension_points: Vec::new(),
1340 transform.visit_body(body);
1342 // Update our MIR struct to reflect the changes we've made
1343 body.yield_ty = None;
1344 body.arg_count = 2; // self, resume arg
1345 body.spread_arg = None;
1346 body.generator_layout = Some(layout);
1348 // Insert `drop(generator_struct)` which is used to drop upvars for generators in
1349 // the unresumed state.
1350 // This is expanded to a drop ladder in `elaborate_generator_drops`.
1351 let drop_clean = insert_clean_drop(body);
1353 dump_mir(tcx, None, "generator_pre-elab", &0, body, |_, _| Ok(()));
1355 // Expand `drop(generator_struct)` to a drop ladder which destroys upvars.
1356 // If any upvars are moved out of, drop elaboration will handle upvar destruction.
1357 // However we need to also elaborate the code generated by `insert_clean_drop`.
1358 elaborate_generator_drops(tcx, body);
1360 dump_mir(tcx, None, "generator_post-transform", &0, body, |_, _| Ok(()));
1362 // Create a copy of our MIR and use it to create the drop shim for the generator
1363 let drop_shim = create_generator_drop_shim(tcx, &transform, gen_ty, body, drop_clean);
1365 body.generator_drop = Some(box drop_shim);
1367 // Create the Generator::resume function
1368 create_generator_resume_function(tcx, transform, body, can_return);
1372 /// Looks for any assignments between locals (e.g., `_4 = _5`) that will both be converted to fields
1373 /// in the generator state machine but whose storage is not marked as conflicting
1375 /// Validation needs to happen immediately *before* `TransformVisitor` is invoked, not after.
1377 /// This condition would arise when the assignment is the last use of `_5` but the initial
1378 /// definition of `_4` if we weren't extra careful to mark all locals used inside a statement as
1379 /// conflicting. Non-conflicting generator saved locals may be stored at the same location within
1380 /// the generator state machine, which would result in ill-formed MIR: the left-hand and right-hand
1381 /// sides of an assignment may not alias. This caused a miscompilation in [#73137].
1383 /// [#73137]: https://github.com/rust-lang/rust/issues/73137
1384 struct EnsureGeneratorFieldAssignmentsNeverAlias<'a> {
1385 saved_locals: &'a GeneratorSavedLocals,
1386 storage_conflicts: &'a BitMatrix<GeneratorSavedLocal, GeneratorSavedLocal>,
1387 assigned_local: Option<GeneratorSavedLocal>,
1390 impl EnsureGeneratorFieldAssignmentsNeverAlias<'_> {
1391 fn saved_local_for_direct_place(&self, place: Place<'_>) -> Option<GeneratorSavedLocal> {
1392 if place.is_indirect() {
1396 self.saved_locals.get(place.local)
1399 fn check_assigned_place(&mut self, place: Place<'tcx>, f: impl FnOnce(&mut Self)) {
1400 if let Some(assigned_local) = self.saved_local_for_direct_place(place) {
1401 assert!(self.assigned_local.is_none(), "`check_assigned_place` must not recurse");
1403 self.assigned_local = Some(assigned_local);
1405 self.assigned_local = None;
1410 impl Visitor<'tcx> for EnsureGeneratorFieldAssignmentsNeverAlias<'_> {
1411 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
1412 let lhs = match self.assigned_local {
1415 // This visitor only invokes `visit_place` for the right-hand side of an assignment
1416 // and only after setting `self.assigned_local`. However, the default impl of
1417 // `Visitor::super_body` may call `visit_place` with a `NonUseContext` for places
1418 // with debuginfo. Ignore them here.
1419 assert!(!context.is_use());
1424 let rhs = match self.saved_local_for_direct_place(*place) {
1429 if !self.storage_conflicts.contains(lhs, rhs) {
1431 "Assignment between generator saved locals whose storage is not \
1432 marked as conflicting: {:?}: {:?} = {:?}",
1440 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
1441 match &statement.kind {
1442 StatementKind::Assign(box (lhs, rhs)) => {
1443 self.check_assigned_place(*lhs, |this| this.visit_rvalue(rhs, location));
1446 // FIXME: Does `llvm_asm!` have any aliasing requirements?
1447 StatementKind::LlvmInlineAsm(_) => {}
1449 StatementKind::FakeRead(..)
1450 | StatementKind::SetDiscriminant { .. }
1451 | StatementKind::StorageLive(_)
1452 | StatementKind::StorageDead(_)
1453 | StatementKind::Retag(..)
1454 | StatementKind::AscribeUserType(..)
1455 | StatementKind::Coverage(..)
1456 | StatementKind::Nop => {}
1460 fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
1461 // Checking for aliasing in terminators is probably overkill, but until we have actual
1462 // semantics, we should be conservative here.
1463 match &terminator.kind {
1464 TerminatorKind::Call {
1467 destination: Some((dest, _)),
1472 self.check_assigned_place(*dest, |this| {
1473 this.visit_operand(func, location);
1475 this.visit_operand(arg, location);
1480 TerminatorKind::Yield { value, resume: _, resume_arg, drop: _ } => {
1481 self.check_assigned_place(*resume_arg, |this| this.visit_operand(value, location));
1484 // FIXME: Does `asm!` have any aliasing requirements?
1485 TerminatorKind::InlineAsm { .. } => {}
1487 TerminatorKind::Call { .. }
1488 | TerminatorKind::Goto { .. }
1489 | TerminatorKind::SwitchInt { .. }
1490 | TerminatorKind::Resume
1491 | TerminatorKind::Abort
1492 | TerminatorKind::Return
1493 | TerminatorKind::Unreachable
1494 | TerminatorKind::Drop { .. }
1495 | TerminatorKind::DropAndReplace { .. }
1496 | TerminatorKind::Assert { .. }
1497 | TerminatorKind::GeneratorDrop
1498 | TerminatorKind::FalseEdge { .. }
1499 | TerminatorKind::FalseUnwind { .. } => {}