1mod by_move_body;
54mod drop;
55use std::ops;
56
57pub(super) use by_move_body::coroutine_by_move_body_def_id;
58use drop::{
59 cleanup_async_drops, create_coroutine_drop_shim, create_coroutine_drop_shim_async,
60 create_coroutine_drop_shim_proxy_async, elaborate_coroutine_drops, expand_async_drops,
61 has_expandable_async_drops, insert_clean_drop,
62};
63use itertools::izip;
64use rustc_abi::{FieldIdx, VariantIdx};
65use rustc_data_structures::fx::FxHashSet;
66use rustc_errors::pluralize;
67use rustc_hir::lang_items::LangItem;
68use rustc_hir::{self as hir, CoroutineDesugaring, CoroutineKind, find_attr};
69use rustc_index::bit_set::{BitMatrix, DenseBitSet, GrowableBitSet};
70use rustc_index::{Idx, IndexVec, indexvec};
71use rustc_middle::mir::visit::{MutVisitor, MutatingUseContext, PlaceContext, Visitor};
72use rustc_middle::mir::*;
73use rustc_middle::ty::util::Discr;
74use rustc_middle::ty::{
75 self, CoroutineArgs, CoroutineArgsExt, GenericArgsRef, InstanceKind, Ty, TyCtxt, TypingMode,
76};
77use rustc_middle::{bug, span_bug};
78use rustc_mir_dataflow::impls::{
79 MaybeBorrowedLocals, MaybeLiveLocals, MaybeRequiresStorage, MaybeStorageLive,
80 always_storage_live_locals,
81};
82use rustc_mir_dataflow::{
83 Analysis, Results, ResultsCursor, ResultsVisitor, visit_reachable_results,
84};
85use rustc_span::def_id::{DefId, LocalDefId};
86use rustc_span::{DUMMY_SP, Span, dummy_spanned};
87use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
88use rustc_trait_selection::infer::TyCtxtInferExt as _;
89use rustc_trait_selection::traits::{ObligationCause, ObligationCauseCode, ObligationCtxt};
90use tracing::{debug, instrument, trace};
91
92use crate::deref_separator::deref_finder;
93use crate::{abort_unwinding_calls, errors, pass_manager as pm, simplify};
94
95pub(super) struct StateTransform;
96
97struct RenameLocalVisitor<'tcx> {
98 from: Local,
99 to: Local,
100 tcx: TyCtxt<'tcx>,
101}
102
103impl<'tcx> MutVisitor<'tcx> for RenameLocalVisitor<'tcx> {
104 fn tcx(&self) -> TyCtxt<'tcx> {
105 self.tcx
106 }
107
108 fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
109 if *local == self.from {
110 *local = self.to;
111 } else if *local == self.to {
112 *local = self.from;
113 }
114 }
115
116 fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, location: Location) {
117 match terminator.kind {
118 TerminatorKind::Return => {
119 }
122 _ => self.super_terminator(terminator, location),
123 }
124 }
125}
126
127struct SelfArgVisitor<'tcx> {
128 tcx: TyCtxt<'tcx>,
129 new_base: Place<'tcx>,
130}
131
132impl<'tcx> SelfArgVisitor<'tcx> {
133 fn new(tcx: TyCtxt<'tcx>, new_base: Place<'tcx>) -> Self {
134 Self { tcx, new_base }
135 }
136}
137
138impl<'tcx> MutVisitor<'tcx> for SelfArgVisitor<'tcx> {
139 fn tcx(&self) -> TyCtxt<'tcx> {
140 self.tcx
141 }
142
143 fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
144 assert_ne!(*local, SELF_ARG);
145 }
146
147 fn visit_place(&mut self, place: &mut Place<'tcx>, _: PlaceContext, _: Location) {
148 if place.local == SELF_ARG {
149 replace_base(place, self.new_base, self.tcx);
150 }
151
152 for elem in place.projection.iter() {
153 if let PlaceElem::Index(local) = elem {
154 assert_ne!(local, SELF_ARG);
155 }
156 }
157 }
158}
159
160#[tracing::instrument(level = "trace", skip(tcx))]
161fn replace_base<'tcx>(place: &mut Place<'tcx>, new_base: Place<'tcx>, tcx: TyCtxt<'tcx>) {
162 place.local = new_base.local;
163
164 let mut new_projection = new_base.projection.to_vec();
165 new_projection.append(&mut place.projection.to_vec());
166
167 place.projection = tcx.mk_place_elems(&new_projection);
168 tracing::trace!(?place);
169}
170
171const SELF_ARG: Local = Local::arg(0);
172const CTX_ARG: Local = Local::arg(1);
173
174struct SuspensionPoint<'tcx> {
176 state: usize,
178 resume: BasicBlock,
180 resume_arg: Place<'tcx>,
182 drop: Option<BasicBlock>,
184 storage_liveness: GrowableBitSet<Local>,
186}
187
188struct TransformVisitor<'tcx> {
189 tcx: TyCtxt<'tcx>,
190 coroutine_kind: hir::CoroutineKind,
191
192 discr_ty: Ty<'tcx>,
194
195 remap: IndexVec<Local, Option<(Ty<'tcx>, VariantIdx, FieldIdx)>>,
197
198 storage_liveness: IndexVec<BasicBlock, Option<DenseBitSet<Local>>>,
200
201 suspension_points: Vec<SuspensionPoint<'tcx>>,
203
204 always_live_locals: DenseBitSet<Local>,
206
207 new_ret_local: Local,
209
210 old_yield_ty: Ty<'tcx>,
211
212 old_ret_ty: Ty<'tcx>,
213}
214
215impl<'tcx> TransformVisitor<'tcx> {
216 fn insert_none_ret_block(&self, body: &mut Body<'tcx>) -> BasicBlock {
217 let block = body.basic_blocks.next_index();
218 let source_info = SourceInfo::outermost(body.span);
219
220 let none_value = match self.coroutine_kind {
221 CoroutineKind::Desugared(CoroutineDesugaring::Async, _) => {
222 span_bug!(body.span, "`Future`s are not fused inherently")
223 }
224 CoroutineKind::Coroutine(_) => span_bug!(body.span, "`Coroutine`s cannot be fused"),
225 CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
227 let option_def_id = self.tcx.require_lang_item(LangItem::Option, body.span);
228 make_aggregate_adt(
229 option_def_id,
230 VariantIdx::ZERO,
231 self.tcx.mk_args(&[self.old_yield_ty.into()]),
232 IndexVec::new(),
233 )
234 }
235 CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => {
237 let ty::Adt(_poll_adt, args) = *self.old_yield_ty.kind() else { bug!() };
238 let ty::Adt(_option_adt, args) = *args.type_at(0).kind() else { bug!() };
239 let yield_ty = args.type_at(0);
240 Rvalue::Use(
241 Operand::Constant(Box::new(ConstOperand {
242 span: source_info.span,
243 const_: Const::Unevaluated(
244 UnevaluatedConst::new(
245 self.tcx.require_lang_item(LangItem::AsyncGenFinished, body.span),
246 self.tcx.mk_args(&[yield_ty.into()]),
247 ),
248 self.old_yield_ty,
249 ),
250 user_ty: None,
251 })),
252 WithRetag::Yes,
253 )
254 }
255 };
256
257 let statements = vec![Statement::new(
258 source_info,
259 StatementKind::Assign(Box::new((Place::return_place(), none_value))),
260 )];
261
262 body.basic_blocks_mut().push(BasicBlockData::new_stmts(
263 statements,
264 Some(Terminator { source_info, kind: TerminatorKind::Return }),
265 false,
266 ));
267
268 block
269 }
270
271 #[tracing::instrument(level = "trace", skip(self, statements))]
277 fn make_state(
278 &self,
279 val: Operand<'tcx>,
280 source_info: SourceInfo,
281 is_return: bool,
282 statements: &mut Vec<Statement<'tcx>>,
283 ) {
284 const ZERO: VariantIdx = VariantIdx::ZERO;
285 const ONE: VariantIdx = VariantIdx::from_usize(1);
286 let rvalue = match self.coroutine_kind {
287 CoroutineKind::Desugared(CoroutineDesugaring::Async, _) => {
288 let poll_def_id = self.tcx.require_lang_item(LangItem::Poll, source_info.span);
289 let args = self.tcx.mk_args(&[self.old_ret_ty.into()]);
290 let (variant_idx, operands) = if is_return {
291 (ZERO, indexvec![val]) } else {
293 (ONE, IndexVec::new()) };
295 make_aggregate_adt(poll_def_id, variant_idx, args, operands)
296 }
297 CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
298 let option_def_id = self.tcx.require_lang_item(LangItem::Option, source_info.span);
299 let args = self.tcx.mk_args(&[self.old_yield_ty.into()]);
300 let (variant_idx, operands) = if is_return {
301 (ZERO, IndexVec::new()) } else {
303 (ONE, indexvec![val]) };
305 make_aggregate_adt(option_def_id, variant_idx, args, operands)
306 }
307 CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => {
308 if is_return {
309 let ty::Adt(_poll_adt, args) = *self.old_yield_ty.kind() else { bug!() };
310 let ty::Adt(_option_adt, args) = *args.type_at(0).kind() else { bug!() };
311 let yield_ty = args.type_at(0);
312 Rvalue::Use(
313 Operand::Constant(Box::new(ConstOperand {
314 span: source_info.span,
315 const_: Const::Unevaluated(
316 UnevaluatedConst::new(
317 self.tcx.require_lang_item(
318 LangItem::AsyncGenFinished,
319 source_info.span,
320 ),
321 self.tcx.mk_args(&[yield_ty.into()]),
322 ),
323 self.old_yield_ty,
324 ),
325 user_ty: None,
326 })),
327 WithRetag::Yes,
328 )
329 } else {
330 Rvalue::Use(val, WithRetag::Yes)
331 }
332 }
333 CoroutineKind::Coroutine(_) => {
334 let coroutine_state_def_id =
335 self.tcx.require_lang_item(LangItem::CoroutineState, source_info.span);
336 let args = self.tcx.mk_args(&[self.old_yield_ty.into(), self.old_ret_ty.into()]);
337 let variant_idx = if is_return {
338 ONE } else {
340 ZERO };
342 make_aggregate_adt(coroutine_state_def_id, variant_idx, args, indexvec![val])
343 }
344 };
345
346 statements.push(Statement::new(
348 source_info,
349 StatementKind::Assign(Box::new((self.new_ret_local.into(), rvalue))),
350 ));
351 }
352
353 #[tracing::instrument(level = "trace", skip(self), ret)]
355 fn make_field(&self, variant_index: VariantIdx, idx: FieldIdx, ty: Ty<'tcx>) -> Place<'tcx> {
356 let self_place = Place::from(SELF_ARG);
357 let base = self.tcx.mk_place_downcast_unnamed(self_place, variant_index);
358 let mut projection = base.projection.to_vec();
359 projection.push(ProjectionElem::Field(idx, ty));
360
361 Place { local: base.local, projection: self.tcx.mk_place_elems(&projection) }
362 }
363
364 #[tracing::instrument(level = "trace", skip(self))]
366 fn set_discr(&self, state_disc: VariantIdx, source_info: SourceInfo) -> Statement<'tcx> {
367 let self_place = Place::from(SELF_ARG);
368 Statement::new(
369 source_info,
370 StatementKind::SetDiscriminant {
371 place: Box::new(self_place),
372 variant_index: state_disc,
373 },
374 )
375 }
376
377 #[tracing::instrument(level = "trace", skip(self, body))]
379 fn get_discr(&self, body: &mut Body<'tcx>) -> (Statement<'tcx>, Place<'tcx>) {
380 let temp_decl = LocalDecl::new(self.discr_ty, body.span);
381 let local_decls_len = body.local_decls.push(temp_decl);
382 let temp = Place::from(local_decls_len);
383
384 let self_place = Place::from(SELF_ARG);
385 let assign = Statement::new(
386 SourceInfo::outermost(body.span),
387 StatementKind::Assign(Box::new((temp, Rvalue::Discriminant(self_place)))),
388 );
389 (assign, temp)
390 }
391
392 #[tracing::instrument(level = "trace", skip(self, body))]
394 fn replace_local(&mut self, old_local: Local, new_local: Local, body: &mut Body<'tcx>) {
395 body.local_decls.swap(old_local, new_local);
396
397 let mut visitor = RenameLocalVisitor { from: old_local, to: new_local, tcx: self.tcx };
398 visitor.visit_body(body);
399 for suspension in &mut self.suspension_points {
400 let ctxt = PlaceContext::MutatingUse(MutatingUseContext::Yield);
401 let location = Location { block: START_BLOCK, statement_index: 0 };
402 visitor.visit_place(&mut suspension.resume_arg, ctxt, location);
403 }
404 }
405}
406
407impl<'tcx> MutVisitor<'tcx> for TransformVisitor<'tcx> {
408 fn tcx(&self) -> TyCtxt<'tcx> {
409 self.tcx
410 }
411
412 #[tracing::instrument(level = "trace", skip(self), ret)]
413 fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _location: Location) {
414 assert!(!self.remap.contains(*local));
415 }
416
417 #[tracing::instrument(level = "trace", skip(self), ret)]
418 fn visit_place(&mut self, place: &mut Place<'tcx>, _: PlaceContext, _location: Location) {
419 if let Some(&Some((ty, variant_index, idx))) = self.remap.get(place.local) {
421 replace_base(place, self.make_field(variant_index, idx, ty), self.tcx);
422 }
423 }
424
425 #[tracing::instrument(level = "trace", skip(self, stmt), ret)]
426 fn visit_statement(&mut self, stmt: &mut Statement<'tcx>, location: Location) {
427 if let StatementKind::StorageLive(l) | StatementKind::StorageDead(l) = stmt.kind
429 && self.remap.contains(l)
430 {
431 stmt.make_nop(true);
432 }
433 self.super_statement(stmt, location);
434 }
435
436 #[tracing::instrument(level = "trace", skip(self, term), ret)]
437 fn visit_terminator(&mut self, term: &mut Terminator<'tcx>, location: Location) {
438 if let TerminatorKind::Return = term.kind {
439 return;
442 }
443 self.super_terminator(term, location);
444 }
445
446 #[tracing::instrument(level = "trace", skip(self, data), ret)]
447 fn visit_basic_block_data(&mut self, block: BasicBlock, data: &mut BasicBlockData<'tcx>) {
448 match data.terminator().kind {
449 TerminatorKind::Return => {
450 let source_info = data.terminator().source_info;
451 self.make_state(
453 Operand::Move(Place::return_place()),
454 source_info,
455 true,
456 &mut data.statements,
457 );
458 let state = VariantIdx::new(CoroutineArgs::RETURNED);
460 data.statements.push(self.set_discr(state, source_info));
461 data.terminator_mut().kind = TerminatorKind::Return;
462 }
463 TerminatorKind::Yield { ref value, resume, mut resume_arg, drop } => {
464 let source_info = data.terminator().source_info;
465 self.make_state(value.clone(), source_info, false, &mut data.statements);
467 let state = CoroutineArgs::RESERVED_VARIANTS + self.suspension_points.len();
469
470 if let Some(&Some((ty, variant, idx))) = self.remap.get(resume_arg.local) {
473 replace_base(&mut resume_arg, self.make_field(variant, idx, ty), self.tcx);
474 }
475
476 let storage_liveness: GrowableBitSet<Local> =
477 self.storage_liveness[block].clone().unwrap().into();
478
479 for i in 0..self.always_live_locals.domain_size() {
480 let l = Local::new(i);
481 let needs_storage_dead = storage_liveness.contains(l)
482 && !self.remap.contains(l)
483 && !self.always_live_locals.contains(l);
484 if needs_storage_dead {
485 data.statements
486 .push(Statement::new(source_info, StatementKind::StorageDead(l)));
487 }
488 }
489
490 self.suspension_points.push(SuspensionPoint {
491 state,
492 resume,
493 resume_arg,
494 drop,
495 storage_liveness,
496 });
497
498 let state = VariantIdx::new(state);
499 data.statements.push(self.set_discr(state, source_info));
500 data.terminator_mut().kind = TerminatorKind::Return;
501 }
502 _ => {}
503 }
504
505 self.super_basic_block_data(block, data);
506 }
507}
508
509fn make_aggregate_adt<'tcx>(
510 def_id: DefId,
511 variant_idx: VariantIdx,
512 args: GenericArgsRef<'tcx>,
513 operands: IndexVec<FieldIdx, Operand<'tcx>>,
514) -> Rvalue<'tcx> {
515 Rvalue::Aggregate(Box::new(AggregateKind::Adt(def_id, variant_idx, args, None, None)), operands)
516}
517
518#[tracing::instrument(level = "trace", skip(tcx, body))]
519fn make_coroutine_state_argument_indirect<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
520 let coroutine_ty = body.local_decls[SELF_ARG].ty;
521
522 let ref_coroutine_ty = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, coroutine_ty);
523
524 body.local_decls[SELF_ARG].ty = ref_coroutine_ty;
526
527 SelfArgVisitor::new(tcx, tcx.mk_place_deref(SELF_ARG.into())).visit_body(body);
529}
530
531#[tracing::instrument(level = "trace", skip(tcx, body))]
532fn make_coroutine_state_argument_pinned<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
533 let coroutine_ty = body.local_decls[SELF_ARG].ty;
534
535 let ref_coroutine_ty = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, coroutine_ty);
536
537 let pin_did = tcx.require_lang_item(LangItem::Pin, body.span);
538 let pin_adt_ref = tcx.adt_def(pin_did);
539 let args = tcx.mk_args(&[ref_coroutine_ty.into()]);
540 let pin_ref_coroutine_ty = Ty::new_adt(tcx, pin_adt_ref, args);
541
542 body.local_decls[SELF_ARG].ty = pin_ref_coroutine_ty;
544
545 let unpinned_local = body.local_decls.push(LocalDecl::new(ref_coroutine_ty, body.span));
546
547 SelfArgVisitor::new(tcx, tcx.mk_place_deref(unpinned_local.into())).visit_body(body);
549
550 let source_info = SourceInfo::outermost(body.span);
551 let pin_field = tcx.mk_place_field(SELF_ARG.into(), FieldIdx::ZERO, ref_coroutine_ty);
552
553 let statements = &mut body.basic_blocks.as_mut_preserves_cfg()[START_BLOCK].statements;
554 statements.insert(
555 0,
556 Statement::new(
557 source_info,
558 StatementKind::Assign(Box::new((
559 unpinned_local.into(),
560 Rvalue::Use(Operand::Copy(pin_field), WithRetag::Yes),
561 ))),
562 ),
563 );
564}
565
566#[tracing::instrument(level = "trace", skip(tcx, body), ret)]
588fn transform_async_context<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) -> Ty<'tcx> {
589 let context_mut_ref = Ty::new_task_context(tcx);
590
591 replace_resume_ty_local(tcx, body, CTX_ARG, context_mut_ref);
593
594 let get_context_def_id = tcx.require_lang_item(LangItem::GetContext, body.span);
595
596 for bb in body.basic_blocks.indices() {
597 let bb_data = &body[bb];
598 if bb_data.is_cleanup {
599 continue;
600 }
601
602 match &bb_data.terminator().kind {
603 TerminatorKind::Call { func, .. } => {
604 let func_ty = func.ty(body, tcx);
605 if let ty::FnDef(def_id, _) = *func_ty.kind()
606 && def_id == get_context_def_id
607 {
608 let local = eliminate_get_context_call(&mut body[bb]);
609 replace_resume_ty_local(tcx, body, local, context_mut_ref);
610 }
611 }
612 TerminatorKind::Yield { resume_arg, .. } => {
613 replace_resume_ty_local(tcx, body, resume_arg.local, context_mut_ref);
614 }
615 _ => {}
616 }
617 }
618 context_mut_ref
619}
620
621fn eliminate_get_context_call<'tcx>(bb_data: &mut BasicBlockData<'tcx>) -> Local {
622 let terminator = bb_data.terminator.take().unwrap();
623 let TerminatorKind::Call { args, destination, target, .. } = terminator.kind else {
624 bug!();
625 };
626 let [arg] = *Box::try_from(args).unwrap();
627 let local = arg.node.place().unwrap().local;
628
629 let arg = Rvalue::Use(arg.node, WithRetag::Yes);
630 let assign =
631 Statement::new(terminator.source_info, StatementKind::Assign(Box::new((destination, arg))));
632 bb_data.statements.push(assign);
633 bb_data.terminator = Some(Terminator {
634 source_info: terminator.source_info,
635 kind: TerminatorKind::Goto { target: target.unwrap() },
636 });
637 local
638}
639
640#[cfg_attr(not(debug_assertions), allow(unused))]
641#[tracing::instrument(level = "trace", skip(tcx, body), ret)]
642fn replace_resume_ty_local<'tcx>(
643 tcx: TyCtxt<'tcx>,
644 body: &mut Body<'tcx>,
645 local: Local,
646 context_mut_ref: Ty<'tcx>,
647) {
648 let local_ty = std::mem::replace(&mut body.local_decls[local].ty, context_mut_ref);
649 #[cfg(debug_assertions)]
652 {
653 if let ty::Adt(resume_ty_adt, _) = local_ty.kind() {
654 let expected_adt = tcx.adt_def(tcx.require_lang_item(LangItem::ResumeTy, body.span));
655 assert_eq!(*resume_ty_adt, expected_adt);
656 } else {
657 panic!("expected `ResumeTy`, found `{:?}`", local_ty);
658 };
659 }
660}
661
662fn transform_gen_context<'tcx>(body: &mut Body<'tcx>) {
672 body.arg_count = 1;
676}
677
678struct LivenessInfo {
679 saved_locals: CoroutineSavedLocals,
681
682 live_locals_at_suspension_points: Vec<DenseBitSet<CoroutineSavedLocal>>,
684
685 source_info_at_suspension_points: Vec<SourceInfo>,
687
688 storage_conflicts: BitMatrix<CoroutineSavedLocal, CoroutineSavedLocal>,
692
693 storage_liveness: IndexVec<BasicBlock, Option<DenseBitSet<Local>>>,
696}
697
698#[tracing::instrument(level = "trace", skip(tcx, body))]
707fn locals_live_across_suspend_points<'tcx>(
708 tcx: TyCtxt<'tcx>,
709 body: &Body<'tcx>,
710 always_live_locals: &DenseBitSet<Local>,
711 movable: bool,
712) -> LivenessInfo {
713 let mut storage_live = MaybeStorageLive::new(std::borrow::Cow::Borrowed(always_live_locals))
716 .iterate_to_fixpoint(tcx, body, None)
717 .into_results_cursor(body);
718
719 let borrowed_locals = MaybeBorrowedLocals.iterate_to_fixpoint(tcx, body, Some("coroutine"));
721 let borrowed_locals_cursor1 = ResultsCursor::new_borrowing(body, &borrowed_locals);
722 let mut borrowed_locals_cursor2 = ResultsCursor::new_borrowing(body, &borrowed_locals);
723
724 let requires_storage =
726 MaybeRequiresStorage::new(borrowed_locals_cursor1).iterate_to_fixpoint(tcx, body, None);
727 let mut requires_storage_cursor = ResultsCursor::new_borrowing(body, &requires_storage);
728
729 let mut liveness =
731 MaybeLiveLocals.iterate_to_fixpoint(tcx, body, Some("coroutine")).into_results_cursor(body);
732
733 let mut storage_liveness_map = IndexVec::from_elem(None, &body.basic_blocks);
734 let mut live_locals_at_suspension_points = Vec::new();
735 let mut source_info_at_suspension_points = Vec::new();
736 let mut live_locals_at_any_suspension_point = DenseBitSet::new_empty(body.local_decls.len());
737
738 for (block, data) in body.basic_blocks.iter_enumerated() {
739 let TerminatorKind::Yield { .. } = data.terminator().kind else { continue };
740
741 let loc = Location { block, statement_index: data.statements.len() };
742
743 liveness.seek_to_block_end(block);
744 let mut live_locals = liveness.get().clone();
745
746 if !movable {
747 borrowed_locals_cursor2.seek_before_primary_effect(loc);
758 live_locals.union(borrowed_locals_cursor2.get());
759 }
760
761 storage_live.seek_before_primary_effect(loc);
764 storage_liveness_map[block] = Some(storage_live.get().clone());
765
766 requires_storage_cursor.seek_before_primary_effect(loc);
770 live_locals.intersect(requires_storage_cursor.get());
771
772 live_locals.remove(SELF_ARG);
774
775 debug!(?loc, ?live_locals);
776
777 live_locals_at_any_suspension_point.union(&live_locals);
780
781 live_locals_at_suspension_points.push(live_locals);
782 source_info_at_suspension_points.push(data.terminator().source_info);
783 }
784
785 debug!(?live_locals_at_any_suspension_point);
786 let saved_locals = CoroutineSavedLocals(live_locals_at_any_suspension_point);
787
788 let live_locals_at_suspension_points = live_locals_at_suspension_points
791 .iter()
792 .map(|live_here| saved_locals.renumber_bitset(live_here))
793 .collect();
794
795 let storage_conflicts = compute_storage_conflicts(
796 body,
797 &saved_locals,
798 always_live_locals.clone(),
799 &requires_storage,
800 );
801
802 LivenessInfo {
803 saved_locals,
804 live_locals_at_suspension_points,
805 source_info_at_suspension_points,
806 storage_conflicts,
807 storage_liveness: storage_liveness_map,
808 }
809}
810
811struct CoroutineSavedLocals(DenseBitSet<Local>);
817
818impl CoroutineSavedLocals {
819 fn iter_enumerated(&self) -> impl '_ + Iterator<Item = (CoroutineSavedLocal, Local)> {
822 self.iter().enumerate().map(|(i, l)| (CoroutineSavedLocal::from(i), l))
823 }
824
825 fn renumber_bitset(&self, input: &DenseBitSet<Local>) -> DenseBitSet<CoroutineSavedLocal> {
828 assert!(self.superset(input), "{:?} not a superset of {:?}", self.0, input);
829 let mut out = DenseBitSet::new_empty(self.count());
830 for (saved_local, local) in self.iter_enumerated() {
831 if input.contains(local) {
832 out.insert(saved_local);
833 }
834 }
835 out
836 }
837
838 fn get(&self, local: Local) -> Option<CoroutineSavedLocal> {
839 if !self.contains(local) {
840 return None;
841 }
842
843 let idx = self.iter().take_while(|&l| l < local).count();
844 Some(CoroutineSavedLocal::new(idx))
845 }
846}
847
848impl ops::Deref for CoroutineSavedLocals {
849 type Target = DenseBitSet<Local>;
850
851 fn deref(&self) -> &Self::Target {
852 &self.0
853 }
854}
855
856fn compute_storage_conflicts<'mir, 'tcx>(
861 body: &'mir Body<'tcx>,
862 saved_locals: &'mir CoroutineSavedLocals,
863 always_live_locals: DenseBitSet<Local>,
864 results: &Results<'tcx, MaybeRequiresStorage<'mir, 'tcx>>,
865) -> BitMatrix<CoroutineSavedLocal, CoroutineSavedLocal> {
866 assert_eq!(body.local_decls.len(), saved_locals.domain_size());
867
868 debug!("compute_storage_conflicts({:?})", body.span);
869 debug!("always_live = {:?}", always_live_locals);
870
871 let mut ineligible_locals = always_live_locals;
874 ineligible_locals.intersect(&**saved_locals);
875
876 let mut visitor = StorageConflictVisitor {
878 body,
879 saved_locals,
880 local_conflicts: BitMatrix::from_row_n(&ineligible_locals, body.local_decls.len()),
881 eligible_storage_live: DenseBitSet::new_empty(body.local_decls.len()),
882 };
883
884 visit_reachable_results(body, results, &mut visitor);
885
886 let local_conflicts = visitor.local_conflicts;
887
888 let mut storage_conflicts = BitMatrix::new(saved_locals.count(), saved_locals.count());
896 for (saved_local_a, local_a) in saved_locals.iter_enumerated() {
897 if ineligible_locals.contains(local_a) {
898 storage_conflicts.insert_all_into_row(saved_local_a);
900 } else {
901 for (saved_local_b, local_b) in saved_locals.iter_enumerated() {
903 if local_conflicts.contains(local_a, local_b) {
904 storage_conflicts.insert(saved_local_a, saved_local_b);
905 }
906 }
907 }
908 }
909 storage_conflicts
910}
911
912struct StorageConflictVisitor<'a, 'tcx> {
913 body: &'a Body<'tcx>,
914 saved_locals: &'a CoroutineSavedLocals,
915 local_conflicts: BitMatrix<Local, Local>,
918 eligible_storage_live: DenseBitSet<Local>,
920}
921
922impl<'a, 'tcx> ResultsVisitor<'tcx, MaybeRequiresStorage<'a, 'tcx>>
923 for StorageConflictVisitor<'a, 'tcx>
924{
925 fn visit_after_early_statement_effect(
926 &mut self,
927 _analysis: &MaybeRequiresStorage<'a, 'tcx>,
928 state: &DenseBitSet<Local>,
929 _statement: &Statement<'tcx>,
930 loc: Location,
931 ) {
932 self.apply_state(state, loc);
933 }
934
935 fn visit_after_early_terminator_effect(
936 &mut self,
937 _analysis: &MaybeRequiresStorage<'a, 'tcx>,
938 state: &DenseBitSet<Local>,
939 _terminator: &Terminator<'tcx>,
940 loc: Location,
941 ) {
942 self.apply_state(state, loc);
943 }
944}
945
946impl StorageConflictVisitor<'_, '_> {
947 fn apply_state(&mut self, state: &DenseBitSet<Local>, loc: Location) {
948 if let TerminatorKind::Unreachable = self.body.basic_blocks[loc.block].terminator().kind {
950 return;
951 }
952
953 self.eligible_storage_live.clone_from(state);
954 self.eligible_storage_live.intersect(&**self.saved_locals);
955
956 for local in self.eligible_storage_live.iter() {
957 self.local_conflicts.union_row_with(&self.eligible_storage_live, local);
958 }
959
960 if self.eligible_storage_live.count() > 1 {
961 trace!("at {:?}, eligible_storage_live={:?}", loc, self.eligible_storage_live);
962 }
963 }
964}
965
966#[tracing::instrument(level = "trace", skip(liveness, body))]
967fn compute_layout<'tcx>(
968 liveness: LivenessInfo,
969 body: &Body<'tcx>,
970) -> (
971 IndexVec<Local, Option<(Ty<'tcx>, VariantIdx, FieldIdx)>>,
972 CoroutineLayout<'tcx>,
973 IndexVec<BasicBlock, Option<DenseBitSet<Local>>>,
974) {
975 let LivenessInfo {
976 saved_locals,
977 live_locals_at_suspension_points,
978 source_info_at_suspension_points,
979 storage_conflicts,
980 storage_liveness,
981 } = liveness;
982
983 let mut locals = IndexVec::<CoroutineSavedLocal, _>::with_capacity(saved_locals.domain_size());
985 let mut tys = IndexVec::<CoroutineSavedLocal, _>::with_capacity(saved_locals.domain_size());
986 for (saved_local, local) in saved_locals.iter_enumerated() {
987 debug!("coroutine saved local {:?} => {:?}", saved_local, local);
988
989 locals.push(local);
990 let decl = &body.local_decls[local];
991 debug!(?decl);
992
993 let ignore_for_traits = match decl.local_info {
998 ClearCrossCrate::Set(LocalInfo::StaticRef { is_thread_local, .. }) => !is_thread_local,
1001 ClearCrossCrate::Set(LocalInfo::FakeBorrow) => true,
1004 _ => false,
1005 };
1006 let decl =
1007 CoroutineSavedTy { ty: decl.ty, source_info: decl.source_info, ignore_for_traits };
1008 debug!(?decl);
1009
1010 tys.push(decl);
1011 }
1012
1013 let body_span = body.source_scopes[OUTERMOST_SOURCE_SCOPE].span;
1017 let mut variant_source_info: IndexVec<VariantIdx, SourceInfo> = IndexVec::with_capacity(
1018 CoroutineArgs::RESERVED_VARIANTS + live_locals_at_suspension_points.len(),
1019 );
1020 variant_source_info.extend([
1021 SourceInfo::outermost(body_span.shrink_to_lo()),
1022 SourceInfo::outermost(body_span.shrink_to_hi()),
1023 SourceInfo::outermost(body_span.shrink_to_hi()),
1024 ]);
1025
1026 let mut variant_fields: IndexVec<VariantIdx, _> = IndexVec::from_elem_n(
1029 IndexVec::new(),
1030 CoroutineArgs::RESERVED_VARIANTS + live_locals_at_suspension_points.len(),
1031 );
1032 let mut remap = IndexVec::from_elem_n(None, saved_locals.domain_size());
1033 for (live_locals, &source_info_at_suspension_point, (variant_index, fields)) in izip!(
1034 &live_locals_at_suspension_points,
1035 &source_info_at_suspension_points,
1036 variant_fields.iter_enumerated_mut().skip(CoroutineArgs::RESERVED_VARIANTS)
1037 ) {
1038 *fields = live_locals.iter().collect();
1039 for (idx, &saved_local) in fields.iter_enumerated() {
1040 remap[locals[saved_local]] = Some((tys[saved_local].ty, variant_index, idx));
1045 }
1046 variant_source_info.push(source_info_at_suspension_point);
1047 }
1048 debug!(?variant_fields);
1049 debug!(?storage_conflicts);
1050
1051 let mut field_names = IndexVec::from_elem(None, &tys);
1052 for var in &body.var_debug_info {
1053 let VarDebugInfoContents::Place(place) = &var.value else { continue };
1054 let Some(local) = place.as_local() else { continue };
1055 let Some(&Some((_, variant, field))) = remap.get(local) else {
1056 continue;
1057 };
1058
1059 let saved_local = variant_fields[variant][field];
1060 field_names.get_or_insert_with(saved_local, || var.name);
1061 }
1062
1063 let layout = CoroutineLayout {
1064 field_tys: tys,
1065 field_names,
1066 variant_fields,
1067 variant_source_info,
1068 storage_conflicts,
1069 };
1070 debug!(?remap);
1071 debug!(?layout);
1072 debug!(?storage_liveness);
1073
1074 (remap, layout, storage_liveness)
1075}
1076
1077fn insert_switch<'tcx>(
1082 body: &mut Body<'tcx>,
1083 cases: Vec<(usize, BasicBlock)>,
1084 transform: &TransformVisitor<'tcx>,
1085 default_block: BasicBlock,
1086) {
1087 let (assign, discr) = transform.get_discr(body);
1088 let switch_targets =
1089 SwitchTargets::new(cases.iter().map(|(i, bb)| ((*i) as u128, *bb)), default_block);
1090 let switch = TerminatorKind::SwitchInt { discr: Operand::Move(discr), targets: switch_targets };
1091
1092 let source_info = SourceInfo::outermost(body.span);
1093 body.basic_blocks_mut().raw.insert(
1094 0,
1095 BasicBlockData::new_stmts(
1096 vec![assign],
1097 Some(Terminator { source_info, kind: switch }),
1098 false,
1099 ),
1100 );
1101
1102 for b in body.basic_blocks_mut().iter_mut() {
1103 b.terminator_mut().successors_mut(|target| *target += 1);
1104 }
1105}
1106
1107fn insert_term_block<'tcx>(body: &mut Body<'tcx>, kind: TerminatorKind<'tcx>) -> BasicBlock {
1108 let source_info = SourceInfo::outermost(body.span);
1109 body.basic_blocks_mut().push(BasicBlockData::new(Some(Terminator { source_info, kind }), false))
1110}
1111
1112fn return_poll_ready_assign<'tcx>(tcx: TyCtxt<'tcx>, source_info: SourceInfo) -> Statement<'tcx> {
1113 let poll_def_id = tcx.require_lang_item(LangItem::Poll, source_info.span);
1115 let args = tcx.mk_args(&[tcx.types.unit.into()]);
1116 let val = Operand::Constant(Box::new(ConstOperand {
1117 span: source_info.span,
1118 user_ty: None,
1119 const_: Const::zero_sized(tcx.types.unit),
1120 }));
1121 let ready_val = Rvalue::Aggregate(
1122 Box::new(AggregateKind::Adt(poll_def_id, VariantIdx::from_usize(0), args, None, None)),
1123 indexvec![val],
1124 );
1125 Statement::new(source_info, StatementKind::Assign(Box::new((Place::return_place(), ready_val))))
1126}
1127
1128fn insert_poll_ready_block<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) -> BasicBlock {
1129 let source_info = SourceInfo::outermost(body.span);
1130 body.basic_blocks_mut().push(BasicBlockData::new_stmts(
1131 [return_poll_ready_assign(tcx, source_info)].to_vec(),
1132 Some(Terminator { source_info, kind: TerminatorKind::Return }),
1133 false,
1134 ))
1135}
1136
1137fn insert_panic_block<'tcx>(
1138 tcx: TyCtxt<'tcx>,
1139 body: &mut Body<'tcx>,
1140 message: AssertMessage<'tcx>,
1141) -> BasicBlock {
1142 let assert_block = body.basic_blocks.next_index();
1143 let kind = TerminatorKind::Assert {
1144 cond: Operand::Constant(Box::new(ConstOperand {
1145 span: body.span,
1146 user_ty: None,
1147 const_: Const::from_bool(tcx, false),
1148 })),
1149 expected: true,
1150 msg: Box::new(message),
1151 target: assert_block,
1152 unwind: UnwindAction::Continue,
1153 };
1154
1155 insert_term_block(body, kind)
1156}
1157
1158fn can_return<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1159 if body.return_ty().is_privately_uninhabited(tcx, typing_env) {
1161 return false;
1162 }
1163
1164 body.basic_blocks.iter().any(|block| matches!(block.terminator().kind, TerminatorKind::Return))
1166 }
1168
1169fn can_unwind<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>) -> bool {
1170 if !tcx.sess.panic_strategy().unwinds() {
1172 return false;
1173 }
1174
1175 for block in body.basic_blocks.iter() {
1177 match block.terminator().kind {
1178 TerminatorKind::Goto { .. }
1180 | TerminatorKind::SwitchInt { .. }
1181 | TerminatorKind::UnwindTerminate(_)
1182 | TerminatorKind::Return
1183 | TerminatorKind::Unreachable
1184 | TerminatorKind::CoroutineDrop
1185 | TerminatorKind::FalseEdge { .. }
1186 | TerminatorKind::FalseUnwind { .. } => {}
1187
1188 TerminatorKind::UnwindResume => {}
1191
1192 TerminatorKind::Yield { .. } => {
1193 unreachable!("`can_unwind` called before coroutine transform")
1194 }
1195
1196 TerminatorKind::Drop { .. }
1198 | TerminatorKind::Call { .. }
1199 | TerminatorKind::InlineAsm { .. }
1200 | TerminatorKind::Assert { .. } => return true,
1201
1202 TerminatorKind::TailCall { .. } => {
1203 unreachable!("tail calls can't be present in generators")
1204 }
1205 }
1206 }
1207
1208 false
1210}
1211
1212fn generate_poison_block_and_redirect_unwinds_there<'tcx>(
1214 transform: &TransformVisitor<'tcx>,
1215 body: &mut Body<'tcx>,
1216) {
1217 let source_info = SourceInfo::outermost(body.span);
1218 let poison_block = body.basic_blocks_mut().push(BasicBlockData::new_stmts(
1219 vec![transform.set_discr(VariantIdx::new(CoroutineArgs::POISONED), source_info)],
1220 Some(Terminator { source_info, kind: TerminatorKind::UnwindResume }),
1221 true,
1222 ));
1223
1224 for (idx, block) in body.basic_blocks_mut().iter_enumerated_mut() {
1225 let source_info = block.terminator().source_info;
1226
1227 if let TerminatorKind::UnwindResume = block.terminator().kind {
1228 if idx != poison_block {
1231 *block.terminator_mut() =
1232 Terminator { source_info, kind: TerminatorKind::Goto { target: poison_block } };
1233 }
1234 } else if !block.is_cleanup
1235 && let Some(unwind @ UnwindAction::Continue) = block.terminator_mut().unwind_mut()
1238 {
1239 *unwind = UnwindAction::Cleanup(poison_block);
1240 }
1241 }
1242}
1243
1244#[tracing::instrument(level = "trace", skip(tcx, transform, body))]
1245fn create_coroutine_resume_function<'tcx>(
1246 tcx: TyCtxt<'tcx>,
1247 transform: TransformVisitor<'tcx>,
1248 body: &mut Body<'tcx>,
1249 can_return: bool,
1250 can_unwind: bool,
1251) {
1252 if can_unwind {
1254 generate_poison_block_and_redirect_unwinds_there(&transform, body);
1255 }
1256
1257 let mut cases = create_cases(body, &transform, Operation::Resume);
1258
1259 use rustc_middle::mir::AssertKind::{ResumedAfterPanic, ResumedAfterReturn};
1260
1261 cases.insert(0, (CoroutineArgs::UNRESUMED, START_BLOCK));
1263
1264 if can_unwind {
1266 cases.insert(
1267 1,
1268 (
1269 CoroutineArgs::POISONED,
1270 insert_panic_block(tcx, body, ResumedAfterPanic(transform.coroutine_kind)),
1271 ),
1272 );
1273 }
1274
1275 if can_return {
1276 let block = match transform.coroutine_kind {
1277 CoroutineKind::Desugared(CoroutineDesugaring::Async, _)
1278 | CoroutineKind::Coroutine(_) => {
1279 if tcx.is_async_drop_in_place_coroutine(body.source.def_id()) {
1282 insert_poll_ready_block(tcx, body)
1283 } else {
1284 insert_panic_block(tcx, body, ResumedAfterReturn(transform.coroutine_kind))
1285 }
1286 }
1287 CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _)
1288 | CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
1289 transform.insert_none_ret_block(body)
1290 }
1291 };
1292 cases.insert(1, (CoroutineArgs::RETURNED, block));
1293 }
1294
1295 let default_block = insert_term_block(body, TerminatorKind::Unreachable);
1296 insert_switch(body, cases, &transform, default_block);
1297
1298 match transform.coroutine_kind {
1299 CoroutineKind::Coroutine(_)
1300 | CoroutineKind::Desugared(CoroutineDesugaring::Async | CoroutineDesugaring::AsyncGen, _) =>
1301 {
1302 make_coroutine_state_argument_pinned(tcx, body);
1303 }
1304 CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
1307 make_coroutine_state_argument_indirect(tcx, body);
1308 }
1309 }
1310
1311 simplify::remove_dead_blocks(body);
1314
1315 pm::run_passes_no_validate(tcx, body, &[&abort_unwinding_calls::AbortUnwindingCalls], None);
1316
1317 if let Some(dumper) = MirDumper::new(tcx, "coroutine_resume", body) {
1318 dumper.dump_mir(body);
1319 }
1320}
1321
1322#[derive(PartialEq, Copy, Clone, Debug)]
1324enum Operation {
1325 Resume,
1326 Drop,
1327}
1328
1329impl Operation {
1330 fn target_block(self, point: &SuspensionPoint<'_>) -> Option<BasicBlock> {
1331 match self {
1332 Operation::Resume => Some(point.resume),
1333 Operation::Drop => point.drop,
1334 }
1335 }
1336}
1337
1338#[tracing::instrument(level = "trace", skip(transform, body))]
1339fn create_cases<'tcx>(
1340 body: &mut Body<'tcx>,
1341 transform: &TransformVisitor<'tcx>,
1342 operation: Operation,
1343) -> Vec<(usize, BasicBlock)> {
1344 let source_info = SourceInfo::outermost(body.span);
1345
1346 transform
1347 .suspension_points
1348 .iter()
1349 .filter_map(|point| {
1350 operation.target_block(point).map(|target| {
1352 let mut statements = Vec::new();
1353
1354 for l in body.local_decls.indices() {
1356 let needs_storage_live = point.storage_liveness.contains(l)
1357 && !transform.remap.contains(l)
1358 && !transform.always_live_locals.contains(l);
1359 if needs_storage_live {
1360 statements.push(Statement::new(source_info, StatementKind::StorageLive(l)));
1361 }
1362 }
1363
1364 if operation == Operation::Resume && point.resume_arg != CTX_ARG.into() {
1365 statements.push(Statement::new(
1367 source_info,
1368 StatementKind::Assign(Box::new((
1369 point.resume_arg,
1370 Rvalue::Use(Operand::Move(CTX_ARG.into()), WithRetag::Yes),
1371 ))),
1372 ));
1373 }
1374
1375 let block = body.basic_blocks_mut().push(BasicBlockData::new_stmts(
1377 statements,
1378 Some(Terminator { source_info, kind: TerminatorKind::Goto { target } }),
1379 false,
1380 ));
1381
1382 (point.state, block)
1383 })
1384 })
1385 .collect()
1386}
1387
1388#[instrument(level = "debug", skip(tcx), ret)]
1389pub(crate) fn mir_coroutine_witnesses<'tcx>(
1390 tcx: TyCtxt<'tcx>,
1391 def_id: LocalDefId,
1392) -> Option<CoroutineLayout<'tcx>> {
1393 let (body, _) = tcx.mir_promoted(def_id);
1394 let body = body.borrow();
1395 let body = &*body;
1396
1397 let coroutine_ty = body.local_decls[ty::CAPTURE_STRUCT_LOCAL].ty;
1399
1400 let movable = match *coroutine_ty.kind() {
1401 ty::Coroutine(def_id, _) => tcx.coroutine_movability(def_id) == hir::Movability::Movable,
1402 ty::Error(_) => return None,
1403 _ => span_bug!(body.span, "unexpected coroutine type {}", coroutine_ty),
1404 };
1405
1406 let always_live_locals = always_storage_live_locals(body);
1409 let liveness_info = locals_live_across_suspend_points(tcx, body, &always_live_locals, movable);
1410
1411 let (_, coroutine_layout, _) = compute_layout(liveness_info, body);
1415
1416 check_suspend_tys(tcx, &coroutine_layout, body);
1417 check_field_tys_sized(tcx, &coroutine_layout, def_id);
1418
1419 Some(coroutine_layout)
1420}
1421
1422fn check_field_tys_sized<'tcx>(
1423 tcx: TyCtxt<'tcx>,
1424 coroutine_layout: &CoroutineLayout<'tcx>,
1425 def_id: LocalDefId,
1426) {
1427 if !tcx.features().unsized_fn_params() {
1430 return;
1431 }
1432
1433 let infcx = tcx.infer_ctxt().ignoring_regions().build(TypingMode::non_body_analysis());
1438 let param_env = tcx.param_env(def_id);
1439
1440 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
1441 for field_ty in &coroutine_layout.field_tys {
1442 ocx.register_bound(
1443 ObligationCause::new(
1444 field_ty.source_info.span,
1445 def_id,
1446 ObligationCauseCode::SizedCoroutineInterior(def_id),
1447 ),
1448 param_env,
1449 field_ty.ty,
1450 tcx.require_lang_item(hir::LangItem::Sized, field_ty.source_info.span),
1451 );
1452 }
1453
1454 let errors = ocx.evaluate_obligations_error_on_ambiguity();
1455 debug!(?errors);
1456 if !errors.is_empty() {
1457 infcx.err_ctxt().report_fulfillment_errors(errors);
1458 }
1459}
1460
1461impl<'tcx> crate::MirPass<'tcx> for StateTransform {
1462 #[instrument(level = "debug", skip(self, tcx, body), ret)]
1463 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
1464 debug!(def_id = ?body.source.def_id());
1465
1466 let Some(old_yield_ty) = body.yield_ty() else {
1467 return;
1469 };
1470 tracing::trace!(def_id = ?body.source.def_id());
1471
1472 let old_ret_ty = body.return_ty();
1473
1474 assert!(body.coroutine_drop().is_none() && body.coroutine_drop_async().is_none());
1475
1476 if let Some(dumper) = MirDumper::new(tcx, "coroutine_before", body) {
1477 dumper.dump_mir(body);
1478 }
1479
1480 let coroutine_ty = body.local_decls.raw[1].ty;
1482 let coroutine_kind = body.coroutine_kind().unwrap();
1483
1484 let ty::Coroutine(_, args) = coroutine_ty.kind() else {
1486 tcx.dcx().span_bug(body.span, format!("unexpected coroutine type {coroutine_ty}"));
1487 };
1488 let discr_ty = args.as_coroutine().discr_ty(tcx);
1489
1490 let new_ret_ty = match coroutine_kind {
1491 CoroutineKind::Desugared(CoroutineDesugaring::Async, _) => {
1492 let poll_did = tcx.require_lang_item(LangItem::Poll, body.span);
1494 let poll_adt_ref = tcx.adt_def(poll_did);
1495 let poll_args = tcx.mk_args(&[old_ret_ty.into()]);
1496 Ty::new_adt(tcx, poll_adt_ref, poll_args)
1497 }
1498 CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
1499 let option_did = tcx.require_lang_item(LangItem::Option, body.span);
1501 let option_adt_ref = tcx.adt_def(option_did);
1502 let option_args = tcx.mk_args(&[old_yield_ty.into()]);
1503 Ty::new_adt(tcx, option_adt_ref, option_args)
1504 }
1505 CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => {
1506 old_yield_ty
1508 }
1509 CoroutineKind::Coroutine(_) => {
1510 let state_did = tcx.require_lang_item(LangItem::CoroutineState, body.span);
1512 let state_adt_ref = tcx.adt_def(state_did);
1513 let state_args = tcx.mk_args(&[old_yield_ty.into(), old_ret_ty.into()]);
1514 Ty::new_adt(tcx, state_adt_ref, state_args)
1515 }
1516 };
1517
1518 let has_async_drops = matches!(
1523 coroutine_kind,
1524 CoroutineKind::Desugared(CoroutineDesugaring::Async | CoroutineDesugaring::AsyncGen, _)
1525 ) && has_expandable_async_drops(tcx, body, coroutine_ty);
1526
1527 if matches!(
1529 coroutine_kind,
1530 CoroutineKind::Desugared(CoroutineDesugaring::Async | CoroutineDesugaring::AsyncGen, _)
1531 ) {
1532 let context_mut_ref = transform_async_context(tcx, body);
1533 expand_async_drops(tcx, body, context_mut_ref, coroutine_kind, coroutine_ty);
1534
1535 if let Some(dumper) = MirDumper::new(tcx, "coroutine_async_drop_expand", body) {
1536 dumper.dump_mir(body);
1537 }
1538 } else {
1539 cleanup_async_drops(body);
1540 }
1541
1542 let always_live_locals = always_storage_live_locals(body);
1543 let movable = coroutine_kind.movability() == hir::Movability::Movable;
1544 let liveness_info =
1545 locals_live_across_suspend_points(tcx, body, &always_live_locals, movable);
1546
1547 if tcx.sess.opts.unstable_opts.validate_mir {
1548 let mut vis = EnsureCoroutineFieldAssignmentsNeverAlias {
1549 assigned_local: None,
1550 saved_locals: &liveness_info.saved_locals,
1551 storage_conflicts: &liveness_info.storage_conflicts,
1552 };
1553
1554 vis.visit_body(body);
1555 }
1556
1557 let (remap, layout, storage_liveness) = compute_layout(liveness_info, body);
1561
1562 let can_return = can_return(tcx, body, body.typing_env(tcx));
1563
1564 let new_ret_local = body.local_decls.push(LocalDecl::new(new_ret_ty, body.span));
1567 tracing::trace!(?new_ret_local);
1568
1569 let mut transform = TransformVisitor {
1575 tcx,
1576 coroutine_kind,
1577 remap,
1578 storage_liveness,
1579 always_live_locals,
1580 suspension_points: Vec::new(),
1581 discr_ty,
1582 new_ret_local,
1583 old_ret_ty,
1584 old_yield_ty,
1585 };
1586 transform.visit_body(body);
1587
1588 transform.replace_local(RETURN_PLACE, new_ret_local, body);
1590
1591 let source_info = SourceInfo::outermost(body.span);
1594 let args_iter = body.args_iter();
1595 body.basic_blocks.as_mut()[START_BLOCK].statements.splice(
1596 0..0,
1597 args_iter.filter_map(|local| {
1598 let (ty, variant_index, idx) = transform.remap[local]?;
1599 let lhs = transform.make_field(variant_index, idx, ty);
1600 let rhs = Rvalue::Use(Operand::Move(local.into()), WithRetag::Yes);
1601 let assign = StatementKind::Assign(Box::new((lhs, rhs)));
1602 Some(Statement::new(source_info, assign))
1603 }),
1604 );
1605
1606 body.arg_count = 2; body.spread_arg = None;
1609
1610 if matches!(coroutine_kind, CoroutineKind::Desugared(CoroutineDesugaring::Gen, _)) {
1612 transform_gen_context(body);
1613 }
1614
1615 for var in &mut body.var_debug_info {
1619 var.argument_index = None;
1620 }
1621
1622 body.coroutine.as_mut().unwrap().yield_ty = None;
1623 body.coroutine.as_mut().unwrap().resume_ty = None;
1624 body.coroutine.as_mut().unwrap().coroutine_layout = Some(layout);
1625
1626 let drop_clean = insert_clean_drop(tcx, body, has_async_drops);
1634
1635 if let Some(dumper) = MirDumper::new(tcx, "coroutine_pre-elab", body) {
1636 dumper.dump_mir(body);
1637 }
1638
1639 elaborate_coroutine_drops(tcx, body);
1643
1644 if let Some(dumper) = MirDumper::new(tcx, "coroutine_post-transform", body) {
1645 dumper.dump_mir(body);
1646 }
1647
1648 let can_unwind = can_unwind(tcx, body);
1649
1650 if has_async_drops {
1652 let mut drop_shim =
1654 create_coroutine_drop_shim_async(tcx, &transform, body, drop_clean, can_unwind);
1655 deref_finder(tcx, &mut drop_shim, false);
1657 body.coroutine.as_mut().unwrap().coroutine_drop_async = Some(drop_shim);
1658 } else {
1659 let mut drop_shim =
1661 create_coroutine_drop_shim(tcx, &transform, coroutine_ty, body, drop_clean);
1662 deref_finder(tcx, &mut drop_shim, false);
1664 body.coroutine.as_mut().unwrap().coroutine_drop = Some(drop_shim);
1665
1666 let mut proxy_shim = create_coroutine_drop_shim_proxy_async(tcx, body);
1668 deref_finder(tcx, &mut proxy_shim, false);
1669 body.coroutine.as_mut().unwrap().coroutine_drop_proxy_async = Some(proxy_shim);
1670 }
1671
1672 create_coroutine_resume_function(tcx, transform, body, can_return, can_unwind);
1674
1675 deref_finder(tcx, body, false);
1677 }
1678
1679 fn is_required(&self) -> bool {
1680 true
1681 }
1682}
1683
1684struct EnsureCoroutineFieldAssignmentsNeverAlias<'a> {
1697 saved_locals: &'a CoroutineSavedLocals,
1698 storage_conflicts: &'a BitMatrix<CoroutineSavedLocal, CoroutineSavedLocal>,
1699 assigned_local: Option<CoroutineSavedLocal>,
1700}
1701
1702impl EnsureCoroutineFieldAssignmentsNeverAlias<'_> {
1703 fn saved_local_for_direct_place(&self, place: Place<'_>) -> Option<CoroutineSavedLocal> {
1704 if place.is_indirect() {
1705 return None;
1706 }
1707
1708 self.saved_locals.get(place.local)
1709 }
1710
1711 fn check_assigned_place(&mut self, place: Place<'_>, f: impl FnOnce(&mut Self)) {
1712 if let Some(assigned_local) = self.saved_local_for_direct_place(place) {
1713 assert!(self.assigned_local.is_none(), "`check_assigned_place` must not recurse");
1714
1715 self.assigned_local = Some(assigned_local);
1716 f(self);
1717 self.assigned_local = None;
1718 }
1719 }
1720}
1721
1722impl<'tcx> Visitor<'tcx> for EnsureCoroutineFieldAssignmentsNeverAlias<'_> {
1723 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
1724 let Some(lhs) = self.assigned_local else {
1725 assert!(!context.is_use());
1730 return;
1731 };
1732
1733 let Some(rhs) = self.saved_local_for_direct_place(*place) else { return };
1734
1735 if !self.storage_conflicts.contains(lhs, rhs) {
1736 bug!(
1737 "Assignment between coroutine saved locals whose storage is not \
1738 marked as conflicting: {:?}: {:?} = {:?}",
1739 location,
1740 lhs,
1741 rhs,
1742 );
1743 }
1744 }
1745
1746 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
1747 match &statement.kind {
1748 StatementKind::Assign((lhs, rhs)) => {
1749 self.check_assigned_place(*lhs, |this| this.visit_rvalue(rhs, location));
1750 }
1751
1752 StatementKind::FakeRead(..)
1753 | StatementKind::SetDiscriminant { .. }
1754 | StatementKind::StorageLive(_)
1755 | StatementKind::StorageDead(_)
1756 | StatementKind::AscribeUserType(..)
1757 | StatementKind::PlaceMention(..)
1758 | StatementKind::Coverage(..)
1759 | StatementKind::Intrinsic(..)
1760 | StatementKind::ConstEvalCounter
1761 | StatementKind::BackwardIncompatibleDropHint { .. }
1762 | StatementKind::Nop => {}
1763 }
1764 }
1765
1766 fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
1767 match &terminator.kind {
1770 TerminatorKind::Call {
1771 func,
1772 args,
1773 destination,
1774 target: Some(_),
1775 unwind: _,
1776 call_source: _,
1777 fn_span: _,
1778 } => {
1779 self.check_assigned_place(*destination, |this| {
1780 this.visit_operand(func, location);
1781 for arg in args {
1782 this.visit_operand(&arg.node, location);
1783 }
1784 });
1785 }
1786
1787 TerminatorKind::Yield { value, resume: _, resume_arg, drop: _ } => {
1788 self.check_assigned_place(*resume_arg, |this| this.visit_operand(value, location));
1789 }
1790
1791 TerminatorKind::InlineAsm { .. } => {}
1793
1794 TerminatorKind::Call { .. }
1795 | TerminatorKind::Goto { .. }
1796 | TerminatorKind::SwitchInt { .. }
1797 | TerminatorKind::UnwindResume
1798 | TerminatorKind::UnwindTerminate(_)
1799 | TerminatorKind::Return
1800 | TerminatorKind::TailCall { .. }
1801 | TerminatorKind::Unreachable
1802 | TerminatorKind::Drop { .. }
1803 | TerminatorKind::Assert { .. }
1804 | TerminatorKind::CoroutineDrop
1805 | TerminatorKind::FalseEdge { .. }
1806 | TerminatorKind::FalseUnwind { .. } => {}
1807 }
1808 }
1809}
1810
1811fn check_suspend_tys<'tcx>(tcx: TyCtxt<'tcx>, layout: &CoroutineLayout<'tcx>, body: &Body<'tcx>) {
1812 let mut linted_tys = FxHashSet::default();
1813
1814 for (variant, yield_source_info) in
1815 layout.variant_fields.iter().zip(&layout.variant_source_info)
1816 {
1817 debug!(?variant);
1818 for &local in variant {
1819 let decl = &layout.field_tys[local];
1820 debug!(?decl);
1821
1822 if !decl.ignore_for_traits && linted_tys.insert(decl.ty) {
1823 let Some(hir_id) = decl.source_info.scope.lint_root(&body.source_scopes) else {
1824 continue;
1825 };
1826
1827 check_must_not_suspend_ty(
1828 tcx,
1829 decl.ty,
1830 hir_id,
1831 SuspendCheckData {
1832 source_span: decl.source_info.span,
1833 yield_span: yield_source_info.span,
1834 plural_len: 1,
1835 ..Default::default()
1836 },
1837 );
1838 }
1839 }
1840 }
1841}
1842
1843#[derive(Default)]
1844struct SuspendCheckData<'a> {
1845 source_span: Span,
1846 yield_span: Span,
1847 descr_pre: &'a str,
1848 descr_post: &'a str,
1849 plural_len: usize,
1850}
1851
1852fn check_must_not_suspend_ty<'tcx>(
1859 tcx: TyCtxt<'tcx>,
1860 ty: Ty<'tcx>,
1861 hir_id: hir::HirId,
1862 data: SuspendCheckData<'_>,
1863) -> bool {
1864 if ty.is_unit() {
1865 return false;
1866 }
1867
1868 let plural_suffix = pluralize!(data.plural_len);
1869
1870 debug!("Checking must_not_suspend for {}", ty);
1871
1872 match *ty.kind() {
1873 ty::Adt(_, args) if ty.is_box() => {
1874 let boxed_ty = args.type_at(0);
1875 let allocator_ty = args.type_at(1);
1876 check_must_not_suspend_ty(
1877 tcx,
1878 boxed_ty,
1879 hir_id,
1880 SuspendCheckData { descr_pre: &format!("{}boxed ", data.descr_pre), ..data },
1881 ) || check_must_not_suspend_ty(
1882 tcx,
1883 allocator_ty,
1884 hir_id,
1885 SuspendCheckData { descr_pre: &format!("{}allocator ", data.descr_pre), ..data },
1886 )
1887 }
1888 ty::Adt(def, _) if def.repr().scalable() => {
1894 tcx.dcx()
1895 .span_err(data.source_span, "scalable vectors cannot be held over await points");
1896 true
1897 }
1898 ty::Adt(def, _) => check_must_not_suspend_def(tcx, def.did(), hir_id, data),
1899 ty::Alias(ty::AliasTy { kind: ty::Opaque { def_id: def }, .. }) => {
1901 let mut has_emitted = false;
1902 for &(predicate, _) in tcx.explicit_item_bounds(def).skip_binder() {
1903 if let ty::ClauseKind::Trait(ref poly_trait_predicate) =
1905 predicate.kind().skip_binder()
1906 {
1907 let def_id = poly_trait_predicate.trait_ref.def_id;
1908 let descr_pre = &format!("{}implementer{} of ", data.descr_pre, plural_suffix);
1909 if check_must_not_suspend_def(
1910 tcx,
1911 def_id,
1912 hir_id,
1913 SuspendCheckData { descr_pre, ..data },
1914 ) {
1915 has_emitted = true;
1916 break;
1917 }
1918 }
1919 }
1920 has_emitted
1921 }
1922 ty::Dynamic(binder, _) => {
1923 let mut has_emitted = false;
1924 for predicate in binder.iter() {
1925 if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate.skip_binder() {
1926 let def_id = trait_ref.def_id;
1927 let descr_post = &format!(" trait object{}{}", plural_suffix, data.descr_post);
1928 if check_must_not_suspend_def(
1929 tcx,
1930 def_id,
1931 hir_id,
1932 SuspendCheckData { descr_post, ..data },
1933 ) {
1934 has_emitted = true;
1935 break;
1936 }
1937 }
1938 }
1939 has_emitted
1940 }
1941 ty::Tuple(fields) => {
1942 let mut has_emitted = false;
1943 for (i, ty) in fields.iter().enumerate() {
1944 let descr_post = &format!(" in tuple element {i}");
1945 if check_must_not_suspend_ty(
1946 tcx,
1947 ty,
1948 hir_id,
1949 SuspendCheckData { descr_post, ..data },
1950 ) {
1951 has_emitted = true;
1952 }
1953 }
1954 has_emitted
1955 }
1956 ty::Array(ty, len) => {
1957 let descr_pre = &format!("{}array{} of ", data.descr_pre, plural_suffix);
1958 check_must_not_suspend_ty(
1959 tcx,
1960 ty,
1961 hir_id,
1962 SuspendCheckData {
1963 descr_pre,
1964 plural_len: len.try_to_target_usize(tcx).unwrap_or(0) as usize + 1,
1966 ..data
1967 },
1968 )
1969 }
1970 ty::Ref(_region, ty, _mutability) => {
1973 let descr_pre = &format!("{}reference{} to ", data.descr_pre, plural_suffix);
1974 check_must_not_suspend_ty(tcx, ty, hir_id, SuspendCheckData { descr_pre, ..data })
1975 }
1976 _ => false,
1977 }
1978}
1979
1980fn check_must_not_suspend_def(
1981 tcx: TyCtxt<'_>,
1982 def_id: DefId,
1983 hir_id: hir::HirId,
1984 data: SuspendCheckData<'_>,
1985) -> bool {
1986 if let Some(reason_str) = find_attr!(tcx, def_id, MustNotSupend {reason} => reason) {
1987 let reason =
1988 reason_str.map(|s| errors::MustNotSuspendReason { span: data.source_span, reason: s });
1989 tcx.emit_node_span_lint(
1990 rustc_session::lint::builtin::MUST_NOT_SUSPEND,
1991 hir_id,
1992 data.source_span,
1993 errors::MustNotSupend {
1994 tcx,
1995 yield_sp: data.yield_span,
1996 reason,
1997 src_sp: data.source_span,
1998 pre: data.descr_pre,
1999 def_id,
2000 post: data.descr_post,
2001 },
2002 );
2003
2004 true
2005 } else {
2006 false
2007 }
2008}