rustc_mir_transform/
coroutine.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;
55use std::ops;
56
57pub(super) use by_move_body::coroutine_by_move_body_def_id;
58use drop::{
59    cleanup_async_drops, create_coroutine_drop_shim, create_coroutine_drop_shim_async,
60    create_coroutine_drop_shim_proxy_async, elaborate_coroutine_drops, expand_async_drops,
61    has_expandable_async_drops, insert_clean_drop,
62};
63use itertools::izip;
64use rustc_abi::{FieldIdx, VariantIdx};
65use rustc_data_structures::fx::FxHashSet;
66use rustc_errors::pluralize;
67use rustc_hir::attrs::AttributeKind;
68use rustc_hir::lang_items::LangItem;
69use rustc_hir::{self as hir, CoroutineDesugaring, CoroutineKind, find_attr};
70use rustc_index::bit_set::{BitMatrix, DenseBitSet, GrowableBitSet};
71use rustc_index::{Idx, IndexVec, indexvec};
72use rustc_middle::mir::visit::{MutVisitor, MutatingUseContext, PlaceContext, Visitor};
73use rustc_middle::mir::*;
74use rustc_middle::ty::util::Discr;
75use rustc_middle::ty::{
76    self, CoroutineArgs, CoroutineArgsExt, GenericArgsRef, InstanceKind, Ty, TyCtxt, TypingMode,
77};
78use rustc_middle::{bug, span_bug};
79use rustc_mir_dataflow::impls::{
80    MaybeBorrowedLocals, MaybeLiveLocals, MaybeRequiresStorage, MaybeStorageLive,
81    always_storage_live_locals,
82};
83use rustc_mir_dataflow::{
84    Analysis, Results, ResultsCursor, ResultsVisitor, visit_reachable_results,
85};
86use rustc_span::def_id::{DefId, LocalDefId};
87use rustc_span::source_map::dummy_spanned;
88use rustc_span::{DUMMY_SP, Span};
89use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
90use rustc_trait_selection::infer::TyCtxtInferExt as _;
91use rustc_trait_selection::traits::{ObligationCause, ObligationCauseCode, ObligationCtxt};
92use tracing::{debug, instrument, trace};
93
94use crate::deref_separator::deref_finder;
95use crate::{abort_unwinding_calls, errors, pass_manager as pm, simplify};
96
97pub(super) struct StateTransform;
98
99struct RenameLocalVisitor<'tcx> {
100    from: Local,
101    to: Local,
102    tcx: TyCtxt<'tcx>,
103}
104
105impl<'tcx> MutVisitor<'tcx> for RenameLocalVisitor<'tcx> {
106    fn tcx(&self) -> TyCtxt<'tcx> {
107        self.tcx
108    }
109
110    fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
111        if *local == self.from {
112            *local = self.to;
113        } else if *local == self.to {
114            *local = self.from;
115        }
116    }
117
118    fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, location: Location) {
119        match terminator.kind {
120            TerminatorKind::Return => {
121                // Do not replace the implicit `_0` access here, as that's not possible. The
122                // transform already handles `return` correctly.
123            }
124            _ => self.super_terminator(terminator, location),
125        }
126    }
127}
128
129struct SelfArgVisitor<'tcx> {
130    tcx: TyCtxt<'tcx>,
131    new_base: Place<'tcx>,
132}
133
134impl<'tcx> SelfArgVisitor<'tcx> {
135    fn new(tcx: TyCtxt<'tcx>, new_base: Place<'tcx>) -> Self {
136        Self { tcx, new_base }
137    }
138}
139
140impl<'tcx> MutVisitor<'tcx> for SelfArgVisitor<'tcx> {
141    fn tcx(&self) -> TyCtxt<'tcx> {
142        self.tcx
143    }
144
145    fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
146        assert_ne!(*local, SELF_ARG);
147    }
148
149    fn visit_place(&mut self, place: &mut Place<'tcx>, _: PlaceContext, _: Location) {
150        if place.local == SELF_ARG {
151            replace_base(place, self.new_base, self.tcx);
152        }
153
154        for elem in place.projection.iter() {
155            if let PlaceElem::Index(local) = elem {
156                assert_ne!(local, SELF_ARG);
157            }
158        }
159    }
160}
161
162#[tracing::instrument(level = "trace", skip(tcx))]
163fn replace_base<'tcx>(place: &mut Place<'tcx>, new_base: Place<'tcx>, tcx: TyCtxt<'tcx>) {
164    place.local = new_base.local;
165
166    let mut new_projection = new_base.projection.to_vec();
167    new_projection.append(&mut place.projection.to_vec());
168
169    place.projection = tcx.mk_place_elems(&new_projection);
170    tracing::trace!(?place);
171}
172
173const SELF_ARG: Local = Local::from_u32(1);
174const CTX_ARG: Local = Local::from_u32(2);
175
176/// A `yield` point in the coroutine.
177struct SuspensionPoint<'tcx> {
178    /// State discriminant used when suspending or resuming at this point.
179    state: usize,
180    /// The block to jump to after resumption.
181    resume: BasicBlock,
182    /// Where to move the resume argument after resumption.
183    resume_arg: Place<'tcx>,
184    /// Which block to jump to if the coroutine is dropped in this state.
185    drop: Option<BasicBlock>,
186    /// Set of locals that have live storage while at this suspension point.
187    storage_liveness: GrowableBitSet<Local>,
188}
189
190struct TransformVisitor<'tcx> {
191    tcx: TyCtxt<'tcx>,
192    coroutine_kind: hir::CoroutineKind,
193
194    // The type of the discriminant in the coroutine struct
195    discr_ty: Ty<'tcx>,
196
197    // Mapping from Local to (type of local, coroutine struct index)
198    remap: IndexVec<Local, Option<(Ty<'tcx>, VariantIdx, FieldIdx)>>,
199
200    // A map from a suspension point in a block to the locals which have live storage at that point
201    storage_liveness: IndexVec<BasicBlock, Option<DenseBitSet<Local>>>,
202
203    // A list of suspension points, generated during the transform
204    suspension_points: Vec<SuspensionPoint<'tcx>>,
205
206    // The set of locals that have no `StorageLive`/`StorageDead` annotations.
207    always_live_locals: DenseBitSet<Local>,
208
209    // New local we just create to hold the `CoroutineState` value.
210    new_ret_local: Local,
211
212    old_yield_ty: Ty<'tcx>,
213
214    old_ret_ty: Ty<'tcx>,
215}
216
217impl<'tcx> TransformVisitor<'tcx> {
218    fn insert_none_ret_block(&self, body: &mut Body<'tcx>) -> BasicBlock {
219        let block = body.basic_blocks.next_index();
220        let source_info = SourceInfo::outermost(body.span);
221
222        let none_value = match self.coroutine_kind {
223            CoroutineKind::Desugared(CoroutineDesugaring::Async, _) => {
224                span_bug!(body.span, "`Future`s are not fused inherently")
225            }
226            CoroutineKind::Coroutine(_) => span_bug!(body.span, "`Coroutine`s cannot be fused"),
227            // `gen` continues return `None`
228            CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
229                let option_def_id = self.tcx.require_lang_item(LangItem::Option, body.span);
230                make_aggregate_adt(
231                    option_def_id,
232                    VariantIdx::ZERO,
233                    self.tcx.mk_args(&[self.old_yield_ty.into()]),
234                    IndexVec::new(),
235                )
236            }
237            // `async gen` continues to return `Poll::Ready(None)`
238            CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => {
239                let ty::Adt(_poll_adt, args) = *self.old_yield_ty.kind() else { bug!() };
240                let ty::Adt(_option_adt, args) = *args.type_at(0).kind() else { bug!() };
241                let yield_ty = args.type_at(0);
242                Rvalue::Use(Operand::Constant(Box::new(ConstOperand {
243                    span: source_info.span,
244                    const_: Const::Unevaluated(
245                        UnevaluatedConst::new(
246                            self.tcx.require_lang_item(LangItem::AsyncGenFinished, body.span),
247                            self.tcx.mk_args(&[yield_ty.into()]),
248                        ),
249                        self.old_yield_ty,
250                    ),
251                    user_ty: None,
252                })))
253            }
254        };
255
256        let statements = vec![Statement::new(
257            source_info,
258            StatementKind::Assign(Box::new((Place::return_place(), none_value))),
259        )];
260
261        body.basic_blocks_mut().push(BasicBlockData::new_stmts(
262            statements,
263            Some(Terminator { source_info, kind: TerminatorKind::Return }),
264            false,
265        ));
266
267        block
268    }
269
270    // Make a `CoroutineState` or `Poll` variant assignment.
271    //
272    // `core::ops::CoroutineState` only has single element tuple variants,
273    // so we can just write to the downcasted first field and then set the
274    // discriminant to the appropriate variant.
275    #[tracing::instrument(level = "trace", skip(self, statements))]
276    fn make_state(
277        &self,
278        val: Operand<'tcx>,
279        source_info: SourceInfo,
280        is_return: bool,
281        statements: &mut Vec<Statement<'tcx>>,
282    ) {
283        const ZERO: VariantIdx = VariantIdx::ZERO;
284        const ONE: VariantIdx = VariantIdx::from_usize(1);
285        let rvalue = match self.coroutine_kind {
286            CoroutineKind::Desugared(CoroutineDesugaring::Async, _) => {
287                let poll_def_id = self.tcx.require_lang_item(LangItem::Poll, source_info.span);
288                let args = self.tcx.mk_args(&[self.old_ret_ty.into()]);
289                let (variant_idx, operands) = if is_return {
290                    (ZERO, indexvec![val]) // Poll::Ready(val)
291                } else {
292                    (ONE, IndexVec::new()) // Poll::Pending
293                };
294                make_aggregate_adt(poll_def_id, variant_idx, args, operands)
295            }
296            CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
297                let option_def_id = self.tcx.require_lang_item(LangItem::Option, source_info.span);
298                let args = self.tcx.mk_args(&[self.old_yield_ty.into()]);
299                let (variant_idx, operands) = if is_return {
300                    (ZERO, IndexVec::new()) // None
301                } else {
302                    (ONE, indexvec![val]) // Some(val)
303                };
304                make_aggregate_adt(option_def_id, variant_idx, args, operands)
305            }
306            CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => {
307                if is_return {
308                    let ty::Adt(_poll_adt, args) = *self.old_yield_ty.kind() else { bug!() };
309                    let ty::Adt(_option_adt, args) = *args.type_at(0).kind() else { bug!() };
310                    let yield_ty = args.type_at(0);
311                    Rvalue::Use(Operand::Constant(Box::new(ConstOperand {
312                        span: source_info.span,
313                        const_: Const::Unevaluated(
314                            UnevaluatedConst::new(
315                                self.tcx.require_lang_item(
316                                    LangItem::AsyncGenFinished,
317                                    source_info.span,
318                                ),
319                                self.tcx.mk_args(&[yield_ty.into()]),
320                            ),
321                            self.old_yield_ty,
322                        ),
323                        user_ty: None,
324                    })))
325                } else {
326                    Rvalue::Use(val)
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    }
420
421    #[tracing::instrument(level = "trace", skip(self, stmt), ret)]
422    fn visit_statement(&mut self, stmt: &mut Statement<'tcx>, location: Location) {
423        // Remove StorageLive and StorageDead statements for remapped locals
424        if let StatementKind::StorageLive(l) | StatementKind::StorageDead(l) = stmt.kind
425            && self.remap.contains(l)
426        {
427            stmt.make_nop(true);
428        }
429        self.super_statement(stmt, location);
430    }
431
432    #[tracing::instrument(level = "trace", skip(self, term), ret)]
433    fn visit_terminator(&mut self, term: &mut Terminator<'tcx>, location: Location) {
434        if let TerminatorKind::Return = term.kind {
435            // `visit_basic_block_data` introduces `Return` terminators which read `RETURN_PLACE`.
436            // But this `RETURN_PLACE` is already remapped, so we should not touch it again.
437            return;
438        }
439        self.super_terminator(term, location);
440    }
441
442    #[tracing::instrument(level = "trace", skip(self, data), ret)]
443    fn visit_basic_block_data(&mut self, block: BasicBlock, data: &mut BasicBlockData<'tcx>) {
444        match data.terminator().kind {
445            TerminatorKind::Return => {
446                let source_info = data.terminator().source_info;
447                // We must assign the value first in case it gets declared dead below
448                self.make_state(
449                    Operand::Move(Place::return_place()),
450                    source_info,
451                    true,
452                    &mut data.statements,
453                );
454                // Return state.
455                let state = VariantIdx::new(CoroutineArgs::RETURNED);
456                data.statements.push(self.set_discr(state, source_info));
457                data.terminator_mut().kind = TerminatorKind::Return;
458            }
459            TerminatorKind::Yield { ref value, resume, mut resume_arg, drop } => {
460                let source_info = data.terminator().source_info;
461                // We must assign the value first in case it gets declared dead below
462                self.make_state(value.clone(), source_info, false, &mut data.statements);
463                // Yield state.
464                let state = CoroutineArgs::RESERVED_VARIANTS + self.suspension_points.len();
465
466                // The resume arg target location might itself be remapped if its base local is
467                // live across a yield.
468                if let Some(&Some((ty, variant, idx))) = self.remap.get(resume_arg.local) {
469                    replace_base(&mut resume_arg, self.make_field(variant, idx, ty), self.tcx);
470                }
471
472                let storage_liveness: GrowableBitSet<Local> =
473                    self.storage_liveness[block].clone().unwrap().into();
474
475                for i in 0..self.always_live_locals.domain_size() {
476                    let l = Local::new(i);
477                    let needs_storage_dead = storage_liveness.contains(l)
478                        && !self.remap.contains(l)
479                        && !self.always_live_locals.contains(l);
480                    if needs_storage_dead {
481                        data.statements
482                            .push(Statement::new(source_info, StatementKind::StorageDead(l)));
483                    }
484                }
485
486                self.suspension_points.push(SuspensionPoint {
487                    state,
488                    resume,
489                    resume_arg,
490                    drop,
491                    storage_liveness,
492                });
493
494                let state = VariantIdx::new(state);
495                data.statements.push(self.set_discr(state, source_info));
496                data.terminator_mut().kind = TerminatorKind::Return;
497            }
498            _ => {}
499        }
500
501        self.super_basic_block_data(block, data);
502    }
503}
504
505fn make_aggregate_adt<'tcx>(
506    def_id: DefId,
507    variant_idx: VariantIdx,
508    args: GenericArgsRef<'tcx>,
509    operands: IndexVec<FieldIdx, Operand<'tcx>>,
510) -> Rvalue<'tcx> {
511    Rvalue::Aggregate(Box::new(AggregateKind::Adt(def_id, variant_idx, args, None, None)), operands)
512}
513
514#[tracing::instrument(level = "trace", skip(tcx, body))]
515fn make_coroutine_state_argument_indirect<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
516    let coroutine_ty = body.local_decls[SELF_ARG].ty;
517
518    let ref_coroutine_ty = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, coroutine_ty);
519
520    // Replace the by value coroutine argument
521    body.local_decls[SELF_ARG].ty = ref_coroutine_ty;
522
523    // Add a deref to accesses of the coroutine state
524    SelfArgVisitor::new(tcx, tcx.mk_place_deref(SELF_ARG.into())).visit_body(body);
525}
526
527#[tracing::instrument(level = "trace", skip(tcx, body))]
528fn make_coroutine_state_argument_pinned<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
529    let coroutine_ty = body.local_decls[SELF_ARG].ty;
530
531    let ref_coroutine_ty = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, coroutine_ty);
532
533    let pin_did = tcx.require_lang_item(LangItem::Pin, body.span);
534    let pin_adt_ref = tcx.adt_def(pin_did);
535    let args = tcx.mk_args(&[ref_coroutine_ty.into()]);
536    let pin_ref_coroutine_ty = Ty::new_adt(tcx, pin_adt_ref, args);
537
538    // Replace the by ref coroutine argument
539    body.local_decls[SELF_ARG].ty = pin_ref_coroutine_ty;
540
541    let unpinned_local = body.local_decls.push(LocalDecl::new(ref_coroutine_ty, body.span));
542
543    // Add the Pin field access to accesses of the coroutine state
544    SelfArgVisitor::new(tcx, tcx.mk_place_deref(unpinned_local.into())).visit_body(body);
545
546    let source_info = SourceInfo::outermost(body.span);
547    let pin_field = tcx.mk_place_field(SELF_ARG.into(), FieldIdx::ZERO, ref_coroutine_ty);
548
549    let statements = &mut body.basic_blocks.as_mut_preserves_cfg()[START_BLOCK].statements;
550    // Miri requires retags to be the very first thing in the body.
551    // We insert this assignment just after.
552    let insert_point = statements
553        .iter()
554        .position(|stmt| !matches!(stmt.kind, StatementKind::Retag(..)))
555        .unwrap_or(statements.len());
556    statements.insert(
557        insert_point,
558        Statement::new(
559            source_info,
560            StatementKind::Assign(Box::new((
561                unpinned_local.into(),
562                Rvalue::Use(Operand::Copy(pin_field)),
563            ))),
564        ),
565    );
566}
567
568/// Transforms the `body` of the coroutine applying the following transforms:
569///
570/// - Eliminates all the `get_context` calls that async lowering created.
571/// - Replace all `Local` `ResumeTy` types with `&mut Context<'_>` (`context_mut_ref`).
572///
573/// The `Local`s that have their types replaced are:
574/// - The `resume` argument itself.
575/// - The argument to `get_context`.
576/// - The yielded value of a `yield`.
577///
578/// The `ResumeTy` hides a `&mut Context<'_>` behind an unsafe raw pointer, and the
579/// `get_context` function is being used to convert that back to a `&mut Context<'_>`.
580///
581/// Ideally the async lowering would not use the `ResumeTy`/`get_context` indirection,
582/// but rather directly use `&mut Context<'_>`, however that would currently
583/// lead to higher-kinded lifetime errors.
584/// See <https://github.com/rust-lang/rust/issues/105501>.
585///
586/// The async lowering step and the type / lifetime inference / checking are
587/// still using the `ResumeTy` indirection for the time being, and that indirection
588/// is removed here. After this transform, the coroutine body only knows about `&mut Context<'_>`.
589#[tracing::instrument(level = "trace", skip(tcx, body), ret)]
590fn transform_async_context<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) -> Ty<'tcx> {
591    let context_mut_ref = Ty::new_task_context(tcx);
592
593    // replace the type of the `resume` argument
594    replace_resume_ty_local(tcx, body, CTX_ARG, context_mut_ref);
595
596    let get_context_def_id = tcx.require_lang_item(LangItem::GetContext, body.span);
597
598    for bb in body.basic_blocks.indices() {
599        let bb_data = &body[bb];
600        if bb_data.is_cleanup {
601            continue;
602        }
603
604        match &bb_data.terminator().kind {
605            TerminatorKind::Call { func, .. } => {
606                let func_ty = func.ty(body, tcx);
607                if let ty::FnDef(def_id, _) = *func_ty.kind()
608                    && def_id == get_context_def_id
609                {
610                    let local = eliminate_get_context_call(&mut body[bb]);
611                    replace_resume_ty_local(tcx, body, local, context_mut_ref);
612                }
613            }
614            TerminatorKind::Yield { resume_arg, .. } => {
615                replace_resume_ty_local(tcx, body, resume_arg.local, context_mut_ref);
616            }
617            _ => {}
618        }
619    }
620    context_mut_ref
621}
622
623fn eliminate_get_context_call<'tcx>(bb_data: &mut BasicBlockData<'tcx>) -> Local {
624    let terminator = bb_data.terminator.take().unwrap();
625    let TerminatorKind::Call { args, destination, target, .. } = terminator.kind else {
626        bug!();
627    };
628    let [arg] = *Box::try_from(args).unwrap();
629    let local = arg.node.place().unwrap().local;
630
631    let arg = Rvalue::Use(arg.node);
632    let assign =
633        Statement::new(terminator.source_info, StatementKind::Assign(Box::new((destination, arg))));
634    bb_data.statements.push(assign);
635    bb_data.terminator = Some(Terminator {
636        source_info: terminator.source_info,
637        kind: TerminatorKind::Goto { target: target.unwrap() },
638    });
639    local
640}
641
642#[cfg_attr(not(debug_assertions), allow(unused))]
643#[tracing::instrument(level = "trace", skip(tcx, body), ret)]
644fn replace_resume_ty_local<'tcx>(
645    tcx: TyCtxt<'tcx>,
646    body: &mut Body<'tcx>,
647    local: Local,
648    context_mut_ref: Ty<'tcx>,
649) {
650    let local_ty = std::mem::replace(&mut body.local_decls[local].ty, context_mut_ref);
651    // We have to replace the `ResumeTy` that is used for type and borrow checking
652    // with `&mut Context<'_>` in MIR.
653    #[cfg(debug_assertions)]
654    {
655        if let ty::Adt(resume_ty_adt, _) = local_ty.kind() {
656            let expected_adt = tcx.adt_def(tcx.require_lang_item(LangItem::ResumeTy, body.span));
657            assert_eq!(*resume_ty_adt, expected_adt);
658        } else {
659            panic!("expected `ResumeTy`, found `{:?}`", local_ty);
660        };
661    }
662}
663
664/// Transforms the `body` of the coroutine applying the following transform:
665///
666/// - Remove the `resume` argument.
667///
668/// Ideally the async lowering would not add the `resume` argument.
669///
670/// The async lowering step and the type / lifetime inference / checking are
671/// still using the `resume` argument for the time being. After this transform,
672/// the coroutine body doesn't have the `resume` argument.
673fn transform_gen_context<'tcx>(body: &mut Body<'tcx>) {
674    // This leaves the local representing the `resume` argument in place,
675    // but turns it into a regular local variable. This is cheaper than
676    // adjusting all local references in the body after removing it.
677    body.arg_count = 1;
678}
679
680struct LivenessInfo {
681    /// Which locals are live across any suspension point.
682    saved_locals: CoroutineSavedLocals,
683
684    /// The set of saved locals live at each suspension point.
685    live_locals_at_suspension_points: Vec<DenseBitSet<CoroutineSavedLocal>>,
686
687    /// Parallel vec to the above with SourceInfo for each yield terminator.
688    source_info_at_suspension_points: Vec<SourceInfo>,
689
690    /// For every saved local, the set of other saved locals that are
691    /// storage-live at the same time as this local. We cannot overlap locals in
692    /// the layout which have conflicting storage.
693    storage_conflicts: BitMatrix<CoroutineSavedLocal, CoroutineSavedLocal>,
694
695    /// For every suspending block, the locals which are storage-live across
696    /// that suspension point.
697    storage_liveness: IndexVec<BasicBlock, Option<DenseBitSet<Local>>>,
698}
699
700/// Computes which locals have to be stored in the state-machine for the
701/// given coroutine.
702///
703/// The basic idea is as follows:
704/// - a local is live until we encounter a `StorageDead` statement. In
705///   case none exist, the local is considered to be always live.
706/// - a local has to be stored if it is either directly used after the
707///   the suspend point, or if it is live and has been previously borrowed.
708#[tracing::instrument(level = "trace", skip(tcx, body))]
709fn locals_live_across_suspend_points<'tcx>(
710    tcx: TyCtxt<'tcx>,
711    body: &Body<'tcx>,
712    always_live_locals: &DenseBitSet<Local>,
713    movable: bool,
714) -> LivenessInfo {
715    // Calculate when MIR locals have live storage. This gives us an upper bound of their
716    // lifetimes.
717    let mut storage_live = MaybeStorageLive::new(std::borrow::Cow::Borrowed(always_live_locals))
718        .iterate_to_fixpoint(tcx, body, None)
719        .into_results_cursor(body);
720
721    // Calculate the MIR locals that have been previously borrowed (even if they are still active).
722    let borrowed_locals = MaybeBorrowedLocals.iterate_to_fixpoint(tcx, body, Some("coroutine"));
723    let borrowed_locals_cursor1 = ResultsCursor::new_borrowing(body, &borrowed_locals);
724    let mut borrowed_locals_cursor2 = ResultsCursor::new_borrowing(body, &borrowed_locals);
725
726    // Calculate the MIR locals that we need to keep storage around for.
727    let requires_storage =
728        MaybeRequiresStorage::new(borrowed_locals_cursor1).iterate_to_fixpoint(tcx, body, None);
729    let mut requires_storage_cursor = ResultsCursor::new_borrowing(body, &requires_storage);
730
731    // Calculate the liveness of MIR locals ignoring borrows.
732    let mut liveness =
733        MaybeLiveLocals.iterate_to_fixpoint(tcx, body, Some("coroutine")).into_results_cursor(body);
734
735    let mut storage_liveness_map = IndexVec::from_elem(None, &body.basic_blocks);
736    let mut live_locals_at_suspension_points = Vec::new();
737    let mut source_info_at_suspension_points = Vec::new();
738    let mut live_locals_at_any_suspension_point = DenseBitSet::new_empty(body.local_decls.len());
739
740    for (block, data) in body.basic_blocks.iter_enumerated() {
741        let TerminatorKind::Yield { .. } = data.terminator().kind else { continue };
742
743        let loc = Location { block, statement_index: data.statements.len() };
744
745        liveness.seek_to_block_end(block);
746        let mut live_locals = liveness.get().clone();
747
748        if !movable {
749            // The `liveness` variable contains the liveness of MIR locals ignoring borrows.
750            // This is correct for movable coroutines since borrows cannot live across
751            // suspension points. However for immovable coroutines we need to account for
752            // borrows, so we conservatively assume that all borrowed locals are live until
753            // we find a StorageDead statement referencing the locals.
754            // To do this we just union our `liveness` result with `borrowed_locals`, which
755            // contains all the locals which has been borrowed before this suspension point.
756            // If a borrow is converted to a raw reference, we must also assume that it lives
757            // forever. Note that the final liveness is still bounded by the storage liveness
758            // of the local, which happens using the `intersect` operation below.
759            borrowed_locals_cursor2.seek_before_primary_effect(loc);
760            live_locals.union(borrowed_locals_cursor2.get());
761        }
762
763        // Store the storage liveness for later use so we can restore the state
764        // after a suspension point
765        storage_live.seek_before_primary_effect(loc);
766        storage_liveness_map[block] = Some(storage_live.get().clone());
767
768        // Locals live are live at this point only if they are used across
769        // suspension points (the `liveness` variable)
770        // and their storage is required (the `storage_required` variable)
771        requires_storage_cursor.seek_before_primary_effect(loc);
772        live_locals.intersect(requires_storage_cursor.get());
773
774        // The coroutine argument is ignored.
775        live_locals.remove(SELF_ARG);
776
777        debug!(?loc, ?live_locals);
778
779        // Add the locals live at this suspension point to the set of locals which live across
780        // any suspension points
781        live_locals_at_any_suspension_point.union(&live_locals);
782
783        live_locals_at_suspension_points.push(live_locals);
784        source_info_at_suspension_points.push(data.terminator().source_info);
785    }
786
787    debug!(?live_locals_at_any_suspension_point);
788    let saved_locals = CoroutineSavedLocals(live_locals_at_any_suspension_point);
789
790    // Renumber our liveness_map bitsets to include only the locals we are
791    // saving.
792    let live_locals_at_suspension_points = live_locals_at_suspension_points
793        .iter()
794        .map(|live_here| saved_locals.renumber_bitset(live_here))
795        .collect();
796
797    let storage_conflicts = compute_storage_conflicts(
798        body,
799        &saved_locals,
800        always_live_locals.clone(),
801        &requires_storage,
802    );
803
804    LivenessInfo {
805        saved_locals,
806        live_locals_at_suspension_points,
807        source_info_at_suspension_points,
808        storage_conflicts,
809        storage_liveness: storage_liveness_map,
810    }
811}
812
813/// The set of `Local`s that must be saved across yield points.
814///
815/// `CoroutineSavedLocal` is indexed in terms of the elements in this set;
816/// i.e. `CoroutineSavedLocal::new(1)` corresponds to the second local
817/// included in this set.
818struct CoroutineSavedLocals(DenseBitSet<Local>);
819
820impl CoroutineSavedLocals {
821    /// Returns an iterator over each `CoroutineSavedLocal` along with the `Local` it corresponds
822    /// to.
823    fn iter_enumerated(&self) -> impl '_ + Iterator<Item = (CoroutineSavedLocal, Local)> {
824        self.iter().enumerate().map(|(i, l)| (CoroutineSavedLocal::from(i), l))
825    }
826
827    /// Transforms a `DenseBitSet<Local>` that contains only locals saved across yield points to the
828    /// equivalent `DenseBitSet<CoroutineSavedLocal>`.
829    fn renumber_bitset(&self, input: &DenseBitSet<Local>) -> DenseBitSet<CoroutineSavedLocal> {
830        assert!(self.superset(input), "{:?} not a superset of {:?}", self.0, input);
831        let mut out = DenseBitSet::new_empty(self.count());
832        for (saved_local, local) in self.iter_enumerated() {
833            if input.contains(local) {
834                out.insert(saved_local);
835            }
836        }
837        out
838    }
839
840    fn get(&self, local: Local) -> Option<CoroutineSavedLocal> {
841        if !self.contains(local) {
842            return None;
843        }
844
845        let idx = self.iter().take_while(|&l| l < local).count();
846        Some(CoroutineSavedLocal::new(idx))
847    }
848}
849
850impl ops::Deref for CoroutineSavedLocals {
851    type Target = DenseBitSet<Local>;
852
853    fn deref(&self) -> &Self::Target {
854        &self.0
855    }
856}
857
858/// For every saved local, looks for which locals are StorageLive at the same
859/// time. Generates a bitset for every local of all the other locals that may be
860/// StorageLive simultaneously with that local. This is used in the layout
861/// computation; see `CoroutineLayout` for more.
862fn compute_storage_conflicts<'mir, 'tcx>(
863    body: &'mir Body<'tcx>,
864    saved_locals: &'mir CoroutineSavedLocals,
865    always_live_locals: DenseBitSet<Local>,
866    results: &Results<'tcx, MaybeRequiresStorage<'mir, 'tcx>>,
867) -> BitMatrix<CoroutineSavedLocal, CoroutineSavedLocal> {
868    assert_eq!(body.local_decls.len(), saved_locals.domain_size());
869
870    debug!("compute_storage_conflicts({:?})", body.span);
871    debug!("always_live = {:?}", always_live_locals);
872
873    // Locals that are always live or ones that need to be stored across
874    // suspension points are not eligible for overlap.
875    let mut ineligible_locals = always_live_locals;
876    ineligible_locals.intersect(&**saved_locals);
877
878    // Compute the storage conflicts for all eligible locals.
879    let mut visitor = StorageConflictVisitor {
880        body,
881        saved_locals,
882        local_conflicts: BitMatrix::from_row_n(&ineligible_locals, body.local_decls.len()),
883        eligible_storage_live: DenseBitSet::new_empty(body.local_decls.len()),
884    };
885
886    visit_reachable_results(body, results, &mut visitor);
887
888    let local_conflicts = visitor.local_conflicts;
889
890    // Compress the matrix using only stored locals (Local -> CoroutineSavedLocal).
891    //
892    // NOTE: Today we store a full conflict bitset for every local. Technically
893    // this is twice as many bits as we need, since the relation is symmetric.
894    // However, in practice these bitsets are not usually large. The layout code
895    // also needs to keep track of how many conflicts each local has, so it's
896    // simpler to keep it this way for now.
897    let mut storage_conflicts = BitMatrix::new(saved_locals.count(), saved_locals.count());
898    for (saved_local_a, local_a) in saved_locals.iter_enumerated() {
899        if ineligible_locals.contains(local_a) {
900            // Conflicts with everything.
901            storage_conflicts.insert_all_into_row(saved_local_a);
902        } else {
903            // Keep overlap information only for stored locals.
904            for (saved_local_b, local_b) in saved_locals.iter_enumerated() {
905                if local_conflicts.contains(local_a, local_b) {
906                    storage_conflicts.insert(saved_local_a, saved_local_b);
907                }
908            }
909        }
910    }
911    storage_conflicts
912}
913
914struct StorageConflictVisitor<'a, 'tcx> {
915    body: &'a Body<'tcx>,
916    saved_locals: &'a CoroutineSavedLocals,
917    // FIXME(tmandry): Consider using sparse bitsets here once we have good
918    // benchmarks for coroutines.
919    local_conflicts: BitMatrix<Local, Local>,
920    // We keep this bitset as a buffer to avoid reallocating memory.
921    eligible_storage_live: DenseBitSet<Local>,
922}
923
924impl<'a, 'tcx> ResultsVisitor<'tcx, MaybeRequiresStorage<'a, 'tcx>>
925    for StorageConflictVisitor<'a, 'tcx>
926{
927    fn visit_after_early_statement_effect(
928        &mut self,
929        _analysis: &MaybeRequiresStorage<'a, 'tcx>,
930        state: &DenseBitSet<Local>,
931        _statement: &Statement<'tcx>,
932        loc: Location,
933    ) {
934        self.apply_state(state, loc);
935    }
936
937    fn visit_after_early_terminator_effect(
938        &mut self,
939        _analysis: &MaybeRequiresStorage<'a, 'tcx>,
940        state: &DenseBitSet<Local>,
941        _terminator: &Terminator<'tcx>,
942        loc: Location,
943    ) {
944        self.apply_state(state, loc);
945    }
946}
947
948impl StorageConflictVisitor<'_, '_> {
949    fn apply_state(&mut self, state: &DenseBitSet<Local>, loc: Location) {
950        // Ignore unreachable blocks.
951        if let TerminatorKind::Unreachable = self.body.basic_blocks[loc.block].terminator().kind {
952            return;
953        }
954
955        self.eligible_storage_live.clone_from(state);
956        self.eligible_storage_live.intersect(&**self.saved_locals);
957
958        for local in self.eligible_storage_live.iter() {
959            self.local_conflicts.union_row_with(&self.eligible_storage_live, local);
960        }
961
962        if self.eligible_storage_live.count() > 1 {
963            trace!("at {:?}, eligible_storage_live={:?}", loc, self.eligible_storage_live);
964        }
965    }
966}
967
968#[tracing::instrument(level = "trace", skip(liveness, body))]
969fn compute_layout<'tcx>(
970    liveness: LivenessInfo,
971    body: &Body<'tcx>,
972) -> (
973    IndexVec<Local, Option<(Ty<'tcx>, VariantIdx, FieldIdx)>>,
974    CoroutineLayout<'tcx>,
975    IndexVec<BasicBlock, Option<DenseBitSet<Local>>>,
976) {
977    let LivenessInfo {
978        saved_locals,
979        live_locals_at_suspension_points,
980        source_info_at_suspension_points,
981        storage_conflicts,
982        storage_liveness,
983    } = liveness;
984
985    // Gather live local types and their indices.
986    let mut locals = IndexVec::<CoroutineSavedLocal, _>::with_capacity(saved_locals.domain_size());
987    let mut tys = IndexVec::<CoroutineSavedLocal, _>::with_capacity(saved_locals.domain_size());
988    for (saved_local, local) in saved_locals.iter_enumerated() {
989        debug!("coroutine saved local {:?} => {:?}", saved_local, local);
990
991        locals.push(local);
992        let decl = &body.local_decls[local];
993        debug!(?decl);
994
995        // Do not `unwrap_crate_local` here, as post-borrowck cleanup may have already cleared
996        // the information. This is alright, since `ignore_for_traits` is only relevant when
997        // this code runs on pre-cleanup MIR, and `ignore_for_traits = false` is the safer
998        // default.
999        let ignore_for_traits = match decl.local_info {
1000            // Do not include raw pointers created from accessing `static` items, as those could
1001            // well be re-created by another access to the same static.
1002            ClearCrossCrate::Set(box LocalInfo::StaticRef { is_thread_local, .. }) => {
1003                !is_thread_local
1004            }
1005            // Fake borrows are only read by fake reads, so do not have any reality in
1006            // post-analysis MIR.
1007            ClearCrossCrate::Set(box LocalInfo::FakeBorrow) => true,
1008            _ => false,
1009        };
1010        let decl =
1011            CoroutineSavedTy { ty: decl.ty, source_info: decl.source_info, ignore_for_traits };
1012        debug!(?decl);
1013
1014        tys.push(decl);
1015    }
1016
1017    // Leave empty variants for the UNRESUMED, RETURNED, and POISONED states.
1018    // In debuginfo, these will correspond to the beginning (UNRESUMED) or end
1019    // (RETURNED, POISONED) of the function.
1020    let body_span = body.source_scopes[OUTERMOST_SOURCE_SCOPE].span;
1021    let mut variant_source_info: IndexVec<VariantIdx, SourceInfo> = IndexVec::with_capacity(
1022        CoroutineArgs::RESERVED_VARIANTS + live_locals_at_suspension_points.len(),
1023    );
1024    variant_source_info.extend([
1025        SourceInfo::outermost(body_span.shrink_to_lo()),
1026        SourceInfo::outermost(body_span.shrink_to_hi()),
1027        SourceInfo::outermost(body_span.shrink_to_hi()),
1028    ]);
1029
1030    // Build the coroutine variant field list.
1031    // Create a map from local indices to coroutine struct indices.
1032    let mut variant_fields: IndexVec<VariantIdx, _> = IndexVec::from_elem_n(
1033        IndexVec::new(),
1034        CoroutineArgs::RESERVED_VARIANTS + live_locals_at_suspension_points.len(),
1035    );
1036    let mut remap = IndexVec::from_elem_n(None, saved_locals.domain_size());
1037    for (live_locals, &source_info_at_suspension_point, (variant_index, fields)) in izip!(
1038        &live_locals_at_suspension_points,
1039        &source_info_at_suspension_points,
1040        variant_fields.iter_enumerated_mut().skip(CoroutineArgs::RESERVED_VARIANTS)
1041    ) {
1042        *fields = live_locals.iter().collect();
1043        for (idx, &saved_local) in fields.iter_enumerated() {
1044            // Note that if a field is included in multiple variants, we will
1045            // just use the first one here. That's fine; fields do not move
1046            // around inside coroutines, so it doesn't matter which variant
1047            // index we access them by.
1048            remap[locals[saved_local]] = Some((tys[saved_local].ty, variant_index, idx));
1049        }
1050        variant_source_info.push(source_info_at_suspension_point);
1051    }
1052    debug!(?variant_fields);
1053    debug!(?storage_conflicts);
1054
1055    let mut field_names = IndexVec::from_elem(None, &tys);
1056    for var in &body.var_debug_info {
1057        let VarDebugInfoContents::Place(place) = &var.value else { continue };
1058        let Some(local) = place.as_local() else { continue };
1059        let Some(&Some((_, variant, field))) = remap.get(local) else {
1060            continue;
1061        };
1062
1063        let saved_local = variant_fields[variant][field];
1064        field_names.get_or_insert_with(saved_local, || var.name);
1065    }
1066
1067    let layout = CoroutineLayout {
1068        field_tys: tys,
1069        field_names,
1070        variant_fields,
1071        variant_source_info,
1072        storage_conflicts,
1073    };
1074    debug!(?remap);
1075    debug!(?layout);
1076    debug!(?storage_liveness);
1077
1078    (remap, layout, storage_liveness)
1079}
1080
1081/// Replaces the entry point of `body` with a block that switches on the coroutine discriminant and
1082/// dispatches to blocks according to `cases`.
1083///
1084/// After this function, the former entry point of the function will be bb1.
1085fn insert_switch<'tcx>(
1086    body: &mut Body<'tcx>,
1087    cases: Vec<(usize, BasicBlock)>,
1088    transform: &TransformVisitor<'tcx>,
1089    default_block: BasicBlock,
1090) {
1091    let (assign, discr) = transform.get_discr(body);
1092    let switch_targets =
1093        SwitchTargets::new(cases.iter().map(|(i, bb)| ((*i) as u128, *bb)), default_block);
1094    let switch = TerminatorKind::SwitchInt { discr: Operand::Move(discr), targets: switch_targets };
1095
1096    let source_info = SourceInfo::outermost(body.span);
1097    body.basic_blocks_mut().raw.insert(
1098        0,
1099        BasicBlockData::new_stmts(
1100            vec![assign],
1101            Some(Terminator { source_info, kind: switch }),
1102            false,
1103        ),
1104    );
1105
1106    for b in body.basic_blocks_mut().iter_mut() {
1107        b.terminator_mut().successors_mut(|target| *target += 1);
1108    }
1109}
1110
1111fn insert_term_block<'tcx>(body: &mut Body<'tcx>, kind: TerminatorKind<'tcx>) -> BasicBlock {
1112    let source_info = SourceInfo::outermost(body.span);
1113    body.basic_blocks_mut().push(BasicBlockData::new(Some(Terminator { source_info, kind }), false))
1114}
1115
1116fn return_poll_ready_assign<'tcx>(tcx: TyCtxt<'tcx>, source_info: SourceInfo) -> Statement<'tcx> {
1117    // Poll::Ready(())
1118    let poll_def_id = tcx.require_lang_item(LangItem::Poll, source_info.span);
1119    let args = tcx.mk_args(&[tcx.types.unit.into()]);
1120    let val = Operand::Constant(Box::new(ConstOperand {
1121        span: source_info.span,
1122        user_ty: None,
1123        const_: Const::zero_sized(tcx.types.unit),
1124    }));
1125    let ready_val = Rvalue::Aggregate(
1126        Box::new(AggregateKind::Adt(poll_def_id, VariantIdx::from_usize(0), args, None, None)),
1127        indexvec![val],
1128    );
1129    Statement::new(source_info, StatementKind::Assign(Box::new((Place::return_place(), ready_val))))
1130}
1131
1132fn insert_poll_ready_block<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) -> BasicBlock {
1133    let source_info = SourceInfo::outermost(body.span);
1134    body.basic_blocks_mut().push(BasicBlockData::new_stmts(
1135        [return_poll_ready_assign(tcx, source_info)].to_vec(),
1136        Some(Terminator { source_info, kind: TerminatorKind::Return }),
1137        false,
1138    ))
1139}
1140
1141fn insert_panic_block<'tcx>(
1142    tcx: TyCtxt<'tcx>,
1143    body: &mut Body<'tcx>,
1144    message: AssertMessage<'tcx>,
1145) -> BasicBlock {
1146    let assert_block = body.basic_blocks.next_index();
1147    let kind = TerminatorKind::Assert {
1148        cond: Operand::Constant(Box::new(ConstOperand {
1149            span: body.span,
1150            user_ty: None,
1151            const_: Const::from_bool(tcx, false),
1152        })),
1153        expected: true,
1154        msg: Box::new(message),
1155        target: assert_block,
1156        unwind: UnwindAction::Continue,
1157    };
1158
1159    insert_term_block(body, kind)
1160}
1161
1162fn can_return<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1163    // Returning from a function with an uninhabited return type is undefined behavior.
1164    if body.return_ty().is_privately_uninhabited(tcx, typing_env) {
1165        return false;
1166    }
1167
1168    // If there's a return terminator the function may return.
1169    body.basic_blocks.iter().any(|block| matches!(block.terminator().kind, TerminatorKind::Return))
1170    // Otherwise the function can't return.
1171}
1172
1173fn can_unwind<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>) -> bool {
1174    // Nothing can unwind when landing pads are off.
1175    if !tcx.sess.panic_strategy().unwinds() {
1176        return false;
1177    }
1178
1179    // Unwinds can only start at certain terminators.
1180    for block in body.basic_blocks.iter() {
1181        match block.terminator().kind {
1182            // These never unwind.
1183            TerminatorKind::Goto { .. }
1184            | TerminatorKind::SwitchInt { .. }
1185            | TerminatorKind::UnwindTerminate(_)
1186            | TerminatorKind::Return
1187            | TerminatorKind::Unreachable
1188            | TerminatorKind::CoroutineDrop
1189            | TerminatorKind::FalseEdge { .. }
1190            | TerminatorKind::FalseUnwind { .. } => {}
1191
1192            // Resume will *continue* unwinding, but if there's no other unwinding terminator it
1193            // will never be reached.
1194            TerminatorKind::UnwindResume => {}
1195
1196            TerminatorKind::Yield { .. } => {
1197                unreachable!("`can_unwind` called before coroutine transform")
1198            }
1199
1200            // These may unwind.
1201            TerminatorKind::Drop { .. }
1202            | TerminatorKind::Call { .. }
1203            | TerminatorKind::InlineAsm { .. }
1204            | TerminatorKind::Assert { .. } => return true,
1205
1206            TerminatorKind::TailCall { .. } => {
1207                unreachable!("tail calls can't be present in generators")
1208            }
1209        }
1210    }
1211
1212    // If we didn't find an unwinding terminator, the function cannot unwind.
1213    false
1214}
1215
1216// Poison the coroutine when it unwinds
1217fn generate_poison_block_and_redirect_unwinds_there<'tcx>(
1218    transform: &TransformVisitor<'tcx>,
1219    body: &mut Body<'tcx>,
1220) {
1221    let source_info = SourceInfo::outermost(body.span);
1222    let poison_block = body.basic_blocks_mut().push(BasicBlockData::new_stmts(
1223        vec![transform.set_discr(VariantIdx::new(CoroutineArgs::POISONED), source_info)],
1224        Some(Terminator { source_info, kind: TerminatorKind::UnwindResume }),
1225        true,
1226    ));
1227
1228    for (idx, block) in body.basic_blocks_mut().iter_enumerated_mut() {
1229        let source_info = block.terminator().source_info;
1230
1231        if let TerminatorKind::UnwindResume = block.terminator().kind {
1232            // An existing `Resume` terminator is redirected to jump to our dedicated
1233            // "poisoning block" above.
1234            if idx != poison_block {
1235                *block.terminator_mut() =
1236                    Terminator { source_info, kind: TerminatorKind::Goto { target: poison_block } };
1237            }
1238        } else if !block.is_cleanup
1239            // Any terminators that *can* unwind but don't have an unwind target set are also
1240            // pointed at our poisoning block (unless they're part of the cleanup path).
1241            && let Some(unwind @ UnwindAction::Continue) = block.terminator_mut().unwind_mut()
1242        {
1243            *unwind = UnwindAction::Cleanup(poison_block);
1244        }
1245    }
1246}
1247
1248#[tracing::instrument(level = "trace", skip(tcx, transform, body))]
1249fn create_coroutine_resume_function<'tcx>(
1250    tcx: TyCtxt<'tcx>,
1251    transform: TransformVisitor<'tcx>,
1252    body: &mut Body<'tcx>,
1253    can_return: bool,
1254    can_unwind: bool,
1255) {
1256    // Poison the coroutine when it unwinds
1257    if can_unwind {
1258        generate_poison_block_and_redirect_unwinds_there(&transform, body);
1259    }
1260
1261    let mut cases = create_cases(body, &transform, Operation::Resume);
1262
1263    use rustc_middle::mir::AssertKind::{ResumedAfterPanic, ResumedAfterReturn};
1264
1265    // Jump to the entry point on the unresumed
1266    cases.insert(0, (CoroutineArgs::UNRESUMED, START_BLOCK));
1267
1268    // Panic when resumed on the returned or poisoned state
1269    if can_unwind {
1270        cases.insert(
1271            1,
1272            (
1273                CoroutineArgs::POISONED,
1274                insert_panic_block(tcx, body, ResumedAfterPanic(transform.coroutine_kind)),
1275            ),
1276        );
1277    }
1278
1279    if can_return {
1280        let block = match transform.coroutine_kind {
1281            CoroutineKind::Desugared(CoroutineDesugaring::Async, _)
1282            | CoroutineKind::Coroutine(_) => {
1283                // For `async_drop_in_place<T>::{closure}` we just keep return Poll::Ready,
1284                // because async drop of such coroutine keeps polling original coroutine
1285                if tcx.is_async_drop_in_place_coroutine(body.source.def_id()) {
1286                    insert_poll_ready_block(tcx, body)
1287                } else {
1288                    insert_panic_block(tcx, body, ResumedAfterReturn(transform.coroutine_kind))
1289                }
1290            }
1291            CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _)
1292            | CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
1293                transform.insert_none_ret_block(body)
1294            }
1295        };
1296        cases.insert(1, (CoroutineArgs::RETURNED, block));
1297    }
1298
1299    let default_block = insert_term_block(body, TerminatorKind::Unreachable);
1300    insert_switch(body, cases, &transform, default_block);
1301
1302    match transform.coroutine_kind {
1303        CoroutineKind::Coroutine(_)
1304        | CoroutineKind::Desugared(CoroutineDesugaring::Async | CoroutineDesugaring::AsyncGen, _) =>
1305        {
1306            make_coroutine_state_argument_pinned(tcx, body);
1307        }
1308        // Iterator::next doesn't accept a pinned argument,
1309        // unlike for all other coroutine kinds.
1310        CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
1311            make_coroutine_state_argument_indirect(tcx, body);
1312        }
1313    }
1314
1315    // Make sure we remove dead blocks to remove
1316    // unrelated code from the drop part of the function
1317    simplify::remove_dead_blocks(body);
1318
1319    pm::run_passes_no_validate(tcx, body, &[&abort_unwinding_calls::AbortUnwindingCalls], None);
1320
1321    if let Some(dumper) = MirDumper::new(tcx, "coroutine_resume", body) {
1322        dumper.dump_mir(body);
1323    }
1324}
1325
1326/// An operation that can be performed on a coroutine.
1327#[derive(PartialEq, Copy, Clone, Debug)]
1328enum Operation {
1329    Resume,
1330    Drop,
1331}
1332
1333impl Operation {
1334    fn target_block(self, point: &SuspensionPoint<'_>) -> Option<BasicBlock> {
1335        match self {
1336            Operation::Resume => Some(point.resume),
1337            Operation::Drop => point.drop,
1338        }
1339    }
1340}
1341
1342#[tracing::instrument(level = "trace", skip(transform, body))]
1343fn create_cases<'tcx>(
1344    body: &mut Body<'tcx>,
1345    transform: &TransformVisitor<'tcx>,
1346    operation: Operation,
1347) -> Vec<(usize, BasicBlock)> {
1348    let source_info = SourceInfo::outermost(body.span);
1349
1350    transform
1351        .suspension_points
1352        .iter()
1353        .filter_map(|point| {
1354            // Find the target for this suspension point, if applicable
1355            operation.target_block(point).map(|target| {
1356                let mut statements = Vec::new();
1357
1358                // Create StorageLive instructions for locals with live storage
1359                for l in body.local_decls.indices() {
1360                    let needs_storage_live = point.storage_liveness.contains(l)
1361                        && !transform.remap.contains(l)
1362                        && !transform.always_live_locals.contains(l);
1363                    if needs_storage_live {
1364                        statements.push(Statement::new(source_info, StatementKind::StorageLive(l)));
1365                    }
1366                }
1367
1368                if operation == Operation::Resume && point.resume_arg != CTX_ARG.into() {
1369                    // Move the resume argument to the destination place of the `Yield` terminator
1370                    statements.push(Statement::new(
1371                        source_info,
1372                        StatementKind::Assign(Box::new((
1373                            point.resume_arg,
1374                            Rvalue::Use(Operand::Move(CTX_ARG.into())),
1375                        ))),
1376                    ));
1377                }
1378
1379                // Then jump to the real target
1380                let block = body.basic_blocks_mut().push(BasicBlockData::new_stmts(
1381                    statements,
1382                    Some(Terminator { source_info, kind: TerminatorKind::Goto { target } }),
1383                    false,
1384                ));
1385
1386                (point.state, block)
1387            })
1388        })
1389        .collect()
1390}
1391
1392#[instrument(level = "debug", skip(tcx), ret)]
1393pub(crate) fn mir_coroutine_witnesses<'tcx>(
1394    tcx: TyCtxt<'tcx>,
1395    def_id: LocalDefId,
1396) -> Option<CoroutineLayout<'tcx>> {
1397    let (body, _) = tcx.mir_promoted(def_id);
1398    let body = body.borrow();
1399    let body = &*body;
1400
1401    // The first argument is the coroutine type passed by value
1402    let coroutine_ty = body.local_decls[ty::CAPTURE_STRUCT_LOCAL].ty;
1403
1404    let movable = match *coroutine_ty.kind() {
1405        ty::Coroutine(def_id, _) => tcx.coroutine_movability(def_id) == hir::Movability::Movable,
1406        ty::Error(_) => return None,
1407        _ => span_bug!(body.span, "unexpected coroutine type {}", coroutine_ty),
1408    };
1409
1410    // The witness simply contains all locals live across suspend points.
1411
1412    let always_live_locals = always_storage_live_locals(body);
1413    let liveness_info = locals_live_across_suspend_points(tcx, body, &always_live_locals, movable);
1414
1415    // Extract locals which are live across suspension point into `layout`
1416    // `remap` gives a mapping from local indices onto coroutine struct indices
1417    // `storage_liveness` tells us which locals have live storage at suspension points
1418    let (_, coroutine_layout, _) = compute_layout(liveness_info, body);
1419
1420    check_suspend_tys(tcx, &coroutine_layout, body);
1421    check_field_tys_sized(tcx, &coroutine_layout, def_id);
1422
1423    Some(coroutine_layout)
1424}
1425
1426fn check_field_tys_sized<'tcx>(
1427    tcx: TyCtxt<'tcx>,
1428    coroutine_layout: &CoroutineLayout<'tcx>,
1429    def_id: LocalDefId,
1430) {
1431    // No need to check if unsized_fn_params is disabled,
1432    // since we will error during typeck.
1433    if !tcx.features().unsized_fn_params() {
1434        return;
1435    }
1436
1437    // FIXME(#132279): @lcnr believes that we may want to support coroutines
1438    // whose `Sized`-ness relies on the hidden types of opaques defined by the
1439    // parent function. In this case we'd have to be able to reveal only these
1440    // opaques here.
1441    let infcx = tcx.infer_ctxt().ignoring_regions().build(TypingMode::non_body_analysis());
1442    let param_env = tcx.param_env(def_id);
1443
1444    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
1445    for field_ty in &coroutine_layout.field_tys {
1446        ocx.register_bound(
1447            ObligationCause::new(
1448                field_ty.source_info.span,
1449                def_id,
1450                ObligationCauseCode::SizedCoroutineInterior(def_id),
1451            ),
1452            param_env,
1453            field_ty.ty,
1454            tcx.require_lang_item(hir::LangItem::Sized, field_ty.source_info.span),
1455        );
1456    }
1457
1458    let errors = ocx.evaluate_obligations_error_on_ambiguity();
1459    debug!(?errors);
1460    if !errors.is_empty() {
1461        infcx.err_ctxt().report_fulfillment_errors(errors);
1462    }
1463}
1464
1465impl<'tcx> crate::MirPass<'tcx> for StateTransform {
1466    #[instrument(level = "debug", skip(self, tcx, body), ret)]
1467    fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
1468        debug!(def_id = ?body.source.def_id());
1469
1470        let Some(old_yield_ty) = body.yield_ty() else {
1471            // This only applies to coroutines
1472            return;
1473        };
1474        tracing::trace!(def_id = ?body.source.def_id());
1475
1476        let old_ret_ty = body.return_ty();
1477
1478        assert!(body.coroutine_drop().is_none() && body.coroutine_drop_async().is_none());
1479
1480        if let Some(dumper) = MirDumper::new(tcx, "coroutine_before", body) {
1481            dumper.dump_mir(body);
1482        }
1483
1484        // The first argument is the coroutine type passed by value
1485        let coroutine_ty = body.local_decls.raw[1].ty;
1486        let coroutine_kind = body.coroutine_kind().unwrap();
1487
1488        // Get the discriminant type and args which typeck computed
1489        let ty::Coroutine(_, args) = coroutine_ty.kind() else {
1490            tcx.dcx().span_bug(body.span, format!("unexpected coroutine type {coroutine_ty}"));
1491        };
1492        let discr_ty = args.as_coroutine().discr_ty(tcx);
1493
1494        let new_ret_ty = match coroutine_kind {
1495            CoroutineKind::Desugared(CoroutineDesugaring::Async, _) => {
1496                // Compute Poll<return_ty>
1497                let poll_did = tcx.require_lang_item(LangItem::Poll, body.span);
1498                let poll_adt_ref = tcx.adt_def(poll_did);
1499                let poll_args = tcx.mk_args(&[old_ret_ty.into()]);
1500                Ty::new_adt(tcx, poll_adt_ref, poll_args)
1501            }
1502            CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
1503                // Compute Option<yield_ty>
1504                let option_did = tcx.require_lang_item(LangItem::Option, body.span);
1505                let option_adt_ref = tcx.adt_def(option_did);
1506                let option_args = tcx.mk_args(&[old_yield_ty.into()]);
1507                Ty::new_adt(tcx, option_adt_ref, option_args)
1508            }
1509            CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => {
1510                // The yield ty is already `Poll<Option<yield_ty>>`
1511                old_yield_ty
1512            }
1513            CoroutineKind::Coroutine(_) => {
1514                // Compute CoroutineState<yield_ty, return_ty>
1515                let state_did = tcx.require_lang_item(LangItem::CoroutineState, body.span);
1516                let state_adt_ref = tcx.adt_def(state_did);
1517                let state_args = tcx.mk_args(&[old_yield_ty.into(), old_ret_ty.into()]);
1518                Ty::new_adt(tcx, state_adt_ref, state_args)
1519            }
1520        };
1521
1522        // We need to insert clean drop for unresumed state and perform drop elaboration
1523        // (finally in open_drop_for_tuple) before async drop expansion.
1524        // Async drops, produced by this drop elaboration, will be expanded,
1525        // and corresponding futures kept in layout.
1526        let has_async_drops = matches!(
1527            coroutine_kind,
1528            CoroutineKind::Desugared(CoroutineDesugaring::Async | CoroutineDesugaring::AsyncGen, _)
1529        ) && has_expandable_async_drops(tcx, body, coroutine_ty);
1530
1531        // Replace all occurrences of `ResumeTy` with `&mut Context<'_>` within async bodies.
1532        if matches!(
1533            coroutine_kind,
1534            CoroutineKind::Desugared(CoroutineDesugaring::Async | CoroutineDesugaring::AsyncGen, _)
1535        ) {
1536            let context_mut_ref = transform_async_context(tcx, body);
1537            expand_async_drops(tcx, body, context_mut_ref, coroutine_kind, coroutine_ty);
1538
1539            if let Some(dumper) = MirDumper::new(tcx, "coroutine_async_drop_expand", body) {
1540                dumper.dump_mir(body);
1541            }
1542        } else {
1543            cleanup_async_drops(body);
1544        }
1545
1546        let always_live_locals = always_storage_live_locals(body);
1547        let movable = coroutine_kind.movability() == hir::Movability::Movable;
1548        let liveness_info =
1549            locals_live_across_suspend_points(tcx, body, &always_live_locals, movable);
1550
1551        if tcx.sess.opts.unstable_opts.validate_mir {
1552            let mut vis = EnsureCoroutineFieldAssignmentsNeverAlias {
1553                assigned_local: None,
1554                saved_locals: &liveness_info.saved_locals,
1555                storage_conflicts: &liveness_info.storage_conflicts,
1556            };
1557
1558            vis.visit_body(body);
1559        }
1560
1561        // Extract locals which are live across suspension point into `layout`
1562        // `remap` gives a mapping from local indices onto coroutine struct indices
1563        // `storage_liveness` tells us which locals have live storage at suspension points
1564        let (remap, layout, storage_liveness) = compute_layout(liveness_info, body);
1565
1566        let can_return = can_return(tcx, body, body.typing_env(tcx));
1567
1568        // We rename RETURN_PLACE which has type mir.return_ty to new_ret_local
1569        // RETURN_PLACE then is a fresh unused local with type ret_ty.
1570        let new_ret_local = body.local_decls.push(LocalDecl::new(new_ret_ty, body.span));
1571        tracing::trace!(?new_ret_local);
1572
1573        // Run the transformation which converts Places from Local to coroutine struct
1574        // accesses for locals in `remap`.
1575        // It also rewrites `return x` and `yield y` as writing a new coroutine state and returning
1576        // either `CoroutineState::Complete(x)` and `CoroutineState::Yielded(y)`,
1577        // or `Poll::Ready(x)` and `Poll::Pending` respectively depending on the coroutine kind.
1578        let mut transform = TransformVisitor {
1579            tcx,
1580            coroutine_kind,
1581            remap,
1582            storage_liveness,
1583            always_live_locals,
1584            suspension_points: Vec::new(),
1585            discr_ty,
1586            new_ret_local,
1587            old_ret_ty,
1588            old_yield_ty,
1589        };
1590        transform.visit_body(body);
1591
1592        // Swap the actual `RETURN_PLACE` and the provisional `new_ret_local`.
1593        transform.replace_local(RETURN_PLACE, new_ret_local, body);
1594
1595        // MIR parameters are not explicitly assigned-to when entering the MIR body.
1596        // If we want to save their values inside the coroutine state, we need to do so explicitly.
1597        let source_info = SourceInfo::outermost(body.span);
1598        let args_iter = body.args_iter();
1599        body.basic_blocks.as_mut()[START_BLOCK].statements.splice(
1600            0..0,
1601            args_iter.filter_map(|local| {
1602                let (ty, variant_index, idx) = transform.remap[local]?;
1603                let lhs = transform.make_field(variant_index, idx, ty);
1604                let rhs = Rvalue::Use(Operand::Move(local.into()));
1605                let assign = StatementKind::Assign(Box::new((lhs, rhs)));
1606                Some(Statement::new(source_info, assign))
1607            }),
1608        );
1609
1610        // Update our MIR struct to reflect the changes we've made
1611        body.arg_count = 2; // self, resume arg
1612        body.spread_arg = None;
1613
1614        // Remove the context argument within generator bodies.
1615        if matches!(coroutine_kind, CoroutineKind::Desugared(CoroutineDesugaring::Gen, _)) {
1616            transform_gen_context(body);
1617        }
1618
1619        // The original arguments to the function are no longer arguments, mark them as such.
1620        // Otherwise they'll conflict with our new arguments, which although they don't have
1621        // argument_index set, will get emitted as unnamed arguments.
1622        for var in &mut body.var_debug_info {
1623            var.argument_index = None;
1624        }
1625
1626        body.coroutine.as_mut().unwrap().yield_ty = None;
1627        body.coroutine.as_mut().unwrap().resume_ty = None;
1628        body.coroutine.as_mut().unwrap().coroutine_layout = Some(layout);
1629
1630        // FIXME: Drops, produced by insert_clean_drop + elaborate_coroutine_drops,
1631        // are currently sync only. To allow async for them, we need to move those calls
1632        // before expand_async_drops, and fix the related problems.
1633        //
1634        // Insert `drop(coroutine_struct)` which is used to drop upvars for coroutines in
1635        // the unresumed state.
1636        // This is expanded to a drop ladder in `elaborate_coroutine_drops`.
1637        let drop_clean = insert_clean_drop(tcx, body, has_async_drops);
1638
1639        if let Some(dumper) = MirDumper::new(tcx, "coroutine_pre-elab", body) {
1640            dumper.dump_mir(body);
1641        }
1642
1643        // Expand `drop(coroutine_struct)` to a drop ladder which destroys upvars.
1644        // If any upvars are moved out of, drop elaboration will handle upvar destruction.
1645        // However we need to also elaborate the code generated by `insert_clean_drop`.
1646        elaborate_coroutine_drops(tcx, body);
1647
1648        if let Some(dumper) = MirDumper::new(tcx, "coroutine_post-transform", body) {
1649            dumper.dump_mir(body);
1650        }
1651
1652        let can_unwind = can_unwind(tcx, body);
1653
1654        // Create a copy of our MIR and use it to create the drop shim for the coroutine
1655        if has_async_drops {
1656            // If coroutine has async drops, generating async drop shim
1657            let mut drop_shim =
1658                create_coroutine_drop_shim_async(tcx, &transform, body, drop_clean, can_unwind);
1659            // Run derefer to fix Derefs that are not in the first place
1660            deref_finder(tcx, &mut drop_shim, false);
1661            body.coroutine.as_mut().unwrap().coroutine_drop_async = Some(drop_shim);
1662        } else {
1663            // If coroutine has no async drops, generating sync drop shim
1664            let mut drop_shim =
1665                create_coroutine_drop_shim(tcx, &transform, coroutine_ty, body, drop_clean);
1666            // Run derefer to fix Derefs that are not in the first place
1667            deref_finder(tcx, &mut drop_shim, false);
1668            body.coroutine.as_mut().unwrap().coroutine_drop = Some(drop_shim);
1669
1670            // For coroutine with sync drop, generating async proxy for `future_drop_poll` call
1671            let mut proxy_shim = create_coroutine_drop_shim_proxy_async(tcx, body);
1672            deref_finder(tcx, &mut proxy_shim, false);
1673            body.coroutine.as_mut().unwrap().coroutine_drop_proxy_async = Some(proxy_shim);
1674        }
1675
1676        // Create the Coroutine::resume / Future::poll function
1677        create_coroutine_resume_function(tcx, transform, body, can_return, can_unwind);
1678
1679        // Run derefer to fix Derefs that are not in the first place
1680        deref_finder(tcx, body, false);
1681    }
1682
1683    fn is_required(&self) -> bool {
1684        true
1685    }
1686}
1687
1688/// Looks for any assignments between locals (e.g., `_4 = _5`) that will both be converted to fields
1689/// in the coroutine state machine but whose storage is not marked as conflicting
1690///
1691/// Validation needs to happen immediately *before* `TransformVisitor` is invoked, not after.
1692///
1693/// This condition would arise when the assignment is the last use of `_5` but the initial
1694/// definition of `_4` if we weren't extra careful to mark all locals used inside a statement as
1695/// conflicting. Non-conflicting coroutine saved locals may be stored at the same location within
1696/// the coroutine state machine, which would result in ill-formed MIR: the left-hand and right-hand
1697/// sides of an assignment may not alias. This caused a miscompilation in [#73137].
1698///
1699/// [#73137]: https://github.com/rust-lang/rust/issues/73137
1700struct EnsureCoroutineFieldAssignmentsNeverAlias<'a> {
1701    saved_locals: &'a CoroutineSavedLocals,
1702    storage_conflicts: &'a BitMatrix<CoroutineSavedLocal, CoroutineSavedLocal>,
1703    assigned_local: Option<CoroutineSavedLocal>,
1704}
1705
1706impl EnsureCoroutineFieldAssignmentsNeverAlias<'_> {
1707    fn saved_local_for_direct_place(&self, place: Place<'_>) -> Option<CoroutineSavedLocal> {
1708        if place.is_indirect() {
1709            return None;
1710        }
1711
1712        self.saved_locals.get(place.local)
1713    }
1714
1715    fn check_assigned_place(&mut self, place: Place<'_>, f: impl FnOnce(&mut Self)) {
1716        if let Some(assigned_local) = self.saved_local_for_direct_place(place) {
1717            assert!(self.assigned_local.is_none(), "`check_assigned_place` must not recurse");
1718
1719            self.assigned_local = Some(assigned_local);
1720            f(self);
1721            self.assigned_local = None;
1722        }
1723    }
1724}
1725
1726impl<'tcx> Visitor<'tcx> for EnsureCoroutineFieldAssignmentsNeverAlias<'_> {
1727    fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
1728        let Some(lhs) = self.assigned_local else {
1729            // This visitor only invokes `visit_place` for the right-hand side of an assignment
1730            // and only after setting `self.assigned_local`. However, the default impl of
1731            // `Visitor::super_body` may call `visit_place` with a `NonUseContext` for places
1732            // with debuginfo. Ignore them here.
1733            assert!(!context.is_use());
1734            return;
1735        };
1736
1737        let Some(rhs) = self.saved_local_for_direct_place(*place) else { return };
1738
1739        if !self.storage_conflicts.contains(lhs, rhs) {
1740            bug!(
1741                "Assignment between coroutine saved locals whose storage is not \
1742                    marked as conflicting: {:?}: {:?} = {:?}",
1743                location,
1744                lhs,
1745                rhs,
1746            );
1747        }
1748    }
1749
1750    fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
1751        match &statement.kind {
1752            StatementKind::Assign(box (lhs, rhs)) => {
1753                self.check_assigned_place(*lhs, |this| this.visit_rvalue(rhs, location));
1754            }
1755
1756            StatementKind::FakeRead(..)
1757            | StatementKind::SetDiscriminant { .. }
1758            | StatementKind::StorageLive(_)
1759            | StatementKind::StorageDead(_)
1760            | StatementKind::Retag(..)
1761            | StatementKind::AscribeUserType(..)
1762            | StatementKind::PlaceMention(..)
1763            | StatementKind::Coverage(..)
1764            | StatementKind::Intrinsic(..)
1765            | StatementKind::ConstEvalCounter
1766            | StatementKind::BackwardIncompatibleDropHint { .. }
1767            | StatementKind::Nop => {}
1768        }
1769    }
1770
1771    fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
1772        // Checking for aliasing in terminators is probably overkill, but until we have actual
1773        // semantics, we should be conservative here.
1774        match &terminator.kind {
1775            TerminatorKind::Call {
1776                func,
1777                args,
1778                destination,
1779                target: Some(_),
1780                unwind: _,
1781                call_source: _,
1782                fn_span: _,
1783            } => {
1784                self.check_assigned_place(*destination, |this| {
1785                    this.visit_operand(func, location);
1786                    for arg in args {
1787                        this.visit_operand(&arg.node, location);
1788                    }
1789                });
1790            }
1791
1792            TerminatorKind::Yield { value, resume: _, resume_arg, drop: _ } => {
1793                self.check_assigned_place(*resume_arg, |this| this.visit_operand(value, location));
1794            }
1795
1796            // FIXME: Does `asm!` have any aliasing requirements?
1797            TerminatorKind::InlineAsm { .. } => {}
1798
1799            TerminatorKind::Call { .. }
1800            | TerminatorKind::Goto { .. }
1801            | TerminatorKind::SwitchInt { .. }
1802            | TerminatorKind::UnwindResume
1803            | TerminatorKind::UnwindTerminate(_)
1804            | TerminatorKind::Return
1805            | TerminatorKind::TailCall { .. }
1806            | TerminatorKind::Unreachable
1807            | TerminatorKind::Drop { .. }
1808            | TerminatorKind::Assert { .. }
1809            | TerminatorKind::CoroutineDrop
1810            | TerminatorKind::FalseEdge { .. }
1811            | TerminatorKind::FalseUnwind { .. } => {}
1812        }
1813    }
1814}
1815
1816fn check_suspend_tys<'tcx>(tcx: TyCtxt<'tcx>, layout: &CoroutineLayout<'tcx>, body: &Body<'tcx>) {
1817    let mut linted_tys = FxHashSet::default();
1818
1819    for (variant, yield_source_info) in
1820        layout.variant_fields.iter().zip(&layout.variant_source_info)
1821    {
1822        debug!(?variant);
1823        for &local in variant {
1824            let decl = &layout.field_tys[local];
1825            debug!(?decl);
1826
1827            if !decl.ignore_for_traits && linted_tys.insert(decl.ty) {
1828                let Some(hir_id) = decl.source_info.scope.lint_root(&body.source_scopes) else {
1829                    continue;
1830                };
1831
1832                check_must_not_suspend_ty(
1833                    tcx,
1834                    decl.ty,
1835                    hir_id,
1836                    SuspendCheckData {
1837                        source_span: decl.source_info.span,
1838                        yield_span: yield_source_info.span,
1839                        plural_len: 1,
1840                        ..Default::default()
1841                    },
1842                );
1843            }
1844        }
1845    }
1846}
1847
1848#[derive(Default)]
1849struct SuspendCheckData<'a> {
1850    source_span: Span,
1851    yield_span: Span,
1852    descr_pre: &'a str,
1853    descr_post: &'a str,
1854    plural_len: usize,
1855}
1856
1857// Returns whether it emitted a diagnostic or not
1858// Note that this fn and the proceeding one are based on the code
1859// for creating must_use diagnostics
1860//
1861// Note that this technique was chosen over things like a `Suspend` marker trait
1862// as it is simpler and has precedent in the compiler
1863fn check_must_not_suspend_ty<'tcx>(
1864    tcx: TyCtxt<'tcx>,
1865    ty: Ty<'tcx>,
1866    hir_id: hir::HirId,
1867    data: SuspendCheckData<'_>,
1868) -> bool {
1869    if ty.is_unit() {
1870        return false;
1871    }
1872
1873    let plural_suffix = pluralize!(data.plural_len);
1874
1875    debug!("Checking must_not_suspend for {}", ty);
1876
1877    match *ty.kind() {
1878        ty::Adt(_, args) if ty.is_box() => {
1879            let boxed_ty = args.type_at(0);
1880            let allocator_ty = args.type_at(1);
1881            check_must_not_suspend_ty(
1882                tcx,
1883                boxed_ty,
1884                hir_id,
1885                SuspendCheckData { descr_pre: &format!("{}boxed ", data.descr_pre), ..data },
1886            ) || check_must_not_suspend_ty(
1887                tcx,
1888                allocator_ty,
1889                hir_id,
1890                SuspendCheckData { descr_pre: &format!("{}allocator ", data.descr_pre), ..data },
1891            )
1892        }
1893        // FIXME(sized_hierarchy): This should be replaced with a requirement that types in
1894        // coroutines implement `const Sized`. Scalable vectors are temporarily `Sized` while
1895        // `feature(sized_hierarchy)` is not fully implemented, but in practice are
1896        // non-`const Sized` and so do not have a known size at compilation time. Layout computation
1897        // for a coroutine containing scalable vectors would be incorrect.
1898        ty::Adt(def, _) if def.repr().scalable() => {
1899            tcx.dcx()
1900                .span_err(data.source_span, "scalable vectors cannot be held over await points");
1901            true
1902        }
1903        ty::Adt(def, _) => check_must_not_suspend_def(tcx, def.did(), hir_id, data),
1904        // FIXME: support adding the attribute to TAITs
1905        ty::Alias(ty::Opaque, ty::AliasTy { def_id: def, .. }) => {
1906            let mut has_emitted = false;
1907            for &(predicate, _) in tcx.explicit_item_bounds(def).skip_binder() {
1908                // We only look at the `DefId`, so it is safe to skip the binder here.
1909                if let ty::ClauseKind::Trait(ref poly_trait_predicate) =
1910                    predicate.kind().skip_binder()
1911                {
1912                    let def_id = poly_trait_predicate.trait_ref.def_id;
1913                    let descr_pre = &format!("{}implementer{} of ", data.descr_pre, plural_suffix);
1914                    if check_must_not_suspend_def(
1915                        tcx,
1916                        def_id,
1917                        hir_id,
1918                        SuspendCheckData { descr_pre, ..data },
1919                    ) {
1920                        has_emitted = true;
1921                        break;
1922                    }
1923                }
1924            }
1925            has_emitted
1926        }
1927        ty::Dynamic(binder, _) => {
1928            let mut has_emitted = false;
1929            for predicate in binder.iter() {
1930                if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate.skip_binder() {
1931                    let def_id = trait_ref.def_id;
1932                    let descr_post = &format!(" trait object{}{}", plural_suffix, data.descr_post);
1933                    if check_must_not_suspend_def(
1934                        tcx,
1935                        def_id,
1936                        hir_id,
1937                        SuspendCheckData { descr_post, ..data },
1938                    ) {
1939                        has_emitted = true;
1940                        break;
1941                    }
1942                }
1943            }
1944            has_emitted
1945        }
1946        ty::Tuple(fields) => {
1947            let mut has_emitted = false;
1948            for (i, ty) in fields.iter().enumerate() {
1949                let descr_post = &format!(" in tuple element {i}");
1950                if check_must_not_suspend_ty(
1951                    tcx,
1952                    ty,
1953                    hir_id,
1954                    SuspendCheckData { descr_post, ..data },
1955                ) {
1956                    has_emitted = true;
1957                }
1958            }
1959            has_emitted
1960        }
1961        ty::Array(ty, len) => {
1962            let descr_pre = &format!("{}array{} of ", data.descr_pre, plural_suffix);
1963            check_must_not_suspend_ty(
1964                tcx,
1965                ty,
1966                hir_id,
1967                SuspendCheckData {
1968                    descr_pre,
1969                    // FIXME(must_not_suspend): This is wrong. We should handle printing unevaluated consts.
1970                    plural_len: len.try_to_target_usize(tcx).unwrap_or(0) as usize + 1,
1971                    ..data
1972                },
1973            )
1974        }
1975        // If drop tracking is enabled, we want to look through references, since the referent
1976        // may not be considered live across the await point.
1977        ty::Ref(_region, ty, _mutability) => {
1978            let descr_pre = &format!("{}reference{} to ", data.descr_pre, plural_suffix);
1979            check_must_not_suspend_ty(tcx, ty, hir_id, SuspendCheckData { descr_pre, ..data })
1980        }
1981        _ => false,
1982    }
1983}
1984
1985fn check_must_not_suspend_def(
1986    tcx: TyCtxt<'_>,
1987    def_id: DefId,
1988    hir_id: hir::HirId,
1989    data: SuspendCheckData<'_>,
1990) -> bool {
1991    if let Some(reason_str) =
1992        find_attr!(tcx.get_all_attrs(def_id), AttributeKind::MustNotSupend {reason} => reason)
1993    {
1994        let reason =
1995            reason_str.map(|s| errors::MustNotSuspendReason { span: data.source_span, reason: s });
1996        tcx.emit_node_span_lint(
1997            rustc_session::lint::builtin::MUST_NOT_SUSPEND,
1998            hir_id,
1999            data.source_span,
2000            errors::MustNotSupend {
2001                tcx,
2002                yield_sp: data.yield_span,
2003                reason,
2004                src_sp: data.source_span,
2005                pre: data.descr_pre,
2006                def_id,
2007                post: data.descr_post,
2008            },
2009        );
2010
2011        true
2012    } else {
2013        false
2014    }
2015}