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