Skip to main content

rustc_mir_transform/coroutine/
mod.rs

1//! This is the implementation of the pass which transforms coroutines into state machines.
2//!
3//! MIR generation for coroutines creates a function which has a self argument which
4//! passes by value. This argument is effectively a coroutine type which only contains upvars and
5//! is only used for this argument inside the MIR for the coroutine.
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 coroutine argument (which only consists of upvars) if any of the upvars
9//! are moved out of. This pass elaborates the drops of upvars / coroutine 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//! coroutine in the MIR, since it is used to create the drop glue for the coroutine. We'd get
12//! infinite recursion otherwise.
13//!
14//! This pass creates the implementation for either the `Coroutine::resume` or `Future::poll`
15//! function and the drop shim for the coroutine based on the MIR input.
16//! It converts the coroutine argument from Self to &mut Self adding derefs in the MIR as needed.
17//! It computes the final layout of the coroutine struct which looks like this:
18//!     First upvars are stored
19//!     It is followed by the coroutine state field.
20//!     Then finally the MIR locals which are live across a suspension point are stored.
21//!     ```ignore (illustrative)
22//!     struct Coroutine {
23//!         upvars...,
24//!         state: u32,
25//!         mir_locals...,
26//!     }
27//!     ```
28//! This pass computes the meaning of the state field and the MIR locals which are live
29//! across a suspension point. There are however three hardcoded coroutine states:
30//!     0 - Coroutine have not been resumed yet
31//!     1 - Coroutine has returned / is completed
32//!     2 - Coroutine has been poisoned
33//!
34//! It also rewrites `return x` and `yield y` as setting a new coroutine state and returning
35//! `CoroutineState::Complete(x)` and `CoroutineState::Yielded(y)`,
36//! or `Poll::Ready(x)` and `Poll::Pending` respectively.
37//! MIR locals which are live across a suspension point are moved to the coroutine struct
38//! with references to them being updated with references to the coroutine struct.
39//!
40//! The pass creates two functions which have a switch on the coroutine state giving
41//! the action to take.
42//!
43//! One of them is the implementation of `Coroutine::resume` / `Future::poll`.
44//! For coroutines with state 0 (unresumed) it starts the execution of the coroutine.
45//! For coroutines with state 1 (returned) and state 2 (poisoned) it panics.
46//! Otherwise it continues the execution from the last suspension point.
47//!
48//! The other function is the drop glue for the coroutine.
49//! For coroutines with state 0 (unresumed) it drops the upvars of the coroutine.
50//! For coroutines with state 1 (returned) and state 2 (poisoned) it does nothing.
51//! Otherwise it drops all the values in scope at the last suspension point.
52
53mod by_move_body;
54mod drop;
55mod layout;
56
57pub(super) use by_move_body::coroutine_by_move_body_def_id;
58use drop::{
59    create_coroutine_drop_shim, create_coroutine_drop_shim_async,
60    create_coroutine_drop_shim_proxy_async, elaborate_coroutine_drops, has_async_drops,
61    insert_clean_drop,
62};
63pub(super) use layout::mir_coroutine_witnesses;
64use layout::{CoroutineSavedLocals, compute_layout, locals_live_across_suspend_points};
65use rustc_abi::{FieldIdx, VariantIdx};
66use rustc_data_structures::thin_vec::ThinVec;
67use rustc_hir::lang_items::LangItem;
68use rustc_hir::{self as hir, CoroutineDesugaring, CoroutineKind};
69use rustc_index::bit_set::{BitMatrix, DenseBitSet, GrowableBitSet};
70use rustc_index::{Idx, IndexVec, indexvec};
71use rustc_middle::mir::visit::{MutVisitor, MutatingUseContext, PlaceContext, Visitor};
72use rustc_middle::mir::*;
73use rustc_middle::ty::{
74    self, CoroutineArgs, CoroutineArgsExt, GenericArgsRef, InstanceKind, ShimKind, Ty, TyCtxt,
75};
76use rustc_middle::{bug, span_bug};
77use rustc_mir_dataflow::impls::always_storage_live_locals;
78use rustc_span::def_id::DefId;
79use tracing::{debug, instrument};
80
81use crate::deref_separator::deref_finder;
82use crate::patch::MirPatch;
83use crate::{abort_unwinding_calls, pass_manager as pm, simplify};
84
85pub(super) struct StateTransform;
86
87struct RenameLocalVisitor<'tcx> {
88    from: Local,
89    to: Local,
90    tcx: TyCtxt<'tcx>,
91}
92
93impl<'tcx> MutVisitor<'tcx> for RenameLocalVisitor<'tcx> {
94    fn tcx(&self) -> TyCtxt<'tcx> {
95        self.tcx
96    }
97
98    fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
99        if *local == self.from {
100            *local = self.to;
101        } else if *local == self.to {
102            *local = self.from;
103        }
104    }
105
106    fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, location: Location) {
107        match terminator.kind {
108            TerminatorKind::Return => {
109                // Do not replace the implicit `_0` access here, as that's not possible. The
110                // transform already handles `return` correctly.
111            }
112            _ => self.super_terminator(terminator, location),
113        }
114    }
115}
116
117struct SelfArgVisitor<'tcx> {
118    tcx: TyCtxt<'tcx>,
119    new_base: Place<'tcx>,
120}
121
122impl<'tcx> SelfArgVisitor<'tcx> {
123    fn new(tcx: TyCtxt<'tcx>, new_base: Place<'tcx>) -> Self {
124        Self { tcx, new_base }
125    }
126}
127
128impl<'tcx> MutVisitor<'tcx> for SelfArgVisitor<'tcx> {
129    fn tcx(&self) -> TyCtxt<'tcx> {
130        self.tcx
131    }
132
133    fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
134        assert_ne!(*local, SELF_ARG);
135    }
136
137    fn visit_place(&mut self, place: &mut Place<'tcx>, _: PlaceContext, _: Location) {
138        if place.local == SELF_ARG {
139            replace_base(place, self.new_base, self.tcx);
140        }
141
142        for elem in place.projection.iter() {
143            if let PlaceElem::Index(local) = elem {
144                assert_ne!(local, SELF_ARG);
145            }
146        }
147    }
148}
149
150#[tracing::instrument(level = "trace", skip(tcx))]
151fn replace_base<'tcx>(place: &mut Place<'tcx>, new_base: Place<'tcx>, tcx: TyCtxt<'tcx>) {
152    place.local = new_base.local;
153
154    let mut new_projection = new_base.projection.to_vec();
155    new_projection.append(&mut place.projection.to_vec());
156
157    place.projection = tcx.mk_place_elems(&new_projection);
158    tracing::trace!(?place);
159}
160
161const SELF_ARG: Local = Local::arg(0);
162pub(crate) const CTX_ARG: Local = Local::arg(1);
163
164/// A `yield` point in the coroutine.
165struct SuspensionPoint<'tcx> {
166    /// State discriminant used when suspending or resuming at this point.
167    state: usize,
168    /// The block to jump to after resumption.
169    resume: BasicBlock,
170    /// Where to move the resume argument after resumption.
171    resume_arg: Place<'tcx>,
172    /// Which block to jump to if the coroutine is dropped in this state.
173    drop: Option<BasicBlock>,
174    /// Set of locals that have live storage while at this suspension point.
175    storage_liveness: GrowableBitSet<Local>,
176}
177
178struct TransformVisitor<'tcx> {
179    tcx: TyCtxt<'tcx>,
180    coroutine_kind: hir::CoroutineKind,
181
182    // The type of the discriminant in the coroutine struct
183    discr_ty: Ty<'tcx>,
184
185    // Mapping from Local to (type of local, coroutine struct index)
186    remap: IndexVec<Local, Option<(Ty<'tcx>, VariantIdx, FieldIdx)>>,
187
188    // A map from a suspension point in a block to the locals which have live storage at that point
189    storage_liveness: IndexVec<BasicBlock, Option<DenseBitSet<Local>>>,
190
191    // A list of suspension points, generated during the transform
192    suspension_points: Vec<SuspensionPoint<'tcx>>,
193
194    // The set of locals that have no `StorageLive`/`StorageDead` annotations.
195    always_live_locals: DenseBitSet<Local>,
196
197    // New local we just create to hold the `CoroutineState` value.
198    new_ret_local: Local,
199
200    old_yield_ty: Ty<'tcx>,
201
202    old_ret_ty: Ty<'tcx>,
203
204    patch: Option<MirPatch<'tcx>>,
205}
206
207impl<'tcx> TransformVisitor<'tcx> {
208    fn insert_none_ret_block(&self, body: &mut Body<'tcx>) -> BasicBlock {
209        let block = body.basic_blocks.next_index();
210        let source_info = SourceInfo::outermost(body.span);
211
212        let none_value = match self.coroutine_kind {
213            CoroutineKind::Desugared(CoroutineDesugaring::Async, _) => {
214                span_bug!(body.span, "`Future`s are not fused inherently")
215            }
216            CoroutineKind::Coroutine(_) => span_bug!(body.span, "`Coroutine`s cannot be fused"),
217            // `gen` continues return `None`
218            CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
219                let option_def_id = self.tcx.require_lang_item(LangItem::Option, body.span);
220                make_aggregate_adt(
221                    option_def_id,
222                    VariantIdx::ZERO,
223                    self.tcx.mk_args(&[self.old_yield_ty.into()]),
224                    IndexVec::new(),
225                )
226            }
227            // `async gen` continues to return `Poll::Ready(None)`
228            CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => {
229                let ty::Adt(_poll_adt, args) = *self.old_yield_ty.kind() else { bug!() };
230                let ty::Adt(_option_adt, args) = *args.type_at(0).kind() else { bug!() };
231                let yield_ty = args.type_at(0);
232                Rvalue::Use(
233                    Operand::Constant(Box::new(ConstOperand {
234                        span: source_info.span,
235                        const_: Const::Unevaluated(
236                            UnevaluatedConst::new(
237                                self.tcx.require_lang_item(LangItem::AsyncGenFinished, body.span),
238                                self.tcx.mk_args(&[yield_ty.into()]),
239                            ),
240                            self.old_yield_ty,
241                        ),
242                        user_ty: None,
243                    })),
244                    WithRetag::Yes,
245                )
246            }
247        };
248
249        let statements = vec![Statement::new(
250            source_info,
251            StatementKind::Assign(Box::new((Place::return_place(), none_value))),
252        )];
253
254        body.basic_blocks_mut().push(BasicBlockData::new_stmts(
255            statements,
256            Some(Terminator {
257                source_info,
258                kind: TerminatorKind::Return,
259                attributes: ThinVec::new(),
260            }),
261            false,
262        ));
263
264        block
265    }
266
267    // Make a `CoroutineState` or `Poll` variant assignment.
268    //
269    // `core::ops::CoroutineState` only has single element tuple variants,
270    // so we can just write to the downcasted first field and then set the
271    // discriminant to the appropriate variant.
272    #[tracing::instrument(level = "trace", skip(self, statements))]
273    fn make_state(
274        &self,
275        val: Operand<'tcx>,
276        source_info: SourceInfo,
277        is_return: bool,
278        statements: &mut Vec<Statement<'tcx>>,
279    ) {
280        const ZERO: VariantIdx = VariantIdx::ZERO;
281        const ONE: VariantIdx = VariantIdx::from_usize(1);
282        let rvalue = match self.coroutine_kind {
283            CoroutineKind::Desugared(CoroutineDesugaring::Async, _) => {
284                let poll_def_id = self.tcx.require_lang_item(LangItem::Poll, source_info.span);
285                let args = self.tcx.mk_args(&[self.old_ret_ty.into()]);
286                let (variant_idx, operands) = if is_return {
287                    (ZERO, indexvec![val]) // Poll::Ready(val)
288                } else {
289                    (ONE, IndexVec::new()) // Poll::Pending
290                };
291                make_aggregate_adt(poll_def_id, variant_idx, args, operands)
292            }
293            CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
294                let option_def_id = self.tcx.require_lang_item(LangItem::Option, source_info.span);
295                let args = self.tcx.mk_args(&[self.old_yield_ty.into()]);
296                let (variant_idx, operands) = if is_return {
297                    (ZERO, IndexVec::new()) // None
298                } else {
299                    (ONE, indexvec![val]) // Some(val)
300                };
301                make_aggregate_adt(option_def_id, variant_idx, args, operands)
302            }
303            CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => {
304                if is_return {
305                    let ty::Adt(_poll_adt, args) = *self.old_yield_ty.kind() else { bug!() };
306                    let ty::Adt(_option_adt, args) = *args.type_at(0).kind() else { bug!() };
307                    let yield_ty = args.type_at(0);
308                    Rvalue::Use(
309                        Operand::Constant(Box::new(ConstOperand {
310                            span: source_info.span,
311                            const_: Const::Unevaluated(
312                                UnevaluatedConst::new(
313                                    self.tcx.require_lang_item(
314                                        LangItem::AsyncGenFinished,
315                                        source_info.span,
316                                    ),
317                                    self.tcx.mk_args(&[yield_ty.into()]),
318                                ),
319                                self.old_yield_ty,
320                            ),
321                            user_ty: None,
322                        })),
323                        WithRetag::Yes,
324                    )
325                } else {
326                    Rvalue::Use(val, WithRetag::Yes)
327                }
328            }
329            CoroutineKind::Coroutine(_) => {
330                let coroutine_state_def_id =
331                    self.tcx.require_lang_item(LangItem::CoroutineState, source_info.span);
332                let args = self.tcx.mk_args(&[self.old_yield_ty.into(), self.old_ret_ty.into()]);
333                let variant_idx = if is_return {
334                    ONE // CoroutineState::Complete(val)
335                } else {
336                    ZERO // CoroutineState::Yielded(val)
337                };
338                make_aggregate_adt(coroutine_state_def_id, variant_idx, args, indexvec![val])
339            }
340        };
341
342        // Assign to `new_ret_local`, which will be replaced by `RETURN_PLACE` later.
343        statements.push(Statement::new(
344            source_info,
345            StatementKind::Assign(Box::new((self.new_ret_local.into(), rvalue))),
346        ));
347    }
348
349    // Create a Place referencing a coroutine struct field
350    #[tracing::instrument(level = "trace", skip(self), ret)]
351    fn make_field(&self, variant_index: VariantIdx, idx: FieldIdx, ty: Ty<'tcx>) -> Place<'tcx> {
352        let self_place = Place::from(SELF_ARG);
353        let base = self.tcx.mk_place_downcast_unnamed(self_place, variant_index);
354        let mut projection = base.projection.to_vec();
355        projection.push(ProjectionElem::Field(idx, ty));
356
357        Place { local: base.local, projection: self.tcx.mk_place_elems(&projection) }
358    }
359
360    // Create a statement which changes the discriminant
361    #[tracing::instrument(level = "trace", skip(self))]
362    fn set_discr(&self, state_disc: VariantIdx, source_info: SourceInfo) -> Statement<'tcx> {
363        let self_place = Place::from(SELF_ARG);
364        Statement::new(
365            source_info,
366            StatementKind::SetDiscriminant {
367                place: Box::new(self_place),
368                variant_index: state_disc,
369            },
370        )
371    }
372
373    // Create a statement which reads the discriminant into a temporary
374    #[tracing::instrument(level = "trace", skip(self, body))]
375    fn get_discr(&self, body: &mut Body<'tcx>) -> (Statement<'tcx>, Place<'tcx>) {
376        let temp_decl = LocalDecl::new(self.discr_ty, body.span);
377        let local_decls_len = body.local_decls.push(temp_decl);
378        let temp = Place::from(local_decls_len);
379
380        let self_place = Place::from(SELF_ARG);
381        let assign = Statement::new(
382            SourceInfo::outermost(body.span),
383            StatementKind::Assign(Box::new((temp, Rvalue::Discriminant(self_place)))),
384        );
385        (assign, temp)
386    }
387
388    /// Swaps all references of `old_local` and `new_local`.
389    #[tracing::instrument(level = "trace", skip(self, body))]
390    fn replace_local(&mut self, old_local: Local, new_local: Local, body: &mut Body<'tcx>) {
391        body.local_decls.swap(old_local, new_local);
392
393        let mut visitor = RenameLocalVisitor { from: old_local, to: new_local, tcx: self.tcx };
394        visitor.visit_body(body);
395        for suspension in &mut self.suspension_points {
396            let ctxt = PlaceContext::MutatingUse(MutatingUseContext::Yield);
397            let location = Location { block: START_BLOCK, statement_index: 0 };
398            visitor.visit_place(&mut suspension.resume_arg, ctxt, location);
399        }
400    }
401}
402
403impl<'tcx> MutVisitor<'tcx> for TransformVisitor<'tcx> {
404    fn tcx(&self) -> TyCtxt<'tcx> {
405        self.tcx
406    }
407
408    #[tracing::instrument(level = "trace", skip(self), ret)]
409    fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _location: Location) {
410        assert!(!self.remap.contains(*local));
411    }
412
413    #[tracing::instrument(level = "trace", skip(self), ret)]
414    fn visit_place(&mut self, place: &mut Place<'tcx>, _: PlaceContext, location: Location) {
415        // Replace an Local in the remap with a coroutine struct access
416        if let Some(&Some((ty, variant_index, idx))) = self.remap.get(place.local) {
417            replace_base(place, self.make_field(variant_index, idx, ty), self.tcx);
418        }
419        if let Some(new_projection) = self.process_projection(&place.projection, location) {
420            place.projection = self.tcx.mk_place_elems(&new_projection);
421        }
422    }
423
424    fn process_projection_elem(
425        &mut self,
426        elem: PlaceElem<'tcx>,
427        location: Location,
428    ) -> Option<PlaceElem<'tcx>> {
429        match elem {
430            PlaceElem::Index(local) => {
431                if let Some(&Some((ty, variant, idx))) = self.remap.get(local) {
432                    // `PlaceElem::Index` only accepts a `Local`, not an arbitrary `Place`.
433                    // If the local in indexing was saved across a yield point and remapped to a
434                    // coroutine struct field, we cannot inline the struct field access into
435                    // the index projection.
436                    // For example, an local storing the counter to track which element to drop in
437                    // an array is one such case.
438                    //
439                    // Instead, we inject an assignment before this location to restore the
440                    // saved local from the coroutine struct (`local = copy $projection`),
441                    // and leave the `PlaceElem::Index(local)` projection unchanged.
442                    let field = self.make_field(variant, idx, ty);
443                    self.patch.as_mut().unwrap().add_assign(
444                        location,
445                        Place::from(local),
446                        Rvalue::Use(Operand::Copy(field), WithRetag::No),
447                    );
448                }
449                None
450            }
451            PlaceElem::Field(..)
452            | PlaceElem::OpaqueCast(..)
453            | PlaceElem::UnwrapUnsafeBinder(..)
454            | PlaceElem::Deref
455            | PlaceElem::ConstantIndex { .. }
456            | PlaceElem::Subslice { .. }
457            | PlaceElem::Downcast(..) => None,
458        }
459    }
460
461    #[tracing::instrument(level = "trace", skip(self, stmt), ret)]
462    fn visit_statement(&mut self, stmt: &mut Statement<'tcx>, location: Location) {
463        // Remove StorageLive and StorageDead statements for remapped locals
464        if let StatementKind::StorageLive(l) | StatementKind::StorageDead(l) = stmt.kind
465            && self.remap.contains(l)
466        {
467            stmt.make_nop(true);
468        }
469        self.super_statement(stmt, location);
470    }
471
472    #[tracing::instrument(level = "trace", skip(self, term), ret)]
473    fn visit_terminator(&mut self, term: &mut Terminator<'tcx>, location: Location) {
474        if let TerminatorKind::Return = term.kind {
475            // `visit_basic_block_data` introduces `Return` terminators which read `RETURN_PLACE`.
476            // But this `RETURN_PLACE` is already remapped, so we should not touch it again.
477            return;
478        }
479        self.super_terminator(term, location);
480    }
481
482    #[tracing::instrument(level = "trace", skip(self, data), ret)]
483    fn visit_basic_block_data(&mut self, block: BasicBlock, data: &mut BasicBlockData<'tcx>) {
484        match data.terminator().kind {
485            TerminatorKind::Return => {
486                let source_info = data.terminator().source_info;
487                // We must assign the value first in case it gets declared dead below
488                self.make_state(
489                    Operand::Move(Place::return_place()),
490                    source_info,
491                    true,
492                    &mut data.statements,
493                );
494                // Return state.
495                let state = VariantIdx::new(CoroutineArgs::RETURNED);
496                data.statements.push(self.set_discr(state, source_info));
497                data.terminator_mut().kind = TerminatorKind::Return;
498            }
499            TerminatorKind::Yield { ref value, resume, mut resume_arg, drop } => {
500                let source_info = data.terminator().source_info;
501                // We must assign the value first in case it gets declared dead below
502                self.make_state(value.clone(), source_info, false, &mut data.statements);
503                // Yield state.
504                let state = CoroutineArgs::RESERVED_VARIANTS + self.suspension_points.len();
505
506                // The resume arg target location might itself be remapped if its base local is
507                // live across a yield.
508                if let Some(&Some((ty, variant, idx))) = self.remap.get(resume_arg.local) {
509                    replace_base(&mut resume_arg, self.make_field(variant, idx, ty), self.tcx);
510                }
511
512                let storage_liveness: GrowableBitSet<Local> =
513                    self.storage_liveness[block].clone().unwrap().into();
514
515                for i in 0..self.always_live_locals.domain_size() {
516                    let l = Local::new(i);
517                    let needs_storage_dead = storage_liveness.contains(l)
518                        && !self.remap.contains(l)
519                        && !self.always_live_locals.contains(l);
520                    if needs_storage_dead {
521                        data.statements
522                            .push(Statement::new(source_info, StatementKind::StorageDead(l)));
523                    }
524                }
525
526                self.suspension_points.push(SuspensionPoint {
527                    state,
528                    resume,
529                    resume_arg,
530                    drop,
531                    storage_liveness,
532                });
533
534                let state = VariantIdx::new(state);
535                data.statements.push(self.set_discr(state, source_info));
536                data.terminator_mut().kind = TerminatorKind::Return;
537            }
538            _ => {}
539        }
540
541        self.super_basic_block_data(block, data);
542    }
543}
544
545fn make_aggregate_adt<'tcx>(
546    def_id: DefId,
547    variant_idx: VariantIdx,
548    args: GenericArgsRef<'tcx>,
549    operands: IndexVec<FieldIdx, Operand<'tcx>>,
550) -> Rvalue<'tcx> {
551    Rvalue::Aggregate(Box::new(AggregateKind::Adt(def_id, variant_idx, args, None, None)), operands)
552}
553
554#[tracing::instrument(level = "trace", skip(tcx, body))]
555fn make_coroutine_state_argument_indirect<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
556    let coroutine_ty = body.local_decls[SELF_ARG].ty;
557
558    let ref_coroutine_ty = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, coroutine_ty);
559
560    // Replace the by value coroutine argument
561    body.local_decls[SELF_ARG].ty = ref_coroutine_ty;
562
563    // Add a deref to accesses of the coroutine state
564    SelfArgVisitor::new(tcx, tcx.mk_place_deref(SELF_ARG.into())).visit_body(body);
565}
566
567#[tracing::instrument(level = "trace", skip(tcx, body))]
568fn make_coroutine_state_argument_pinned<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
569    let coroutine_ty = body.local_decls[SELF_ARG].ty;
570
571    let ref_coroutine_ty = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, coroutine_ty);
572
573    let pin_did = tcx.require_lang_item(LangItem::Pin, body.span);
574    let pin_adt_ref = tcx.adt_def(pin_did);
575    let args = tcx.mk_args(&[ref_coroutine_ty.into()]);
576    let pin_ref_coroutine_ty = Ty::new_adt(tcx, pin_adt_ref, args);
577
578    // Replace the by ref coroutine argument
579    body.local_decls[SELF_ARG].ty = pin_ref_coroutine_ty;
580
581    let unpinned_local = body.local_decls.push(LocalDecl::new(ref_coroutine_ty, body.span));
582
583    // Add the Pin field access to accesses of the coroutine state
584    SelfArgVisitor::new(tcx, tcx.mk_place_deref(unpinned_local.into())).visit_body(body);
585
586    let source_info = SourceInfo::outermost(body.span);
587    let pin_field = tcx.mk_place_field(SELF_ARG.into(), FieldIdx::ZERO, ref_coroutine_ty);
588
589    let statements = &mut body.basic_blocks.as_mut_preserves_cfg()[START_BLOCK].statements;
590    statements.insert(
591        0,
592        Statement::new(
593            source_info,
594            StatementKind::Assign(Box::new((
595                unpinned_local.into(),
596                Rvalue::Use(Operand::Copy(pin_field), WithRetag::Yes),
597            ))),
598        ),
599    );
600}
601
602/// Async desugaring uses an unsafe binder type `ResumeTy` to circumvert borrow-checking.
603/// The `ResumeTy` hides a `&mut Context<'_>` behind an unsafe raw pointer, and the
604/// `get_context` function is being used to convert that back to a `&mut Context<'_>`.
605///
606/// The actual should be `&mut Context<'_>`. This performs the substitution:
607/// - create a new local `_r` of type `ResumeTy`;
608/// - assign `ResumeTy(transmute::<&mut Context<'_>, NonNull<Context<'_>>>(_2))` to that local;
609/// - let all the code use `_r` instead of `_2`.
610///
611/// Ideally the async lowering would not use the `ResumeTy`/`get_context` indirection,
612/// but rather directly use `&mut Context<'_>`, however that would currently
613/// lead to higher-kinded lifetime errors.
614/// See <https://github.com/rust-lang/rust/issues/105501>.
615///
616/// The async lowering step and the type / lifetime inference / checking are
617/// still using the `ResumeTy` indirection for the time being, and that indirection
618/// is removed here. After this transform, the coroutine body only knows about `&mut Context<'_>`.
619#[tracing::instrument(level = "trace", skip(tcx, body), ret)]
620fn transform_async_context<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
621    let context_mut_ref = Ty::new_task_context(tcx);
622    let resume_ty_def_id = tcx.require_lang_item(LangItem::ResumeTy, body.span);
623    let resume_nonnull_ty = tcx.instantiate_and_normalize_erasing_regions(
624        ty::GenericArgs::empty(),
625        body.typing_env(tcx),
626        tcx.type_of(tcx.adt_def(resume_ty_def_id).non_enum_variant().fields[FieldIdx::ZERO].did),
627    );
628
629    // Replace all occurrences of `CTX_ARG` with `resume_local: ResumeTy`,
630    // and set `CTX_ARG: &mut Context<'_>`.
631    let resume_local = body.local_decls.push(LocalDecl::new(context_mut_ref, body.span));
632    body.local_decls.swap(CTX_ARG, resume_local);
633    RenameLocalVisitor { from: CTX_ARG, to: resume_local, tcx }.visit_body(body);
634
635    // Now `CTX_ARG` is `&mut Context` and `resume_local` is a `ResumeTy`.
636    // Insert a `resume_local = ResumeTy(CTX_ARG as *mut Context<'static>)`
637    // at the function entry to make the bridge.
638    let source_info = SourceInfo::outermost(body.span);
639    let nonnull_local = body.local_decls.push(LocalDecl::new(resume_nonnull_ty, body.span));
640    let nonnull_rhs =
641        Rvalue::Cast(CastKind::Transmute, Operand::Move(CTX_ARG.into()), resume_nonnull_ty);
642    let nonnull_assign = StatementKind::Assign(Box::new((nonnull_local.into(), nonnull_rhs)));
643    let resume_rhs = Rvalue::Aggregate(
644        Box::new(AggregateKind::Adt(
645            resume_ty_def_id,
646            VariantIdx::ZERO,
647            ty::GenericArgs::empty(),
648            None,
649            None,
650        )),
651        indexvec![Operand::Move(nonnull_local.into())],
652    );
653    let resume_assign = StatementKind::Assign(Box::new((resume_local.into(), resume_rhs)));
654    body.basic_blocks.as_mut_preserves_cfg()[START_BLOCK].statements.splice(
655        0..0,
656        [Statement::new(source_info, nonnull_assign), Statement::new(source_info, resume_assign)],
657    );
658}
659
660/// HIR uses `get_context` to unwrap a `&mut Context<'_>` from a `ResumeTy`.
661/// Both types are just a single pointer, but liveness analysis does not know that and
662/// supposes that the operand and the destination are live at the same time.
663/// Forcibly inline those calls to avoid this.
664fn eliminate_get_context_calls<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
665    let context_mut_ref = Ty::new_task_context(tcx);
666    let resume_ty_def_id = tcx.require_lang_item(LangItem::ResumeTy, body.span);
667    let resume_nonnull_ty = tcx.instantiate_and_normalize_erasing_regions(
668        ty::GenericArgs::empty(),
669        body.typing_env(tcx),
670        tcx.type_of(tcx.adt_def(resume_ty_def_id).non_enum_variant().fields[FieldIdx::ZERO].did),
671    );
672
673    let get_context_def_id = tcx.require_lang_item(LangItem::GetContext, body.span);
674    for bb_data in body.basic_blocks.as_mut().iter_mut() {
675        if bb_data.is_cleanup {
676            continue;
677        }
678
679        let terminator = bb_data.terminator_mut();
680        if let TerminatorKind::Call { func, args, destination, target, .. } = &terminator.kind
681            && let func_ty = func.ty(&body.local_decls, tcx)
682            && let ty::FnDef(def_id, _) = *func_ty.kind()
683            && def_id == get_context_def_id
684            && let [arg] = &**args
685            && let Some(place) = arg.node.place()
686        {
687            let arg =
688                Rvalue::Cast(
689                    CastKind::Transmute,
690                    Operand::Copy(place.project_deeper(
691                        &[PlaceElem::Field(FieldIdx::ZERO, resume_nonnull_ty)],
692                        tcx,
693                    )),
694                    context_mut_ref,
695                );
696            let assign = Statement::new(
697                terminator.source_info,
698                StatementKind::Assign(Box::new((*destination, arg))),
699            );
700            terminator.kind = TerminatorKind::Goto { target: target.unwrap() };
701            bb_data.statements.push(assign);
702        }
703    }
704}
705
706/// Replaces the entry point of `body` with a block that switches on the coroutine discriminant and
707/// dispatches to blocks according to `cases`.
708///
709/// After this function, the former entry point of the function will be the last block.
710fn insert_switch<'tcx>(
711    body: &mut Body<'tcx>,
712    cases: Vec<(usize, BasicBlock)>,
713    transform: &TransformVisitor<'tcx>,
714    default_block: BasicBlock,
715) {
716    let (assign, discr) = transform.get_discr(body);
717
718    // MIR validation ensures that no block targets `ENTRY_BLOCK`.
719    #[cfg(debug_assertions)]
720    for bb in body.basic_blocks.iter() {
721        for target in bb.terminator().successors() {
722            assert_ne!(target, START_BLOCK);
723        }
724    }
725
726    // Add the switch as entry block, and put the former entry block at the end.
727    let former_entry = std::mem::replace(
728        &mut body.basic_blocks_mut()[START_BLOCK],
729        BasicBlockData::new_stmts(vec![assign], None, false),
730    );
731    let former_entry = body.basic_blocks_mut().push(former_entry);
732
733    // We may point to `START_BLOCK` in our `cases`, replace it with `former_entry`.
734    let mut switch_targets =
735        SwitchTargets::new(cases.iter().map(|(i, bb)| ((*i) as u128, *bb)), default_block);
736    for bb in switch_targets.all_targets_mut() {
737        if *bb == START_BLOCK {
738            *bb = former_entry;
739        }
740    }
741
742    let switch = TerminatorKind::SwitchInt { discr: Operand::Move(discr), targets: switch_targets };
743    body.basic_blocks_mut()[START_BLOCK].terminator = Some(Terminator {
744        source_info: SourceInfo::outermost(body.span),
745        kind: switch,
746        attributes: ThinVec::new(),
747    });
748}
749
750fn insert_term_block<'tcx>(body: &mut Body<'tcx>, kind: TerminatorKind<'tcx>) -> BasicBlock {
751    let source_info = SourceInfo::outermost(body.span);
752    body.basic_blocks_mut().push(BasicBlockData::new(
753        Some(Terminator { source_info, kind, attributes: ThinVec::new() }),
754        false,
755    ))
756}
757
758fn return_poll_ready_assign<'tcx>(tcx: TyCtxt<'tcx>, source_info: SourceInfo) -> Statement<'tcx> {
759    // Poll::Ready(())
760    let poll_def_id = tcx.require_lang_item(LangItem::Poll, source_info.span);
761    let args = tcx.mk_args(&[tcx.types.unit.into()]);
762    let val = Operand::Constant(Box::new(ConstOperand {
763        span: source_info.span,
764        user_ty: None,
765        const_: Const::zero_sized(tcx.types.unit),
766    }));
767    let ready_val = Rvalue::Aggregate(
768        Box::new(AggregateKind::Adt(poll_def_id, VariantIdx::from_usize(0), args, None, None)),
769        indexvec![val],
770    );
771    Statement::new(source_info, StatementKind::Assign(Box::new((Place::return_place(), ready_val))))
772}
773
774fn insert_poll_ready_block<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) -> BasicBlock {
775    let source_info = SourceInfo::outermost(body.span);
776    body.basic_blocks_mut().push(BasicBlockData::new_stmts(
777        [return_poll_ready_assign(tcx, source_info)].to_vec(),
778        Some(Terminator { source_info, kind: TerminatorKind::Return, attributes: ThinVec::new() }),
779        false,
780    ))
781}
782
783fn insert_panic_block<'tcx>(
784    tcx: TyCtxt<'tcx>,
785    body: &mut Body<'tcx>,
786    message: AssertMessage<'tcx>,
787) -> BasicBlock {
788    let assert_block = body.basic_blocks.next_index();
789    let kind = TerminatorKind::Assert {
790        cond: Operand::Constant(Box::new(ConstOperand {
791            span: body.span,
792            user_ty: None,
793            const_: Const::from_bool(tcx, false),
794        })),
795        expected: true,
796        msg: Box::new(message),
797        target: assert_block,
798        unwind: UnwindAction::Continue,
799    };
800
801    insert_term_block(body, kind)
802}
803
804fn can_return<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
805    // Returning from a function with an uninhabited return type is undefined behavior.
806    if body.return_ty().is_privately_uninhabited(tcx, typing_env) {
807        return false;
808    }
809
810    // If there's a return terminator the function may return.
811    body.basic_blocks.iter().any(|block| matches!(block.terminator().kind, TerminatorKind::Return))
812    // Otherwise the function can't return.
813}
814
815fn can_unwind<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>) -> bool {
816    // Nothing can unwind when landing pads are off.
817    if !tcx.sess.panic_strategy().unwinds() {
818        return false;
819    }
820
821    // If we don't find an unwinding terminator, the function cannot unwind.
822    body.basic_blocks.iter().any(|block| block.terminator().unwind().is_some())
823}
824
825// Poison the coroutine when it unwinds
826fn generate_poison_block_and_redirect_unwinds_there<'tcx>(
827    transform: &TransformVisitor<'tcx>,
828    body: &mut Body<'tcx>,
829) {
830    let source_info = SourceInfo::outermost(body.span);
831    let poison_block = body.basic_blocks_mut().push(BasicBlockData::new_stmts(
832        vec![transform.set_discr(VariantIdx::new(CoroutineArgs::POISONED), source_info)],
833        Some(Terminator {
834            source_info,
835            kind: TerminatorKind::UnwindResume,
836
837            attributes: ThinVec::new(),
838        }),
839        true,
840    ));
841
842    for (idx, block) in body.basic_blocks_mut().iter_enumerated_mut() {
843        let source_info = block.terminator().source_info;
844
845        if let TerminatorKind::UnwindResume = block.terminator().kind {
846            // An existing `Resume` terminator is redirected to jump to our dedicated
847            // "poisoning block" above.
848            if idx != poison_block {
849                *block.terminator_mut() = Terminator {
850                    source_info,
851                    kind: TerminatorKind::Goto { target: poison_block },
852
853                    attributes: ThinVec::new(),
854                };
855            }
856        } else if !block.is_cleanup
857            // Any terminators that *can* unwind but don't have an unwind target set are also
858            // pointed at our poisoning block (unless they're part of the cleanup path).
859            && let Some(unwind @ UnwindAction::Continue) = block.terminator_mut().unwind_mut()
860        {
861            *unwind = UnwindAction::Cleanup(poison_block);
862        }
863    }
864}
865
866#[tracing::instrument(level = "trace", skip(tcx, transform, body))]
867fn create_coroutine_resume_function<'tcx>(
868    tcx: TyCtxt<'tcx>,
869    transform: TransformVisitor<'tcx>,
870    body: &mut Body<'tcx>,
871    can_return: bool,
872    can_unwind: bool,
873) {
874    // Poison the coroutine when it unwinds
875    if can_unwind {
876        generate_poison_block_and_redirect_unwinds_there(&transform, body);
877    }
878
879    let mut cases = create_cases(body, &transform, Operation::Resume);
880
881    use rustc_middle::mir::AssertKind::{ResumedAfterPanic, ResumedAfterReturn};
882
883    // Jump to the entry point on the unresumed
884    cases.insert(0, (CoroutineArgs::UNRESUMED, START_BLOCK));
885
886    // Panic when resumed on the returned or poisoned state
887    if can_unwind {
888        cases.insert(
889            1,
890            (
891                CoroutineArgs::POISONED,
892                insert_panic_block(tcx, body, ResumedAfterPanic(transform.coroutine_kind)),
893            ),
894        );
895    }
896
897    if can_return {
898        let block = match transform.coroutine_kind {
899            CoroutineKind::Desugared(CoroutineDesugaring::Async, _)
900            | CoroutineKind::Coroutine(_) => {
901                // For `async_drop_in_place<T>::{closure}` we just keep return Poll::Ready,
902                // because async drop of such coroutine keeps polling original coroutine
903                if tcx.is_async_drop_in_place_coroutine(body.source.def_id()) {
904                    insert_poll_ready_block(tcx, body)
905                } else {
906                    insert_panic_block(tcx, body, ResumedAfterReturn(transform.coroutine_kind))
907                }
908            }
909            CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _)
910            | CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
911                transform.insert_none_ret_block(body)
912            }
913        };
914        cases.insert(1, (CoroutineArgs::RETURNED, block));
915    }
916
917    let default_block = insert_term_block(body, TerminatorKind::Unreachable);
918    insert_switch(body, cases, &transform, default_block);
919
920    match transform.coroutine_kind {
921        CoroutineKind::Coroutine(_)
922        | CoroutineKind::Desugared(CoroutineDesugaring::Async | CoroutineDesugaring::AsyncGen, _) =>
923        {
924            make_coroutine_state_argument_pinned(tcx, body);
925        }
926        // Iterator::next doesn't accept a pinned argument,
927        // unlike for all other coroutine kinds.
928        CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
929            make_coroutine_state_argument_indirect(tcx, body);
930        }
931    }
932
933    // Make sure we remove dead blocks to remove
934    // unrelated code from the drop part of the function
935    simplify::remove_dead_blocks(body);
936
937    pm::run_passes_no_validate(tcx, body, &[&abort_unwinding_calls::AbortUnwindingCalls], None);
938
939    // Run derefer to fix Derefs that are not in the first place
940    deref_finder(tcx, body, false);
941
942    if transform.coroutine_kind.is_async_desugaring() {
943        transform_async_context(tcx, body);
944    }
945
946    if let Some(dumper) = MirDumper::new(tcx, "coroutine_resume", body) {
947        dumper.dump_mir(body);
948    }
949}
950
951/// An operation that can be performed on a coroutine.
952#[derive(PartialEq, Copy, Clone, Debug)]
953enum Operation {
954    Resume,
955    Drop,
956    AsyncDrop,
957}
958
959impl Operation {
960    fn target_block(self, point: &SuspensionPoint<'_>) -> Option<BasicBlock> {
961        match self {
962            Operation::Resume => Some(point.resume),
963            Operation::Drop | Operation::AsyncDrop => point.drop,
964        }
965    }
966
967    fn resume_place<'tcx>(self, point: &SuspensionPoint<'tcx>) -> Option<Place<'tcx>> {
968        match self {
969            Operation::Resume | Operation::AsyncDrop => Some(point.resume_arg),
970            Operation::Drop => None,
971        }
972    }
973}
974
975#[tracing::instrument(level = "trace", skip(transform, body))]
976fn create_cases<'tcx>(
977    body: &mut Body<'tcx>,
978    transform: &TransformVisitor<'tcx>,
979    operation: Operation,
980) -> Vec<(usize, BasicBlock)> {
981    let source_info = SourceInfo::outermost(body.span);
982
983    transform
984        .suspension_points
985        .iter()
986        .filter_map(|point| {
987            // Find the target for this suspension point, if applicable
988            operation.target_block(point).map(|target| {
989                let mut statements = Vec::new();
990
991                // Create StorageLive instructions for locals with live storage
992                for l in body.local_decls.indices() {
993                    let needs_storage_live = point.storage_liveness.contains(l)
994                        && !transform.remap.contains(l)
995                        && !transform.always_live_locals.contains(l);
996                    if needs_storage_live {
997                        statements.push(Statement::new(source_info, StatementKind::StorageLive(l)));
998                    }
999                }
1000
1001                // Move the resume argument to the destination place of the `Yield` terminator
1002                if let Some(resume_arg) = operation.resume_place(point)
1003                    && resume_arg != CTX_ARG.into()
1004                {
1005                    statements.push(Statement::new(
1006                        source_info,
1007                        StatementKind::Assign(Box::new((
1008                            resume_arg,
1009                            Rvalue::Use(Operand::Move(CTX_ARG.into()), WithRetag::Yes),
1010                        ))),
1011                    ));
1012                }
1013
1014                // Then jump to the real target
1015                let block = body.basic_blocks_mut().push(BasicBlockData::new_stmts(
1016                    statements,
1017                    Some(Terminator {
1018                        source_info,
1019                        kind: TerminatorKind::Goto { target },
1020
1021                        attributes: ThinVec::new(),
1022                    }),
1023                    false,
1024                ));
1025
1026                (point.state, block)
1027            })
1028        })
1029        .collect()
1030}
1031
1032impl<'tcx> crate::MirPass<'tcx> for StateTransform {
1033    #[instrument(level = "debug", skip(self, tcx, body), ret)]
1034    fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
1035        debug!(def_id = ?body.source.def_id());
1036
1037        let Some(old_yield_ty) = body.yield_ty() else {
1038            // This only applies to coroutines
1039            return;
1040        };
1041        tracing::trace!(def_id = ?body.source.def_id());
1042
1043        let old_ret_ty = body.return_ty();
1044
1045        assert!(body.coroutine_drop().is_none() && body.coroutine_drop_async().is_none());
1046
1047        if let Some(dumper) = MirDumper::new(tcx, "coroutine_before", body) {
1048            dumper.dump_mir(body);
1049        }
1050
1051        // The first argument is the coroutine type passed by value
1052        let coroutine_ty = body.local_decls.raw[1].ty;
1053        let coroutine_kind = body.coroutine_kind().unwrap();
1054
1055        // Get the discriminant type and args which typeck computed
1056        let ty::Coroutine(_, args) = coroutine_ty.kind() else {
1057            tcx.dcx().span_bug(body.span, format!("unexpected coroutine type {coroutine_ty}"));
1058        };
1059        let discr_ty = args.as_coroutine().discr_ty(tcx);
1060
1061        let new_ret_ty = match coroutine_kind {
1062            CoroutineKind::Desugared(CoroutineDesugaring::Async, _) => {
1063                // Compute Poll<return_ty>
1064                let poll_did = tcx.require_lang_item(LangItem::Poll, body.span);
1065                let poll_adt_ref = tcx.adt_def(poll_did);
1066                let poll_args = tcx.mk_args(&[old_ret_ty.into()]);
1067                Ty::new_adt(tcx, poll_adt_ref, poll_args)
1068            }
1069            CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
1070                // Compute Option<yield_ty>
1071                let option_did = tcx.require_lang_item(LangItem::Option, body.span);
1072                let option_adt_ref = tcx.adt_def(option_did);
1073                let option_args = tcx.mk_args(&[old_yield_ty.into()]);
1074                Ty::new_adt(tcx, option_adt_ref, option_args)
1075            }
1076            CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => {
1077                // The yield ty is already `Poll<Option<yield_ty>>`
1078                old_yield_ty
1079            }
1080            CoroutineKind::Coroutine(_) => {
1081                // Compute CoroutineState<yield_ty, return_ty>
1082                let state_did = tcx.require_lang_item(LangItem::CoroutineState, body.span);
1083                let state_adt_ref = tcx.adt_def(state_did);
1084                let state_args = tcx.mk_args(&[old_yield_ty.into(), old_ret_ty.into()]);
1085                Ty::new_adt(tcx, state_adt_ref, state_args)
1086            }
1087        };
1088
1089        // We need to insert clean drop for unresumed state and perform drop elaboration
1090        // (finally in open_drop_for_tuple) before async drop expansion.
1091        // Async drops, produced by this drop elaboration, will be expanded,
1092        // and corresponding futures kept in layout.
1093        let has_async_drops = has_async_drops(body);
1094
1095        if coroutine_kind.is_async_desugaring() {
1096            eliminate_get_context_calls(tcx, body);
1097        }
1098
1099        let always_live_locals = always_storage_live_locals(body);
1100        let movable = coroutine_kind.movability() == hir::Movability::Movable;
1101        let liveness_info =
1102            locals_live_across_suspend_points(tcx, body, &always_live_locals, movable);
1103
1104        if tcx.sess.opts.unstable_opts.validate_mir {
1105            let mut vis = EnsureCoroutineFieldAssignmentsNeverAlias {
1106                assigned_local: None,
1107                saved_locals: &liveness_info.saved_locals,
1108                storage_conflicts: &liveness_info.storage_conflicts,
1109            };
1110
1111            vis.visit_body(body);
1112        }
1113
1114        // Extract locals which are live across suspension point into `layout`
1115        // `remap` gives a mapping from local indices onto coroutine struct indices
1116        // `storage_liveness` tells us which locals have live storage at suspension points
1117        let (remap, layout, storage_liveness) = compute_layout(liveness_info, body);
1118
1119        let can_return = can_return(tcx, body, body.typing_env(tcx));
1120
1121        // We rename RETURN_PLACE which has type mir.return_ty to new_ret_local
1122        // RETURN_PLACE then is a fresh unused local with type ret_ty.
1123        let new_ret_local = body.local_decls.push(LocalDecl::new(new_ret_ty, body.span));
1124        tracing::trace!(?new_ret_local);
1125
1126        // Run the transformation which converts Places from Local to coroutine struct
1127        // accesses for locals in `remap`.
1128        // It also rewrites `return x` and `yield y` as writing a new coroutine state and returning
1129        // either `CoroutineState::Complete(x)` and `CoroutineState::Yielded(y)`,
1130        // or `Poll::Ready(x)` and `Poll::Pending` respectively depending on the coroutine kind.
1131        let mut transform = TransformVisitor {
1132            tcx,
1133            coroutine_kind,
1134            remap,
1135            storage_liveness,
1136            always_live_locals,
1137            suspension_points: Vec::new(),
1138            discr_ty,
1139            new_ret_local,
1140            old_ret_ty,
1141            old_yield_ty,
1142            patch: Some(MirPatch::new(body)),
1143        };
1144        transform.visit_body(body);
1145
1146        // Swap the actual `RETURN_PLACE` and the provisional `new_ret_local`.
1147        transform.replace_local(RETURN_PLACE, new_ret_local, body);
1148
1149        // MIR parameters are not explicitly assigned-to when entering the MIR body.
1150        // If we want to save their values inside the coroutine state, we need to do so explicitly.
1151        let source_info = SourceInfo::outermost(body.span);
1152        let args_iter = body.args_iter();
1153        body.basic_blocks.as_mut()[START_BLOCK].statements.splice(
1154            0..0,
1155            args_iter.filter_map(|local| {
1156                let (ty, variant_index, idx) = transform.remap[local]?;
1157                let lhs = transform.make_field(variant_index, idx, ty);
1158                let rhs = Rvalue::Use(Operand::Move(local.into()), WithRetag::Yes);
1159                let assign = StatementKind::Assign(Box::new((lhs, rhs)));
1160                Some(Statement::new(source_info, assign))
1161            }),
1162        );
1163        transform.patch.take().unwrap().apply(body);
1164
1165        // Remove the context argument within generator bodies.
1166        if matches!(coroutine_kind, CoroutineKind::Desugared(CoroutineDesugaring::Gen, _)) {
1167            body.arg_count = 1;
1168        }
1169
1170        // The original arguments to the function are no longer arguments, mark them as such.
1171        // Otherwise they'll conflict with our new arguments, which although they don't have
1172        // argument_index set, will get emitted as unnamed arguments.
1173        for var in &mut body.var_debug_info {
1174            var.argument_index = None;
1175        }
1176
1177        body.coroutine.as_mut().unwrap().yield_ty = None;
1178        body.coroutine.as_mut().unwrap().resume_ty = None;
1179        body.coroutine.as_mut().unwrap().coroutine_layout = Some(layout);
1180
1181        // Insert `drop(coroutine_struct)` which is used to drop upvars for coroutines in
1182        // the unresumed state.
1183        // This is expanded to a drop ladder in `elaborate_coroutine_drops`.
1184        let drop_clean = insert_clean_drop(tcx, body, has_async_drops);
1185
1186        if let Some(dumper) = MirDumper::new(tcx, "coroutine_pre-elab", body) {
1187            dumper.dump_mir(body);
1188        }
1189
1190        // Expand `drop(coroutine_struct)` to a drop ladder which destroys upvars.
1191        // If any upvars are moved out of, drop elaboration will handle upvar destruction.
1192        // However we need to also elaborate the code generated by `insert_clean_drop`.
1193        elaborate_coroutine_drops(tcx, body);
1194
1195        if let Some(dumper) = MirDumper::new(tcx, "coroutine_post-transform", body) {
1196            dumper.dump_mir(body);
1197        }
1198
1199        let can_unwind = can_unwind(tcx, body);
1200
1201        // Create a copy of our MIR and use it to create the drop shim for the coroutine
1202        if has_async_drops {
1203            // If coroutine has async drops, generating async drop shim
1204            let drop_shim =
1205                create_coroutine_drop_shim_async(tcx, &transform, body, drop_clean, can_unwind);
1206            body.coroutine.as_mut().unwrap().coroutine_drop_async = Some(drop_shim);
1207        } else {
1208            // If coroutine has no async drops, generating sync drop shim
1209            let drop_shim =
1210                create_coroutine_drop_shim(tcx, &transform, coroutine_ty, body, drop_clean);
1211            body.coroutine.as_mut().unwrap().coroutine_drop = Some(drop_shim);
1212
1213            // For coroutine with sync drop, generating async proxy for `future_drop_poll` call
1214            let proxy_shim = create_coroutine_drop_shim_proxy_async(tcx, body, coroutine_kind);
1215            body.coroutine.as_mut().unwrap().coroutine_drop_proxy_async = Some(proxy_shim);
1216        }
1217
1218        // Create the Coroutine::resume / Future::poll function
1219        create_coroutine_resume_function(tcx, transform, body, can_return, can_unwind);
1220    }
1221
1222    fn is_required(&self) -> bool {
1223        true
1224    }
1225}
1226
1227/// Looks for any assignments between locals (e.g., `_4 = _5`) that will both be converted to fields
1228/// in the coroutine state machine but whose storage is not marked as conflicting
1229///
1230/// Validation needs to happen immediately *before* `TransformVisitor` is invoked, not after.
1231///
1232/// This condition would arise when the assignment is the last use of `_5` but the initial
1233/// definition of `_4` if we weren't extra careful to mark all locals used inside a statement as
1234/// conflicting. Non-conflicting coroutine saved locals may be stored at the same location within
1235/// the coroutine state machine, which would result in ill-formed MIR: the left-hand and right-hand
1236/// sides of an assignment may not alias. This caused a miscompilation in [#73137].
1237///
1238/// [#73137]: https://github.com/rust-lang/rust/issues/73137
1239struct EnsureCoroutineFieldAssignmentsNeverAlias<'a> {
1240    saved_locals: &'a CoroutineSavedLocals,
1241    storage_conflicts: &'a BitMatrix<CoroutineSavedLocal, CoroutineSavedLocal>,
1242    assigned_local: Option<CoroutineSavedLocal>,
1243}
1244
1245impl EnsureCoroutineFieldAssignmentsNeverAlias<'_> {
1246    fn saved_local_for_direct_place(&self, place: Place<'_>) -> Option<CoroutineSavedLocal> {
1247        if place.is_indirect() {
1248            return None;
1249        }
1250
1251        self.saved_locals.get(place.local)
1252    }
1253
1254    fn check_assigned_place(&mut self, place: Place<'_>, f: impl FnOnce(&mut Self)) {
1255        if let Some(assigned_local) = self.saved_local_for_direct_place(place) {
1256            assert!(self.assigned_local.is_none(), "`check_assigned_place` must not recurse");
1257
1258            self.assigned_local = Some(assigned_local);
1259            f(self);
1260            self.assigned_local = None;
1261        }
1262    }
1263}
1264
1265impl<'tcx> Visitor<'tcx> for EnsureCoroutineFieldAssignmentsNeverAlias<'_> {
1266    fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
1267        let Some(lhs) = self.assigned_local else {
1268            // This visitor only invokes `visit_place` for the right-hand side of an assignment
1269            // and only after setting `self.assigned_local`. However, the default impl of
1270            // `Visitor::super_body` may call `visit_place` with a `NonUseContext` for places
1271            // with debuginfo. Ignore them here.
1272            assert!(!context.is_use());
1273            return;
1274        };
1275
1276        let Some(rhs) = self.saved_local_for_direct_place(*place) else { return };
1277
1278        if !self.storage_conflicts.contains(lhs, rhs) {
1279            bug!(
1280                "Assignment between coroutine saved locals whose storage is not \
1281                    marked as conflicting: {:?}: {:?} = {:?}",
1282                location,
1283                lhs,
1284                rhs,
1285            );
1286        }
1287    }
1288
1289    fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
1290        match &statement.kind {
1291            StatementKind::Assign((lhs, rhs)) => {
1292                self.check_assigned_place(*lhs, |this| this.visit_rvalue(rhs, location));
1293            }
1294
1295            StatementKind::FakeRead(..)
1296            | StatementKind::SetDiscriminant { .. }
1297            | StatementKind::StorageLive(_)
1298            | StatementKind::StorageDead(_)
1299            | StatementKind::AscribeUserType(..)
1300            | StatementKind::PlaceMention(..)
1301            | StatementKind::Coverage(..)
1302            | StatementKind::Intrinsic(..)
1303            | StatementKind::ConstEvalCounter
1304            | StatementKind::BackwardIncompatibleDropHint { .. }
1305            | StatementKind::Nop => {}
1306        }
1307    }
1308
1309    fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
1310        // Checking for aliasing in terminators is probably overkill, but until we have actual
1311        // semantics, we should be conservative here.
1312        match &terminator.kind {
1313            TerminatorKind::Call {
1314                func,
1315                args,
1316                destination,
1317                target: Some(_),
1318                unwind: _,
1319                call_source: _,
1320                fn_span: _,
1321            } => {
1322                self.check_assigned_place(*destination, |this| {
1323                    this.visit_operand(func, location);
1324                    for arg in args {
1325                        this.visit_operand(&arg.node, location);
1326                    }
1327                });
1328            }
1329
1330            TerminatorKind::Yield { value, resume: _, resume_arg, drop: _ } => {
1331                self.check_assigned_place(*resume_arg, |this| this.visit_operand(value, location));
1332            }
1333
1334            // FIXME: Does `asm!` have any aliasing requirements?
1335            TerminatorKind::InlineAsm { .. } => {}
1336
1337            TerminatorKind::Call { .. }
1338            | TerminatorKind::Goto { .. }
1339            | TerminatorKind::SwitchInt { .. }
1340            | TerminatorKind::UnwindResume
1341            | TerminatorKind::UnwindTerminate(_)
1342            | TerminatorKind::Return
1343            | TerminatorKind::TailCall { .. }
1344            | TerminatorKind::Unreachable
1345            | TerminatorKind::Drop { .. }
1346            | TerminatorKind::Assert { .. }
1347            | TerminatorKind::CoroutineDrop
1348            | TerminatorKind::FalseEdge { .. }
1349            | TerminatorKind::FalseUnwind { .. } => {}
1350        }
1351    }
1352}