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