Skip to main content

rustc_mir_transform/coroutine/
layout.rs

1//! Coroutine `StateTransform` inverts control flow in a coroutine from a function with yield
2//! points to a state machine. Each yield point corresponds to a state variant, and each variant
3//! stores the locals that are needed to continue the coroutine.
4//!
5//! The state transform creates a `poll` method such that calling the coroutine `f()` is equivalent
6//! to:
7//! ```ignore (example)
8//! fn initial_mir(state: CoroutineState, mut resume_arg: ResumeTy) {
9//!     // Repeatedly poll the state machine.
10//!     loop {
11//!         match final_mir(&mut state, resume_arg) {
12//!             CoroutineState::Yielded(yield_value) => resume_arg = yield yield_value,
13//!             CoroutineState::Complete(return_value) => return return_value,
14//!         }
15//!     }
16//! }
17//! ```
18//!
19//! This file compute for each yield point the set of locals that need to be saved in the coroutine
20//! state. This is also used for borrowck to compute the set of types held inside that state, which
21//! determine trait and region predicates that hold for this state.
22
23use std::ops;
24
25use itertools::izip;
26use rustc_abi::{FieldIdx, PackCoroutineLayout, VariantIdx};
27use rustc_attr_ir::find_attr;
28use rustc_attr_ir::lang_items::LangItem;
29use rustc_data_structures::fx::FxHashSet;
30use rustc_errors::pluralize;
31use rustc_hir as hir;
32use rustc_index::bit_set::{BitMatrix, DenseBitSet};
33use rustc_index::{Idx, IndexVec};
34use rustc_infer::traits::TraitErrors;
35use rustc_lint_defs::builtin::MUST_NOT_SUSPEND;
36use rustc_middle::mir::*;
37use rustc_middle::ty::{self, CoroutineArgs, CoroutineArgsExt, Ty, TyCtxt, TypingMode};
38use rustc_mir_dataflow::impls::{
39    MaybeBorrowedLocals, MaybeLiveLocals, MaybeRequiresStorage, MaybeStorageLive,
40    always_storage_live_locals,
41};
42use rustc_mir_dataflow::{Analysis, Results, ResultsCursor, ResultsVisitor, visit_results};
43use rustc_span::def_id::{DefId, LocalDefId};
44use rustc_span::{Span, span_bug};
45use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
46use rustc_trait_selection::infer::TyCtxtInferExt as _;
47use rustc_trait_selection::traits::{ObligationCause, ObligationCauseCode, ObligationCtxt};
48use tracing::{debug, instrument};
49
50use crate::diagnostics::{MustNotSuspend, MustNotSuspendReason};
51
52pub(super) struct LivenessInfo {
53    /// Which locals are live across any suspension point.
54    pub(super) saved_locals: CoroutineSavedLocals,
55
56    /// The set of saved locals live at each suspension point.
57    live_locals_at_suspension_points: Vec<DenseBitSet<CoroutineSavedLocal>>,
58
59    /// Parallel vec to the above with SourceInfo for each yield terminator.
60    source_info_at_suspension_points: Vec<SourceInfo>,
61
62    /// For every saved local, the set of other saved locals that are
63    /// storage-live at the same time as this local. We cannot overlap locals in
64    /// the layout which have conflicting storage.
65    pub(super) storage_conflicts: BitMatrix<CoroutineSavedLocal, CoroutineSavedLocal>,
66
67    /// For every suspending block, the locals which are storage-live across
68    /// that suspension point.
69    storage_liveness: IndexVec<BasicBlock, Option<DenseBitSet<Local>>>,
70}
71
72/// Computes which locals have to be stored in the state-machine for the
73/// given coroutine.
74///
75/// The basic idea is as follows:
76/// - a local is live until we encounter a `StorageDead` statement. In
77///   case none exist, the local is considered to be always live.
78/// - a local has to be stored if it is either directly used after the
79///   the suspend point, or if it is live and has been previously borrowed.
80#[tracing::instrument(level = "trace", skip(tcx, body))]
81pub(super) fn locals_live_across_suspend_points<'tcx>(
82    tcx: TyCtxt<'tcx>,
83    body: &Body<'tcx>,
84    always_live_locals: &DenseBitSet<Local>,
85    movable: bool,
86) -> LivenessInfo {
87    // Calculate when MIR locals have live storage. This gives us an upper bound of their
88    // lifetimes.
89    let mut storage_live = MaybeStorageLive::new(std::borrow::Cow::Borrowed(always_live_locals))
90        .iterate_to_fixpoint(tcx, body, None)
91        .into_results_cursor(body);
92
93    // Calculate the MIR locals that have been previously borrowed (even if they are still active).
94    let borrowed_locals = MaybeBorrowedLocals.iterate_to_fixpoint(tcx, body, Some("coroutine"));
95
96    // Calculate the MIR locals that we need to keep storage around for.
97    let requires_storage =
98        MaybeRequiresStorage::new(body, &borrowed_locals).iterate_to_fixpoint(tcx, body, None);
99    let mut requires_storage_cursor = ResultsCursor::new_borrowing(body, &requires_storage);
100
101    // Calculate the liveness of MIR locals ignoring borrows.
102    let mut liveness =
103        MaybeLiveLocals.iterate_to_fixpoint(tcx, body, Some("coroutine")).into_results_cursor(body);
104
105    let mut storage_liveness_map = IndexVec::from_elem(None, &body.basic_blocks);
106    let mut live_locals_at_suspension_points = Vec::new();
107    let mut source_info_at_suspension_points = Vec::new();
108    let mut live_locals_at_any_suspension_point = DenseBitSet::new_empty(body.local_decls.len());
109    let mut borrowed_locals_cursor = ResultsCursor::new_owning(body, borrowed_locals);
110
111    for (block, data) in body.basic_blocks.iter_enumerated() {
112        let TerminatorKind::Yield { .. } = data.terminator().kind else { continue };
113
114        let loc = Location { block, statement_index: data.statements.len() };
115
116        liveness.seek_to_block_end(block);
117        let mut live_locals = liveness.get().clone();
118
119        if !movable {
120            // The `liveness` variable contains the liveness of MIR locals ignoring borrows.
121            // This is correct for movable coroutines since borrows cannot live across
122            // suspension points. However for immovable coroutines we need to account for
123            // borrows, so we conservatively assume that all borrowed locals are live until
124            // we find a StorageDead statement referencing the locals.
125            // To do this we just union our `liveness` result with `borrowed_locals`, which
126            // contains all the locals which has been borrowed before this suspension point.
127            // If a borrow is converted to a raw reference, we must also assume that it lives
128            // forever. Note that the final liveness is still bounded by the storage liveness
129            // of the local, which happens using the `intersect` operation below.
130            borrowed_locals_cursor.seek_before_primary_effect(loc);
131            live_locals.union(borrowed_locals_cursor.get());
132        }
133
134        // Store the storage liveness for later use so we can restore the state
135        // after a suspension point
136        storage_live.seek_before_primary_effect(loc);
137        storage_liveness_map[block] = Some(storage_live.get().clone());
138
139        // Locals live are live at this point only if they are used across
140        // suspension points (the `liveness` variable)
141        // and their storage is required (the `storage_required` variable)
142        requires_storage_cursor.seek_before_primary_effect(loc);
143        live_locals.intersect(requires_storage_cursor.get());
144
145        // The coroutine argument is ignored.
146        live_locals.remove(ty::CAPTURE_STRUCT_LOCAL);
147
148        debug!(?loc, ?live_locals);
149
150        // Add the locals live at this suspension point to the set of locals which live across
151        // any suspension points
152        live_locals_at_any_suspension_point.union(&live_locals);
153
154        live_locals_at_suspension_points.push(live_locals);
155        source_info_at_suspension_points.push(data.terminator().source_info);
156    }
157
158    debug!(?live_locals_at_any_suspension_point);
159    let saved_locals = CoroutineSavedLocals(live_locals_at_any_suspension_point);
160
161    // Renumber our liveness_map bitsets to include only the locals we are
162    // saving.
163    let live_locals_at_suspension_points = live_locals_at_suspension_points
164        .iter()
165        .map(|live_here| saved_locals.renumber_bitset(live_here))
166        .collect();
167
168    let storage_conflicts = compute_storage_conflicts(
169        body,
170        &saved_locals,
171        always_live_locals.clone(),
172        &requires_storage,
173    );
174
175    LivenessInfo {
176        saved_locals,
177        live_locals_at_suspension_points,
178        source_info_at_suspension_points,
179        storage_conflicts,
180        storage_liveness: storage_liveness_map,
181    }
182}
183
184/// The set of `Local`s that must be saved across yield points.
185///
186/// `CoroutineSavedLocal` is indexed in terms of the elements in this set;
187/// i.e. `CoroutineSavedLocal::new(1)` corresponds to the second local
188/// included in this set.
189pub(super) struct CoroutineSavedLocals(DenseBitSet<Local>);
190
191impl CoroutineSavedLocals {
192    /// Returns an iterator over each `CoroutineSavedLocal` along with the `Local` it corresponds
193    /// to.
194    fn iter_enumerated(&self) -> impl '_ + Iterator<Item = (CoroutineSavedLocal, Local)> {
195        self.iter().enumerate().map(|(i, l)| (CoroutineSavedLocal::from(i), l))
196    }
197
198    /// Transforms a `DenseBitSet<Local>` that contains only locals saved across yield points to the
199    /// equivalent `DenseBitSet<CoroutineSavedLocal>`.
200    fn renumber_bitset(&self, input: &DenseBitSet<Local>) -> DenseBitSet<CoroutineSavedLocal> {
201        assert!(self.superset(input), "{:?} not a superset of {:?}", self.0, input);
202        let mut out = DenseBitSet::new_empty(self.count());
203        for (saved_local, local) in self.iter_enumerated() {
204            if input.contains(local) {
205                out.insert(saved_local);
206            }
207        }
208        out
209    }
210
211    pub(super) fn get(&self, local: Local) -> Option<CoroutineSavedLocal> {
212        if !self.contains(local) {
213            return None;
214        }
215
216        let idx = self.iter().take_while(|&l| l < local).count();
217        Some(CoroutineSavedLocal::new(idx))
218    }
219}
220
221impl ops::Deref for CoroutineSavedLocals {
222    type Target = DenseBitSet<Local>;
223
224    fn deref(&self) -> &Self::Target {
225        &self.0
226    }
227}
228
229/// For every saved local, looks for which locals are StorageLive at the same
230/// time. Generates a bitset for every local of all the other locals that may be
231/// StorageLive simultaneously with that local. This is used in the layout
232/// computation; see `CoroutineLayout` for more.
233fn compute_storage_conflicts<'mir, 'tcx>(
234    body: &'mir Body<'tcx>,
235    saved_locals: &'mir CoroutineSavedLocals,
236    always_live_locals: DenseBitSet<Local>,
237    results: &Results<'tcx, MaybeRequiresStorage>,
238) -> BitMatrix<CoroutineSavedLocal, CoroutineSavedLocal> {
239    assert_eq!(body.local_decls.len(), saved_locals.domain_size());
240
241    debug!("compute_storage_conflicts({:?})", body.span);
242    debug!("always_live = {:?}", always_live_locals);
243
244    // Locals that are always live or ones that need to be stored across
245    // suspension points are not eligible for overlap.
246    let mut ineligible_locals = always_live_locals;
247    ineligible_locals.intersect(&**saved_locals);
248
249    // Compute the storage conflicts for all eligible locals.
250    let mut visitor = StorageConflictVisitor {
251        saved_locals,
252        local_conflicts: BitMatrix::from_row_n(&ineligible_locals, body.local_decls.len()),
253        eligible_storage_live: DenseBitSet::new_empty(body.local_decls.len()),
254        last_recorded_storage_live: DenseBitSet::new_empty(body.local_decls.len()),
255    };
256
257    // Filter out:
258    // - unreachable blocks;
259    // - reachable blocks that end in `Unreachable`, because they never complete execution and
260    //   conflicts within them are spurious.
261    let blocks = traversal::reachable(body).filter_map(|(bb, data)| {
262        (!matches!(data.terminator().kind, TerminatorKind::Unreachable)).then_some(bb)
263    });
264    visit_results(body, blocks, results, &mut visitor);
265
266    let local_conflicts = visitor.local_conflicts;
267
268    // Compress the matrix using only stored locals (Local -> CoroutineSavedLocal).
269    //
270    // NOTE: Today we store a full conflict bitset for every local. Technically
271    // this is twice as many bits as we need, since the relation is symmetric.
272    // However, in practice these bitsets are not usually large. The layout code
273    // also needs to keep track of how many conflicts each local has, so it's
274    // simpler to keep it this way for now.
275    let mut storage_conflicts = BitMatrix::new(saved_locals.count(), saved_locals.count());
276    for (saved_local_a, local_a) in saved_locals.iter_enumerated() {
277        if ineligible_locals.contains(local_a) {
278            // Conflicts with everything.
279            storage_conflicts.insert_all_into_row(saved_local_a);
280        } else {
281            // Keep overlap information only for stored locals.
282            for (saved_local_b, local_b) in saved_locals.iter_enumerated() {
283                if local_conflicts.contains(local_a, local_b) {
284                    storage_conflicts.insert(saved_local_a, saved_local_b);
285                }
286            }
287        }
288    }
289    storage_conflicts
290}
291
292struct StorageConflictVisitor<'a> {
293    saved_locals: &'a CoroutineSavedLocals,
294    // FIXME(tmandry): Consider using sparse bitsets here once we have good
295    // benchmarks for coroutines.
296    local_conflicts: BitMatrix<Local, Local>,
297    // We keep this bitset as a buffer to avoid reallocating memory.
298    eligible_storage_live: DenseBitSet<Local>,
299    // The last live set whose conflicts were recorded. This is just a fast path:
300    // if the current live set is a subset, we can skip updating the conflict matrix
301    // since its conflicts have already been recorded.
302    last_recorded_storage_live: DenseBitSet<Local>,
303}
304
305impl<'a, 'tcx> ResultsVisitor<'tcx, MaybeRequiresStorage> for StorageConflictVisitor<'a> {
306    fn visit_after_early_statement_effect(
307        &mut self,
308        state: &DenseBitSet<Local>,
309        _statement: &Statement<'tcx>,
310        _loc: Location,
311    ) {
312        self.apply_state(state);
313    }
314
315    fn visit_after_early_terminator_effect(
316        &mut self,
317        state: &DenseBitSet<Local>,
318        _terminator: &Terminator<'tcx>,
319        _loc: Location,
320    ) {
321        self.apply_state(state);
322    }
323}
324
325impl StorageConflictVisitor<'_> {
326    fn apply_state(&mut self, state: &DenseBitSet<Local>) {
327        self.eligible_storage_live.clone_from(state);
328        self.eligible_storage_live.intersect(&**self.saved_locals);
329
330        if self.last_recorded_storage_live.superset(&self.eligible_storage_live) {
331            return;
332        }
333
334        for local in self.eligible_storage_live.iter() {
335            self.local_conflicts.union_row_with(&self.eligible_storage_live, local);
336        }
337        std::mem::swap(&mut self.last_recorded_storage_live, &mut self.eligible_storage_live);
338    }
339}
340
341#[tracing::instrument(level = "trace", skip(liveness, body))]
342pub(super) fn compute_layout<'tcx>(
343    liveness: LivenessInfo,
344    body: &Body<'tcx>,
345) -> (
346    IndexVec<Local, Option<(Ty<'tcx>, VariantIdx, FieldIdx)>>,
347    CoroutineLayout<'tcx>,
348    IndexVec<BasicBlock, Option<DenseBitSet<Local>>>,
349) {
350    let LivenessInfo {
351        saved_locals,
352        live_locals_at_suspension_points,
353        source_info_at_suspension_points,
354        storage_conflicts,
355        storage_liveness,
356    } = liveness;
357
358    // Gather live local types.
359    let mut tys: IndexVec<CoroutineSavedLocal, CoroutineSavedTy<'_>> = saved_locals
360        .iter_enumerated()
361        .map(|(saved_local, local)| {
362            debug!("coroutine saved local {:?} => {:?}", saved_local, local);
363
364            let decl = &body.local_decls[local];
365
366            // Do not `unwrap_crate_local` here, as post-borrowck cleanup may have already cleared
367            // the information. This is alright, since `ignore_for_traits` is only relevant when
368            // this code runs on pre-cleanup MIR, and `ignore_for_traits = false` is the safer
369            // default.
370            let ignore_for_traits = match decl.local_info {
371                // Do not include raw pointers created from accessing `static` items, as those could
372                // well be re-created by another access to the same static.
373                ClearCrossCrate::Set(LocalInfo::StaticRef { is_thread_local, .. }) => {
374                    !is_thread_local
375                }
376                // Fake borrows are only read by fake reads, so do not have any reality in
377                // post-analysis MIR.
378                ClearCrossCrate::Set(LocalInfo::FakeBorrow) => true,
379                _ => false,
380            };
381
382            CoroutineSavedTy {
383                ty: decl.ty,
384                source_info: decl.source_info,
385                ignore_for_traits,
386                // Will be set later when walking debuginfo.
387                debuginfo_name: None,
388            }
389        })
390        .collect();
391
392    // Leave empty variants for the UNRESUMED, RETURNED, and POISONED states.
393    // In debuginfo, these will correspond to the beginning (UNRESUMED) or end
394    // (RETURNED, POISONED) of the function.
395    let body_span = body.source_scopes[OUTERMOST_SOURCE_SCOPE].span;
396    let mut variant_source_info: IndexVec<VariantIdx, SourceInfo> = IndexVec::with_capacity(
397        CoroutineArgs::RESERVED_VARIANTS + live_locals_at_suspension_points.len(),
398    );
399    variant_source_info.extend([
400        SourceInfo::outermost(body_span.shrink_to_lo()),
401        SourceInfo::outermost(body_span.shrink_to_hi()),
402        SourceInfo::outermost(body_span.shrink_to_hi()),
403    ]);
404
405    // Simple map from new to old indices to avoid repeatedly counting bits.
406    let reverse_local_map: IndexVec<CoroutineSavedLocal, Local> = saved_locals.iter().collect();
407
408    // Build the coroutine variant field list.
409    // Create a map from local indices to coroutine struct indices.
410    let mut variant_fields: IndexVec<VariantIdx, _> = IndexVec::from_elem_n(
411        IndexVec::new(),
412        CoroutineArgs::RESERVED_VARIANTS + live_locals_at_suspension_points.len(),
413    );
414    let mut remap = IndexVec::from_elem_n(None, saved_locals.domain_size());
415    for (live_locals, &source_info_at_suspension_point, (variant_index, fields)) in izip!(
416        &live_locals_at_suspension_points,
417        &source_info_at_suspension_points,
418        variant_fields.iter_enumerated_mut().skip(CoroutineArgs::RESERVED_VARIANTS)
419    ) {
420        *fields = live_locals.iter().collect();
421        for (idx, &saved_local) in fields.iter_enumerated() {
422            // Note that if a field is included in multiple variants, we will
423            // just use the first one here. That's fine; fields do not move
424            // around inside coroutines, so it doesn't matter which variant
425            // index we access them by.
426            remap[reverse_local_map[saved_local]] = Some((tys[saved_local].ty, variant_index, idx));
427        }
428        variant_source_info.push(source_info_at_suspension_point);
429    }
430    debug!(?variant_fields);
431    debug!(?storage_conflicts);
432
433    for var in &body.var_debug_info {
434        let VarDebugInfoContents::Place(place) = &var.value else { continue };
435        let Some(local) = place.as_local() else { continue };
436        let Some(&Some((_, variant, field))) = remap.get(local) else {
437            continue;
438        };
439
440        let saved_local: CoroutineSavedLocal = variant_fields[variant][field];
441        tys[saved_local].debuginfo_name.get_or_insert(var.name);
442    }
443
444    let layout = CoroutineLayout {
445        field_tys: tys,
446        variant_fields,
447        variant_source_info,
448        storage_conflicts,
449        // FIXME(-Zpack-coroutine-layout): Stop ignoring the flag here.
450        pack: PackCoroutineLayout::Classic,
451    };
452    debug!(?remap);
453    debug!(?layout);
454    debug!(?storage_liveness);
455
456    (remap, layout, storage_liveness)
457}
458
459#[instrument(level = "debug", skip(tcx), ret)]
460pub(crate) fn mir_coroutine_witnesses<'tcx>(
461    tcx: TyCtxt<'tcx>,
462    def_id: LocalDefId,
463) -> Option<CoroutineLayout<'tcx>> {
464    let (body, _) = tcx.mir_promoted(def_id);
465    let body = body.borrow();
466    let body = &*body;
467
468    // The first argument is the coroutine type passed by value
469    let coroutine_ty = body.local_decls[ty::CAPTURE_STRUCT_LOCAL].ty;
470
471    let movable = match *coroutine_ty.kind() {
472        ty::Coroutine(def_id, _) => tcx.coroutine_movability(def_id) == hir::Movability::Movable,
473        ty::Error(_) => return None,
474        _ => span_bug!(body.span, "unexpected coroutine type {}", coroutine_ty),
475    };
476
477    // The witness simply contains all locals live across suspend points.
478
479    let always_live_locals = always_storage_live_locals(body);
480    let liveness_info = locals_live_across_suspend_points(tcx, body, &always_live_locals, movable);
481
482    // Extract locals which are live across suspension point into `layout`
483    // `remap` gives a mapping from local indices onto coroutine struct indices
484    // `storage_liveness` tells us which locals have live storage at suspension points
485    let (_, coroutine_layout, _) = compute_layout(liveness_info, body);
486
487    check_suspend_tys(tcx, &coroutine_layout, body);
488    check_field_tys_sized(tcx, &coroutine_layout, def_id);
489
490    Some(coroutine_layout)
491}
492
493fn check_field_tys_sized<'tcx>(
494    tcx: TyCtxt<'tcx>,
495    coroutine_layout: &CoroutineLayout<'tcx>,
496    def_id: LocalDefId,
497) {
498    // No need to check if unsized_fn_params is disabled,
499    // since we will error during typeck.
500    if !tcx.features().unsized_fn_params() {
501        return;
502    }
503
504    // FIXME(#132279): @lcnr believes that we may want to support coroutines
505    // whose `Sized`-ness relies on the hidden types of opaques defined by the
506    // parent function. In this case we'd have to be able to reveal only these
507    // opaques here.
508    let infcx = tcx.infer_ctxt().ignoring_regions().build(TypingMode::non_body_analysis());
509    let param_env = tcx.param_env(def_id);
510
511    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
512    for field_ty in &coroutine_layout.field_tys {
513        ocx.register_bound(
514            ObligationCause::new(
515                field_ty.source_info.span,
516                def_id,
517                ObligationCauseCode::SizedCoroutineInterior(def_id),
518            ),
519            param_env,
520            field_ty.ty,
521            tcx.require_lang_item(LangItem::Sized, field_ty.source_info.span),
522        );
523    }
524
525    let errors = ocx.evaluate_obligations_error_on_ambiguity();
526    debug!(?errors);
527    if let TraitErrors::HasErrors(errors) = errors {
528        infcx.err_ctxt().report_fulfillment_errors(errors);
529    }
530}
531
532fn check_suspend_tys<'tcx>(tcx: TyCtxt<'tcx>, layout: &CoroutineLayout<'tcx>, body: &Body<'tcx>) {
533    let mut linted_tys = FxHashSet::default();
534
535    for (variant, yield_source_info) in
536        layout.variant_fields.iter().zip(&layout.variant_source_info)
537    {
538        debug!(?variant);
539        for &local in variant {
540            let decl = &layout.field_tys[local];
541            debug!(?decl);
542
543            if !decl.ignore_for_traits && linted_tys.insert(decl.ty) {
544                let Some(hir_id) = decl.source_info.scope.lint_root(&body.source_scopes) else {
545                    continue;
546                };
547
548                check_must_not_suspend_ty(
549                    tcx,
550                    decl.ty,
551                    hir_id,
552                    SuspendCheckData {
553                        source_span: decl.source_info.span,
554                        yield_span: yield_source_info.span,
555                        plural_len: 1,
556                        ..Default::default()
557                    },
558                );
559            }
560        }
561    }
562}
563
564#[derive(Default)]
565struct SuspendCheckData<'a> {
566    source_span: Span,
567    yield_span: Span,
568    descr_pre: &'a str,
569    descr_post: &'a str,
570    plural_len: usize,
571}
572
573// Returns whether it emitted a diagnostic or not
574// Note that this fn and the proceeding one are based on the code
575// for creating must_use diagnostics
576//
577// Note that this technique was chosen over things like a `Suspend` marker trait
578// as it is simpler and has precedent in the compiler
579fn check_must_not_suspend_ty<'tcx>(
580    tcx: TyCtxt<'tcx>,
581    ty: Ty<'tcx>,
582    hir_id: hir::HirId,
583    data: SuspendCheckData<'_>,
584) -> bool {
585    if ty.is_unit() {
586        return false;
587    }
588
589    let plural_suffix = pluralize!(data.plural_len);
590
591    debug!("Checking must_not_suspend for {}", ty);
592
593    match *ty.kind() {
594        ty::Adt(_, args) if ty.is_box() => {
595            let boxed_ty = args.type_at(0);
596            let allocator_ty = args.type_at(1);
597            check_must_not_suspend_ty(
598                tcx,
599                boxed_ty,
600                hir_id,
601                SuspendCheckData { descr_pre: &format!("{}boxed ", data.descr_pre), ..data },
602            ) || check_must_not_suspend_ty(
603                tcx,
604                allocator_ty,
605                hir_id,
606                SuspendCheckData { descr_pre: &format!("{}allocator ", data.descr_pre), ..data },
607            )
608        }
609        // FIXME(sized_hierarchy): This should be replaced with a requirement that types in
610        // coroutines implement `const Sized`. Scalable vectors are temporarily `Sized` while
611        // `feature(sized_hierarchy)` is not fully implemented, but in practice are
612        // non-`const Sized` and so do not have a known size at compilation time. Layout computation
613        // for a coroutine containing scalable vectors would be incorrect.
614        ty::Adt(def, _) if def.repr().scalable() => {
615            tcx.dcx()
616                .span_err(data.source_span, "scalable vectors cannot be held over await points");
617            true
618        }
619        ty::Adt(def, _) => check_must_not_suspend_def(tcx, def.did(), hir_id, data),
620        // FIXME: support adding the attribute to TAITs
621        ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id: def }, .. }) => {
622            let mut has_emitted = false;
623            for &(predicate, _) in tcx.explicit_item_bounds(def).skip_binder() {
624                // We only look at the `DefId`, so it is safe to skip the binder here.
625                if let ty::ClauseKind::Trait(ref poly_trait_predicate) =
626                    predicate.kind().skip_binder()
627                {
628                    let def_id = poly_trait_predicate.trait_ref.def_id;
629                    let descr_pre = &format!("{}implementer{} of ", data.descr_pre, plural_suffix);
630                    if check_must_not_suspend_def(
631                        tcx,
632                        def_id,
633                        hir_id,
634                        SuspendCheckData { descr_pre, ..data },
635                    ) {
636                        has_emitted = true;
637                        break;
638                    }
639                }
640            }
641            has_emitted
642        }
643        ty::Dynamic(binder, _) => {
644            let mut has_emitted = false;
645            for predicate in binder.iter() {
646                if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate.skip_binder() {
647                    let def_id = trait_ref.def_id;
648                    let descr_post = &format!(" trait object{}{}", plural_suffix, data.descr_post);
649                    if check_must_not_suspend_def(
650                        tcx,
651                        def_id,
652                        hir_id,
653                        SuspendCheckData { descr_post, ..data },
654                    ) {
655                        has_emitted = true;
656                        break;
657                    }
658                }
659            }
660            has_emitted
661        }
662        ty::Tuple(fields) => {
663            let mut has_emitted = false;
664            for (i, ty) in fields.iter().enumerate() {
665                let descr_post = &format!(" in tuple element {i}");
666                if check_must_not_suspend_ty(
667                    tcx,
668                    ty,
669                    hir_id,
670                    SuspendCheckData { descr_post, ..data },
671                ) {
672                    has_emitted = true;
673                }
674            }
675            has_emitted
676        }
677        ty::Array(ty, len) => {
678            let descr_pre = &format!("{}array{} of ", data.descr_pre, plural_suffix);
679            check_must_not_suspend_ty(
680                tcx,
681                ty,
682                hir_id,
683                SuspendCheckData {
684                    descr_pre,
685                    // FIXME(must_not_suspend): This is wrong. We should handle printing unevaluated consts.
686                    plural_len: len.try_to_target_usize(tcx).unwrap_or(0) as usize + 1,
687                    ..data
688                },
689            )
690        }
691        // If drop tracking is enabled, we want to look through references, since the referent
692        // may not be considered live across the await point.
693        ty::Ref(_region, ty, _mutability) => {
694            let descr_pre = &format!("{}reference{} to ", data.descr_pre, plural_suffix);
695            check_must_not_suspend_ty(tcx, ty, hir_id, SuspendCheckData { descr_pre, ..data })
696        }
697        _ => false,
698    }
699}
700
701fn check_must_not_suspend_def(
702    tcx: TyCtxt<'_>,
703    def_id: DefId,
704    hir_id: hir::HirId,
705    data: SuspendCheckData<'_>,
706) -> bool {
707    if let Some(reason_str) = find_attr!(tcx, def_id, MustNotSuspend {reason} => reason) {
708        let reason = reason_str.map(|s| MustNotSuspendReason { span: data.source_span, reason: s });
709        tcx.emit_node_span_lint(
710            MUST_NOT_SUSPEND,
711            hir_id,
712            data.source_span,
713            MustNotSuspend {
714                tcx,
715                yield_sp: data.yield_span,
716                reason,
717                src_sp: data.source_span,
718                pre: data.descr_pre,
719                def_id,
720                post: data.descr_post,
721            },
722        );
723
724        true
725    } else {
726        false
727    }
728}