1mod by_move_body;
54mod drop;
55mod layout;
56
57pub(super) use by_move_body::coroutine_by_move_body_def_id;
58use drop::{
59 create_coroutine_drop_shim, create_coroutine_drop_shim_async,
60 create_coroutine_drop_shim_proxy_async, elaborate_coroutine_drops, has_async_drops,
61 insert_clean_drop,
62};
63pub(super) use layout::mir_coroutine_witnesses;
64use layout::{CoroutineSavedLocals, compute_layout, locals_live_across_suspend_points};
65use rustc_abi::{FieldIdx, VariantIdx};
66use rustc_data_structures::thin_vec::ThinVec;
67use rustc_hir::lang_items::LangItem;
68use rustc_hir::{self as hir, CoroutineDesugaring, CoroutineKind};
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::{
74 self, CoroutineArgs, CoroutineArgsExt, GenericArgsRef, InstanceKind, ShimKind, Ty, TyCtxt,
75};
76use rustc_middle::{bug, span_bug};
77use rustc_mir_dataflow::impls::always_storage_live_locals;
78use rustc_span::def_id::DefId;
79use tracing::{debug, instrument};
80
81use crate::deref_separator::deref_finder;
82use crate::patch::MirPatch;
83use crate::{abort_unwinding_calls, pass_manager as pm, simplify};
84
85pub(super) struct StateTransform;
86
87struct RenameLocalVisitor<'tcx> {
88 from: Local,
89 to: Local,
90 tcx: TyCtxt<'tcx>,
91}
92
93impl<'tcx> MutVisitor<'tcx> for RenameLocalVisitor<'tcx> {
94 fn tcx(&self) -> TyCtxt<'tcx> {
95 self.tcx
96 }
97
98 fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
99 if *local == self.from {
100 *local = self.to;
101 } else if *local == self.to {
102 *local = self.from;
103 }
104 }
105
106 fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, location: Location) {
107 match terminator.kind {
108 TerminatorKind::Return => {
109 }
112 _ => self.super_terminator(terminator, location),
113 }
114 }
115}
116
117struct SelfArgVisitor<'tcx> {
118 tcx: TyCtxt<'tcx>,
119 new_base: Place<'tcx>,
120}
121
122impl<'tcx> SelfArgVisitor<'tcx> {
123 fn new(tcx: TyCtxt<'tcx>, new_base: Place<'tcx>) -> Self {
124 Self { tcx, new_base }
125 }
126}
127
128impl<'tcx> MutVisitor<'tcx> for SelfArgVisitor<'tcx> {
129 fn tcx(&self) -> TyCtxt<'tcx> {
130 self.tcx
131 }
132
133 fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
134 assert_ne!(*local, SELF_ARG);
135 }
136
137 fn visit_place(&mut self, place: &mut Place<'tcx>, _: PlaceContext, _: Location) {
138 if place.local == SELF_ARG {
139 replace_base(place, self.new_base, self.tcx);
140 }
141
142 for elem in place.projection.iter() {
143 if let PlaceElem::Index(local) = elem {
144 assert_ne!(local, SELF_ARG);
145 }
146 }
147 }
148}
149
150#[tracing::instrument(level = "trace", skip(tcx))]
151fn replace_base<'tcx>(place: &mut Place<'tcx>, new_base: Place<'tcx>, tcx: TyCtxt<'tcx>) {
152 place.local = new_base.local;
153
154 let mut new_projection = new_base.projection.to_vec();
155 new_projection.append(&mut place.projection.to_vec());
156
157 place.projection = tcx.mk_place_elems(&new_projection);
158 tracing::trace!(?place);
159}
160
161const SELF_ARG: Local = Local::arg(0);
162pub(crate) const CTX_ARG: Local = Local::arg(1);
163
164struct SuspensionPoint<'tcx> {
166 state: usize,
168 resume: BasicBlock,
170 resume_arg: Place<'tcx>,
172 drop: Option<BasicBlock>,
174 storage_liveness: GrowableBitSet<Local>,
176}
177
178struct TransformVisitor<'tcx> {
179 tcx: TyCtxt<'tcx>,
180 coroutine_kind: hir::CoroutineKind,
181
182 discr_ty: Ty<'tcx>,
184
185 remap: IndexVec<Local, Option<(Ty<'tcx>, VariantIdx, FieldIdx)>>,
187
188 storage_liveness: IndexVec<BasicBlock, Option<DenseBitSet<Local>>>,
190
191 suspension_points: Vec<SuspensionPoint<'tcx>>,
193
194 always_live_locals: DenseBitSet<Local>,
196
197 new_ret_local: Local,
199
200 old_yield_ty: Ty<'tcx>,
201
202 old_ret_ty: Ty<'tcx>,
203
204 patch: Option<MirPatch<'tcx>>,
205}
206
207impl<'tcx> TransformVisitor<'tcx> {
208 fn insert_none_ret_block(&self, body: &mut Body<'tcx>) -> BasicBlock {
209 let block = body.basic_blocks.next_index();
210 let source_info = SourceInfo::outermost(body.span);
211
212 let none_value = match self.coroutine_kind {
213 CoroutineKind::Desugared(CoroutineDesugaring::Async, _) => {
214 span_bug!(body.span, "`Future`s are not fused inherently")
215 }
216 CoroutineKind::Coroutine(_) => span_bug!(body.span, "`Coroutine`s cannot be fused"),
217 CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
219 let option_def_id = self.tcx.require_lang_item(LangItem::Option, body.span);
220 make_aggregate_adt(
221 option_def_id,
222 VariantIdx::ZERO,
223 self.tcx.mk_args(&[self.old_yield_ty.into()]),
224 IndexVec::new(),
225 )
226 }
227 CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => {
229 let ty::Adt(_poll_adt, args) = *self.old_yield_ty.kind() else { bug!() };
230 let ty::Adt(_option_adt, args) = *args.type_at(0).kind() else { bug!() };
231 let yield_ty = args.type_at(0);
232 Rvalue::Use(
233 Operand::Constant(Box::new(ConstOperand {
234 span: source_info.span,
235 const_: Const::Unevaluated(
236 UnevaluatedConst::new(
237 self.tcx.require_lang_item(LangItem::AsyncGenFinished, body.span),
238 self.tcx.mk_args(&[yield_ty.into()]),
239 ),
240 self.old_yield_ty,
241 ),
242 user_ty: None,
243 })),
244 WithRetag::Yes,
245 )
246 }
247 };
248
249 let statements = vec![Statement::new(
250 source_info,
251 StatementKind::Assign(Box::new((Place::return_place(), none_value))),
252 )];
253
254 body.basic_blocks_mut().push(BasicBlockData::new_stmts(
255 statements,
256 Some(Terminator {
257 source_info,
258 kind: TerminatorKind::Return,
259 attributes: ThinVec::new(),
260 }),
261 false,
262 ));
263
264 block
265 }
266
267 #[tracing::instrument(level = "trace", skip(self, statements))]
273 fn make_state(
274 &self,
275 val: Operand<'tcx>,
276 source_info: SourceInfo,
277 is_return: bool,
278 statements: &mut Vec<Statement<'tcx>>,
279 ) {
280 const ZERO: VariantIdx = VariantIdx::ZERO;
281 const ONE: VariantIdx = VariantIdx::from_usize(1);
282 let rvalue = match self.coroutine_kind {
283 CoroutineKind::Desugared(CoroutineDesugaring::Async, _) => {
284 let poll_def_id = self.tcx.require_lang_item(LangItem::Poll, source_info.span);
285 let args = self.tcx.mk_args(&[self.old_ret_ty.into()]);
286 let (variant_idx, operands) = if is_return {
287 (ZERO, indexvec![val]) } else {
289 (ONE, IndexVec::new()) };
291 make_aggregate_adt(poll_def_id, variant_idx, args, operands)
292 }
293 CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
294 let option_def_id = self.tcx.require_lang_item(LangItem::Option, source_info.span);
295 let args = self.tcx.mk_args(&[self.old_yield_ty.into()]);
296 let (variant_idx, operands) = if is_return {
297 (ZERO, IndexVec::new()) } else {
299 (ONE, indexvec![val]) };
301 make_aggregate_adt(option_def_id, variant_idx, args, operands)
302 }
303 CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => {
304 if is_return {
305 let ty::Adt(_poll_adt, args) = *self.old_yield_ty.kind() else { bug!() };
306 let ty::Adt(_option_adt, args) = *args.type_at(0).kind() else { bug!() };
307 let yield_ty = args.type_at(0);
308 Rvalue::Use(
309 Operand::Constant(Box::new(ConstOperand {
310 span: source_info.span,
311 const_: Const::Unevaluated(
312 UnevaluatedConst::new(
313 self.tcx.require_lang_item(
314 LangItem::AsyncGenFinished,
315 source_info.span,
316 ),
317 self.tcx.mk_args(&[yield_ty.into()]),
318 ),
319 self.old_yield_ty,
320 ),
321 user_ty: None,
322 })),
323 WithRetag::Yes,
324 )
325 } else {
326 Rvalue::Use(val, WithRetag::Yes)
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 if let Some(new_projection) = self.process_projection(&place.projection, location) {
420 place.projection = self.tcx.mk_place_elems(&new_projection);
421 }
422 }
423
424 fn process_projection_elem(
425 &mut self,
426 elem: PlaceElem<'tcx>,
427 location: Location,
428 ) -> Option<PlaceElem<'tcx>> {
429 match elem {
430 PlaceElem::Index(local) => {
431 if let Some(&Some((ty, variant, idx))) = self.remap.get(local) {
432 let field = self.make_field(variant, idx, ty);
443 self.patch.as_mut().unwrap().add_assign(
444 location,
445 Place::from(local),
446 Rvalue::Use(Operand::Copy(field), WithRetag::No),
447 );
448 }
449 None
450 }
451 PlaceElem::Field(..)
452 | PlaceElem::OpaqueCast(..)
453 | PlaceElem::UnwrapUnsafeBinder(..)
454 | PlaceElem::Deref
455 | PlaceElem::ConstantIndex { .. }
456 | PlaceElem::Subslice { .. }
457 | PlaceElem::Downcast(..) => None,
458 }
459 }
460
461 #[tracing::instrument(level = "trace", skip(self, stmt), ret)]
462 fn visit_statement(&mut self, stmt: &mut Statement<'tcx>, location: Location) {
463 if let StatementKind::StorageLive(l) | StatementKind::StorageDead(l) = stmt.kind
465 && self.remap.contains(l)
466 {
467 stmt.make_nop(true);
468 }
469 self.super_statement(stmt, location);
470 }
471
472 #[tracing::instrument(level = "trace", skip(self, term), ret)]
473 fn visit_terminator(&mut self, term: &mut Terminator<'tcx>, location: Location) {
474 if let TerminatorKind::Return = term.kind {
475 return;
478 }
479 self.super_terminator(term, location);
480 }
481
482 #[tracing::instrument(level = "trace", skip(self, data), ret)]
483 fn visit_basic_block_data(&mut self, block: BasicBlock, data: &mut BasicBlockData<'tcx>) {
484 match data.terminator().kind {
485 TerminatorKind::Return => {
486 let source_info = data.terminator().source_info;
487 self.make_state(
489 Operand::Move(Place::return_place()),
490 source_info,
491 true,
492 &mut data.statements,
493 );
494 let state = VariantIdx::new(CoroutineArgs::RETURNED);
496 data.statements.push(self.set_discr(state, source_info));
497 data.terminator_mut().kind = TerminatorKind::Return;
498 }
499 TerminatorKind::Yield { ref value, resume, mut resume_arg, drop } => {
500 let source_info = data.terminator().source_info;
501 self.make_state(value.clone(), source_info, false, &mut data.statements);
503 let state = CoroutineArgs::RESERVED_VARIANTS + self.suspension_points.len();
505
506 if let Some(&Some((ty, variant, idx))) = self.remap.get(resume_arg.local) {
509 replace_base(&mut resume_arg, self.make_field(variant, idx, ty), self.tcx);
510 }
511
512 let storage_liveness: GrowableBitSet<Local> =
513 self.storage_liveness[block].clone().unwrap().into();
514
515 for i in 0..self.always_live_locals.domain_size() {
516 let l = Local::new(i);
517 let needs_storage_dead = storage_liveness.contains(l)
518 && !self.remap.contains(l)
519 && !self.always_live_locals.contains(l);
520 if needs_storage_dead {
521 data.statements
522 .push(Statement::new(source_info, StatementKind::StorageDead(l)));
523 }
524 }
525
526 self.suspension_points.push(SuspensionPoint {
527 state,
528 resume,
529 resume_arg,
530 drop,
531 storage_liveness,
532 });
533
534 let state = VariantIdx::new(state);
535 data.statements.push(self.set_discr(state, source_info));
536 data.terminator_mut().kind = TerminatorKind::Return;
537 }
538 _ => {}
539 }
540
541 self.super_basic_block_data(block, data);
542 }
543}
544
545fn make_aggregate_adt<'tcx>(
546 def_id: DefId,
547 variant_idx: VariantIdx,
548 args: GenericArgsRef<'tcx>,
549 operands: IndexVec<FieldIdx, Operand<'tcx>>,
550) -> Rvalue<'tcx> {
551 Rvalue::Aggregate(Box::new(AggregateKind::Adt(def_id, variant_idx, args, None, None)), operands)
552}
553
554#[tracing::instrument(level = "trace", skip(tcx, body))]
555fn make_coroutine_state_argument_indirect<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
556 let coroutine_ty = body.local_decls[SELF_ARG].ty;
557
558 let ref_coroutine_ty = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, coroutine_ty);
559
560 body.local_decls[SELF_ARG].ty = ref_coroutine_ty;
562
563 SelfArgVisitor::new(tcx, tcx.mk_place_deref(SELF_ARG.into())).visit_body(body);
565}
566
567#[tracing::instrument(level = "trace", skip(tcx, body))]
568fn make_coroutine_state_argument_pinned<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
569 let coroutine_ty = body.local_decls[SELF_ARG].ty;
570
571 let ref_coroutine_ty = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, coroutine_ty);
572
573 let pin_did = tcx.require_lang_item(LangItem::Pin, body.span);
574 let pin_adt_ref = tcx.adt_def(pin_did);
575 let args = tcx.mk_args(&[ref_coroutine_ty.into()]);
576 let pin_ref_coroutine_ty = Ty::new_adt(tcx, pin_adt_ref, args);
577
578 body.local_decls[SELF_ARG].ty = pin_ref_coroutine_ty;
580
581 let unpinned_local = body.local_decls.push(LocalDecl::new(ref_coroutine_ty, body.span));
582
583 SelfArgVisitor::new(tcx, tcx.mk_place_deref(unpinned_local.into())).visit_body(body);
585
586 let source_info = SourceInfo::outermost(body.span);
587 let pin_field = tcx.mk_place_field(SELF_ARG.into(), FieldIdx::ZERO, ref_coroutine_ty);
588
589 let statements = &mut body.basic_blocks.as_mut_preserves_cfg()[START_BLOCK].statements;
590 statements.insert(
591 0,
592 Statement::new(
593 source_info,
594 StatementKind::Assign(Box::new((
595 unpinned_local.into(),
596 Rvalue::Use(Operand::Copy(pin_field), WithRetag::Yes),
597 ))),
598 ),
599 );
600}
601
602#[tracing::instrument(level = "trace", skip(tcx, body), ret)]
620fn transform_async_context<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
621 let context_mut_ref = Ty::new_task_context(tcx);
622 let resume_ty_def_id = tcx.require_lang_item(LangItem::ResumeTy, body.span);
623 let resume_nonnull_ty = tcx.instantiate_and_normalize_erasing_regions(
624 ty::GenericArgs::empty(),
625 body.typing_env(tcx),
626 tcx.type_of(tcx.adt_def(resume_ty_def_id).non_enum_variant().fields[FieldIdx::ZERO].did),
627 );
628
629 let resume_local = body.local_decls.push(LocalDecl::new(context_mut_ref, body.span));
632 body.local_decls.swap(CTX_ARG, resume_local);
633 RenameLocalVisitor { from: CTX_ARG, to: resume_local, tcx }.visit_body(body);
634
635 let source_info = SourceInfo::outermost(body.span);
639 let nonnull_local = body.local_decls.push(LocalDecl::new(resume_nonnull_ty, body.span));
640 let nonnull_rhs =
641 Rvalue::Cast(CastKind::Transmute, Operand::Move(CTX_ARG.into()), resume_nonnull_ty);
642 let nonnull_assign = StatementKind::Assign(Box::new((nonnull_local.into(), nonnull_rhs)));
643 let resume_rhs = Rvalue::Aggregate(
644 Box::new(AggregateKind::Adt(
645 resume_ty_def_id,
646 VariantIdx::ZERO,
647 ty::GenericArgs::empty(),
648 None,
649 None,
650 )),
651 indexvec![Operand::Move(nonnull_local.into())],
652 );
653 let resume_assign = StatementKind::Assign(Box::new((resume_local.into(), resume_rhs)));
654 body.basic_blocks.as_mut_preserves_cfg()[START_BLOCK].statements.splice(
655 0..0,
656 [Statement::new(source_info, nonnull_assign), Statement::new(source_info, resume_assign)],
657 );
658}
659
660fn eliminate_get_context_calls<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
665 let context_mut_ref = Ty::new_task_context(tcx);
666 let resume_ty_def_id = tcx.require_lang_item(LangItem::ResumeTy, body.span);
667 let resume_nonnull_ty = tcx.instantiate_and_normalize_erasing_regions(
668 ty::GenericArgs::empty(),
669 body.typing_env(tcx),
670 tcx.type_of(tcx.adt_def(resume_ty_def_id).non_enum_variant().fields[FieldIdx::ZERO].did),
671 );
672
673 let get_context_def_id = tcx.require_lang_item(LangItem::GetContext, body.span);
674 for bb_data in body.basic_blocks.as_mut().iter_mut() {
675 if bb_data.is_cleanup {
676 continue;
677 }
678
679 let terminator = bb_data.terminator_mut();
680 if let TerminatorKind::Call { func, args, destination, target, .. } = &terminator.kind
681 && let func_ty = func.ty(&body.local_decls, tcx)
682 && let ty::FnDef(def_id, _) = *func_ty.kind()
683 && def_id == get_context_def_id
684 && let [arg] = &**args
685 && let Some(place) = arg.node.place()
686 {
687 let arg =
688 Rvalue::Cast(
689 CastKind::Transmute,
690 Operand::Copy(place.project_deeper(
691 &[PlaceElem::Field(FieldIdx::ZERO, resume_nonnull_ty)],
692 tcx,
693 )),
694 context_mut_ref,
695 );
696 let assign = Statement::new(
697 terminator.source_info,
698 StatementKind::Assign(Box::new((*destination, arg))),
699 );
700 terminator.kind = TerminatorKind::Goto { target: target.unwrap() };
701 bb_data.statements.push(assign);
702 }
703 }
704}
705
706fn insert_switch<'tcx>(
711 body: &mut Body<'tcx>,
712 cases: Vec<(usize, BasicBlock)>,
713 transform: &TransformVisitor<'tcx>,
714 default_block: BasicBlock,
715) {
716 let (assign, discr) = transform.get_discr(body);
717
718 #[cfg(debug_assertions)]
720 for bb in body.basic_blocks.iter() {
721 for target in bb.terminator().successors() {
722 assert_ne!(target, START_BLOCK);
723 }
724 }
725
726 let former_entry = std::mem::replace(
728 &mut body.basic_blocks_mut()[START_BLOCK],
729 BasicBlockData::new_stmts(vec![assign], None, false),
730 );
731 let former_entry = body.basic_blocks_mut().push(former_entry);
732
733 let mut switch_targets =
735 SwitchTargets::new(cases.iter().map(|(i, bb)| ((*i) as u128, *bb)), default_block);
736 for bb in switch_targets.all_targets_mut() {
737 if *bb == START_BLOCK {
738 *bb = former_entry;
739 }
740 }
741
742 let switch = TerminatorKind::SwitchInt { discr: Operand::Move(discr), targets: switch_targets };
743 body.basic_blocks_mut()[START_BLOCK].terminator = Some(Terminator {
744 source_info: SourceInfo::outermost(body.span),
745 kind: switch,
746 attributes: ThinVec::new(),
747 });
748}
749
750fn insert_term_block<'tcx>(body: &mut Body<'tcx>, kind: TerminatorKind<'tcx>) -> BasicBlock {
751 let source_info = SourceInfo::outermost(body.span);
752 body.basic_blocks_mut().push(BasicBlockData::new(
753 Some(Terminator { source_info, kind, attributes: ThinVec::new() }),
754 false,
755 ))
756}
757
758fn return_poll_ready_assign<'tcx>(tcx: TyCtxt<'tcx>, source_info: SourceInfo) -> Statement<'tcx> {
759 let poll_def_id = tcx.require_lang_item(LangItem::Poll, source_info.span);
761 let args = tcx.mk_args(&[tcx.types.unit.into()]);
762 let val = Operand::Constant(Box::new(ConstOperand {
763 span: source_info.span,
764 user_ty: None,
765 const_: Const::zero_sized(tcx.types.unit),
766 }));
767 let ready_val = Rvalue::Aggregate(
768 Box::new(AggregateKind::Adt(poll_def_id, VariantIdx::from_usize(0), args, None, None)),
769 indexvec![val],
770 );
771 Statement::new(source_info, StatementKind::Assign(Box::new((Place::return_place(), ready_val))))
772}
773
774fn insert_poll_ready_block<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) -> BasicBlock {
775 let source_info = SourceInfo::outermost(body.span);
776 body.basic_blocks_mut().push(BasicBlockData::new_stmts(
777 [return_poll_ready_assign(tcx, source_info)].to_vec(),
778 Some(Terminator { source_info, kind: TerminatorKind::Return, attributes: ThinVec::new() }),
779 false,
780 ))
781}
782
783fn insert_panic_block<'tcx>(
784 tcx: TyCtxt<'tcx>,
785 body: &mut Body<'tcx>,
786 message: AssertMessage<'tcx>,
787) -> BasicBlock {
788 let assert_block = body.basic_blocks.next_index();
789 let kind = TerminatorKind::Assert {
790 cond: Operand::Constant(Box::new(ConstOperand {
791 span: body.span,
792 user_ty: None,
793 const_: Const::from_bool(tcx, false),
794 })),
795 expected: true,
796 msg: Box::new(message),
797 target: assert_block,
798 unwind: UnwindAction::Continue,
799 };
800
801 insert_term_block(body, kind)
802}
803
804fn can_return<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
805 if body.return_ty().is_privately_uninhabited(tcx, typing_env) {
807 return false;
808 }
809
810 body.basic_blocks.iter().any(|block| matches!(block.terminator().kind, TerminatorKind::Return))
812 }
814
815fn can_unwind<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>) -> bool {
816 if !tcx.sess.panic_strategy().unwinds() {
818 return false;
819 }
820
821 body.basic_blocks.iter().any(|block| block.terminator().unwind().is_some())
823}
824
825fn generate_poison_block_and_redirect_unwinds_there<'tcx>(
827 transform: &TransformVisitor<'tcx>,
828 body: &mut Body<'tcx>,
829) {
830 let source_info = SourceInfo::outermost(body.span);
831 let poison_block = body.basic_blocks_mut().push(BasicBlockData::new_stmts(
832 vec![transform.set_discr(VariantIdx::new(CoroutineArgs::POISONED), source_info)],
833 Some(Terminator {
834 source_info,
835 kind: TerminatorKind::UnwindResume,
836
837 attributes: ThinVec::new(),
838 }),
839 true,
840 ));
841
842 for (idx, block) in body.basic_blocks_mut().iter_enumerated_mut() {
843 let source_info = block.terminator().source_info;
844
845 if let TerminatorKind::UnwindResume = block.terminator().kind {
846 if idx != poison_block {
849 *block.terminator_mut() = Terminator {
850 source_info,
851 kind: TerminatorKind::Goto { target: poison_block },
852
853 attributes: ThinVec::new(),
854 };
855 }
856 } else if !block.is_cleanup
857 && let Some(unwind @ UnwindAction::Continue) = block.terminator_mut().unwind_mut()
860 {
861 *unwind = UnwindAction::Cleanup(poison_block);
862 }
863 }
864}
865
866#[tracing::instrument(level = "trace", skip(tcx, transform, body))]
867fn create_coroutine_resume_function<'tcx>(
868 tcx: TyCtxt<'tcx>,
869 transform: TransformVisitor<'tcx>,
870 body: &mut Body<'tcx>,
871 can_return: bool,
872 can_unwind: bool,
873) {
874 if can_unwind {
876 generate_poison_block_and_redirect_unwinds_there(&transform, body);
877 }
878
879 let mut cases = create_cases(body, &transform, Operation::Resume);
880
881 use rustc_middle::mir::AssertKind::{ResumedAfterPanic, ResumedAfterReturn};
882
883 cases.insert(0, (CoroutineArgs::UNRESUMED, START_BLOCK));
885
886 if can_unwind {
888 cases.insert(
889 1,
890 (
891 CoroutineArgs::POISONED,
892 insert_panic_block(tcx, body, ResumedAfterPanic(transform.coroutine_kind)),
893 ),
894 );
895 }
896
897 if can_return {
898 let block = match transform.coroutine_kind {
899 CoroutineKind::Desugared(CoroutineDesugaring::Async, _)
900 | CoroutineKind::Coroutine(_) => {
901 if tcx.is_async_drop_in_place_coroutine(body.source.def_id()) {
904 insert_poll_ready_block(tcx, body)
905 } else {
906 insert_panic_block(tcx, body, ResumedAfterReturn(transform.coroutine_kind))
907 }
908 }
909 CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _)
910 | CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
911 transform.insert_none_ret_block(body)
912 }
913 };
914 cases.insert(1, (CoroutineArgs::RETURNED, block));
915 }
916
917 let default_block = insert_term_block(body, TerminatorKind::Unreachable);
918 insert_switch(body, cases, &transform, default_block);
919
920 match transform.coroutine_kind {
921 CoroutineKind::Coroutine(_)
922 | CoroutineKind::Desugared(CoroutineDesugaring::Async | CoroutineDesugaring::AsyncGen, _) =>
923 {
924 make_coroutine_state_argument_pinned(tcx, body);
925 }
926 CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
929 make_coroutine_state_argument_indirect(tcx, body);
930 }
931 }
932
933 simplify::remove_dead_blocks(body);
936
937 pm::run_passes_no_validate(tcx, body, &[&abort_unwinding_calls::AbortUnwindingCalls], None);
938
939 deref_finder(tcx, body, false);
941
942 if transform.coroutine_kind.is_async_desugaring() {
943 transform_async_context(tcx, body);
944 }
945
946 if let Some(dumper) = MirDumper::new(tcx, "coroutine_resume", body) {
947 dumper.dump_mir(body);
948 }
949}
950
951#[derive(PartialEq, Copy, Clone, Debug)]
953enum Operation {
954 Resume,
955 Drop,
956 AsyncDrop,
957}
958
959impl Operation {
960 fn target_block(self, point: &SuspensionPoint<'_>) -> Option<BasicBlock> {
961 match self {
962 Operation::Resume => Some(point.resume),
963 Operation::Drop | Operation::AsyncDrop => point.drop,
964 }
965 }
966
967 fn resume_place<'tcx>(self, point: &SuspensionPoint<'tcx>) -> Option<Place<'tcx>> {
968 match self {
969 Operation::Resume | Operation::AsyncDrop => Some(point.resume_arg),
970 Operation::Drop => None,
971 }
972 }
973}
974
975#[tracing::instrument(level = "trace", skip(transform, body))]
976fn create_cases<'tcx>(
977 body: &mut Body<'tcx>,
978 transform: &TransformVisitor<'tcx>,
979 operation: Operation,
980) -> Vec<(usize, BasicBlock)> {
981 let source_info = SourceInfo::outermost(body.span);
982
983 transform
984 .suspension_points
985 .iter()
986 .filter_map(|point| {
987 operation.target_block(point).map(|target| {
989 let mut statements = Vec::new();
990
991 for l in body.local_decls.indices() {
993 let needs_storage_live = point.storage_liveness.contains(l)
994 && !transform.remap.contains(l)
995 && !transform.always_live_locals.contains(l);
996 if needs_storage_live {
997 statements.push(Statement::new(source_info, StatementKind::StorageLive(l)));
998 }
999 }
1000
1001 if let Some(resume_arg) = operation.resume_place(point)
1003 && resume_arg != CTX_ARG.into()
1004 {
1005 statements.push(Statement::new(
1006 source_info,
1007 StatementKind::Assign(Box::new((
1008 resume_arg,
1009 Rvalue::Use(Operand::Move(CTX_ARG.into()), WithRetag::Yes),
1010 ))),
1011 ));
1012 }
1013
1014 let block = body.basic_blocks_mut().push(BasicBlockData::new_stmts(
1016 statements,
1017 Some(Terminator {
1018 source_info,
1019 kind: TerminatorKind::Goto { target },
1020
1021 attributes: ThinVec::new(),
1022 }),
1023 false,
1024 ));
1025
1026 (point.state, block)
1027 })
1028 })
1029 .collect()
1030}
1031
1032impl<'tcx> crate::MirPass<'tcx> for StateTransform {
1033 #[instrument(level = "debug", skip(self, tcx, body), ret)]
1034 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
1035 debug!(def_id = ?body.source.def_id());
1036
1037 let Some(old_yield_ty) = body.yield_ty() else {
1038 return;
1040 };
1041 tracing::trace!(def_id = ?body.source.def_id());
1042
1043 let old_ret_ty = body.return_ty();
1044
1045 assert!(body.coroutine_drop().is_none() && body.coroutine_drop_async().is_none());
1046
1047 if let Some(dumper) = MirDumper::new(tcx, "coroutine_before", body) {
1048 dumper.dump_mir(body);
1049 }
1050
1051 let coroutine_ty = body.local_decls.raw[1].ty;
1053 let coroutine_kind = body.coroutine_kind().unwrap();
1054
1055 let ty::Coroutine(_, args) = coroutine_ty.kind() else {
1057 tcx.dcx().span_bug(body.span, format!("unexpected coroutine type {coroutine_ty}"));
1058 };
1059 let discr_ty = args.as_coroutine().discr_ty(tcx);
1060
1061 let new_ret_ty = match coroutine_kind {
1062 CoroutineKind::Desugared(CoroutineDesugaring::Async, _) => {
1063 let poll_did = tcx.require_lang_item(LangItem::Poll, body.span);
1065 let poll_adt_ref = tcx.adt_def(poll_did);
1066 let poll_args = tcx.mk_args(&[old_ret_ty.into()]);
1067 Ty::new_adt(tcx, poll_adt_ref, poll_args)
1068 }
1069 CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
1070 let option_did = tcx.require_lang_item(LangItem::Option, body.span);
1072 let option_adt_ref = tcx.adt_def(option_did);
1073 let option_args = tcx.mk_args(&[old_yield_ty.into()]);
1074 Ty::new_adt(tcx, option_adt_ref, option_args)
1075 }
1076 CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => {
1077 old_yield_ty
1079 }
1080 CoroutineKind::Coroutine(_) => {
1081 let state_did = tcx.require_lang_item(LangItem::CoroutineState, body.span);
1083 let state_adt_ref = tcx.adt_def(state_did);
1084 let state_args = tcx.mk_args(&[old_yield_ty.into(), old_ret_ty.into()]);
1085 Ty::new_adt(tcx, state_adt_ref, state_args)
1086 }
1087 };
1088
1089 let has_async_drops = has_async_drops(body);
1094
1095 if coroutine_kind.is_async_desugaring() {
1096 eliminate_get_context_calls(tcx, body);
1097 }
1098
1099 let always_live_locals = always_storage_live_locals(body);
1100 let movable = coroutine_kind.movability() == hir::Movability::Movable;
1101 let liveness_info =
1102 locals_live_across_suspend_points(tcx, body, &always_live_locals, movable);
1103
1104 if tcx.sess.opts.unstable_opts.validate_mir {
1105 let mut vis = EnsureCoroutineFieldAssignmentsNeverAlias {
1106 assigned_local: None,
1107 saved_locals: &liveness_info.saved_locals,
1108 storage_conflicts: &liveness_info.storage_conflicts,
1109 };
1110
1111 vis.visit_body(body);
1112 }
1113
1114 let (remap, layout, storage_liveness) = compute_layout(liveness_info, body);
1118
1119 let can_return = can_return(tcx, body, body.typing_env(tcx));
1120
1121 let new_ret_local = body.local_decls.push(LocalDecl::new(new_ret_ty, body.span));
1124 tracing::trace!(?new_ret_local);
1125
1126 let mut transform = TransformVisitor {
1132 tcx,
1133 coroutine_kind,
1134 remap,
1135 storage_liveness,
1136 always_live_locals,
1137 suspension_points: Vec::new(),
1138 discr_ty,
1139 new_ret_local,
1140 old_ret_ty,
1141 old_yield_ty,
1142 patch: Some(MirPatch::new(body)),
1143 };
1144 transform.visit_body(body);
1145
1146 transform.replace_local(RETURN_PLACE, new_ret_local, body);
1148
1149 let source_info = SourceInfo::outermost(body.span);
1152 let args_iter = body.args_iter();
1153 body.basic_blocks.as_mut()[START_BLOCK].statements.splice(
1154 0..0,
1155 args_iter.filter_map(|local| {
1156 let (ty, variant_index, idx) = transform.remap[local]?;
1157 let lhs = transform.make_field(variant_index, idx, ty);
1158 let rhs = Rvalue::Use(Operand::Move(local.into()), WithRetag::Yes);
1159 let assign = StatementKind::Assign(Box::new((lhs, rhs)));
1160 Some(Statement::new(source_info, assign))
1161 }),
1162 );
1163 transform.patch.take().unwrap().apply(body);
1164
1165 if matches!(coroutine_kind, CoroutineKind::Desugared(CoroutineDesugaring::Gen, _)) {
1167 body.arg_count = 1;
1168 }
1169
1170 for var in &mut body.var_debug_info {
1174 var.argument_index = None;
1175 }
1176
1177 body.coroutine.as_mut().unwrap().yield_ty = None;
1178 body.coroutine.as_mut().unwrap().resume_ty = None;
1179 body.coroutine.as_mut().unwrap().coroutine_layout = Some(layout);
1180
1181 let drop_clean = insert_clean_drop(tcx, body, has_async_drops);
1185
1186 if let Some(dumper) = MirDumper::new(tcx, "coroutine_pre-elab", body) {
1187 dumper.dump_mir(body);
1188 }
1189
1190 elaborate_coroutine_drops(tcx, body);
1194
1195 if let Some(dumper) = MirDumper::new(tcx, "coroutine_post-transform", body) {
1196 dumper.dump_mir(body);
1197 }
1198
1199 let can_unwind = can_unwind(tcx, body);
1200
1201 if has_async_drops {
1203 let drop_shim =
1205 create_coroutine_drop_shim_async(tcx, &transform, body, drop_clean, can_unwind);
1206 body.coroutine.as_mut().unwrap().coroutine_drop_async = Some(drop_shim);
1207 } else {
1208 let drop_shim =
1210 create_coroutine_drop_shim(tcx, &transform, coroutine_ty, body, drop_clean);
1211 body.coroutine.as_mut().unwrap().coroutine_drop = Some(drop_shim);
1212
1213 let proxy_shim = create_coroutine_drop_shim_proxy_async(tcx, body, coroutine_kind);
1215 body.coroutine.as_mut().unwrap().coroutine_drop_proxy_async = Some(proxy_shim);
1216 }
1217
1218 create_coroutine_resume_function(tcx, transform, body, can_return, can_unwind);
1220 }
1221
1222 fn is_required(&self) -> bool {
1223 true
1224 }
1225}
1226
1227struct EnsureCoroutineFieldAssignmentsNeverAlias<'a> {
1240 saved_locals: &'a CoroutineSavedLocals,
1241 storage_conflicts: &'a BitMatrix<CoroutineSavedLocal, CoroutineSavedLocal>,
1242 assigned_local: Option<CoroutineSavedLocal>,
1243}
1244
1245impl EnsureCoroutineFieldAssignmentsNeverAlias<'_> {
1246 fn saved_local_for_direct_place(&self, place: Place<'_>) -> Option<CoroutineSavedLocal> {
1247 if place.is_indirect() {
1248 return None;
1249 }
1250
1251 self.saved_locals.get(place.local)
1252 }
1253
1254 fn check_assigned_place(&mut self, place: Place<'_>, f: impl FnOnce(&mut Self)) {
1255 if let Some(assigned_local) = self.saved_local_for_direct_place(place) {
1256 assert!(self.assigned_local.is_none(), "`check_assigned_place` must not recurse");
1257
1258 self.assigned_local = Some(assigned_local);
1259 f(self);
1260 self.assigned_local = None;
1261 }
1262 }
1263}
1264
1265impl<'tcx> Visitor<'tcx> for EnsureCoroutineFieldAssignmentsNeverAlias<'_> {
1266 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
1267 let Some(lhs) = self.assigned_local else {
1268 assert!(!context.is_use());
1273 return;
1274 };
1275
1276 let Some(rhs) = self.saved_local_for_direct_place(*place) else { return };
1277
1278 if !self.storage_conflicts.contains(lhs, rhs) {
1279 bug!(
1280 "Assignment between coroutine saved locals whose storage is not \
1281 marked as conflicting: {:?}: {:?} = {:?}",
1282 location,
1283 lhs,
1284 rhs,
1285 );
1286 }
1287 }
1288
1289 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
1290 match &statement.kind {
1291 StatementKind::Assign((lhs, rhs)) => {
1292 self.check_assigned_place(*lhs, |this| this.visit_rvalue(rhs, location));
1293 }
1294
1295 StatementKind::FakeRead(..)
1296 | StatementKind::SetDiscriminant { .. }
1297 | StatementKind::StorageLive(_)
1298 | StatementKind::StorageDead(_)
1299 | StatementKind::AscribeUserType(..)
1300 | StatementKind::PlaceMention(..)
1301 | StatementKind::Coverage(..)
1302 | StatementKind::Intrinsic(..)
1303 | StatementKind::ConstEvalCounter
1304 | StatementKind::BackwardIncompatibleDropHint { .. }
1305 | StatementKind::Nop => {}
1306 }
1307 }
1308
1309 fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
1310 match &terminator.kind {
1313 TerminatorKind::Call {
1314 func,
1315 args,
1316 destination,
1317 target: Some(_),
1318 unwind: _,
1319 call_source: _,
1320 fn_span: _,
1321 } => {
1322 self.check_assigned_place(*destination, |this| {
1323 this.visit_operand(func, location);
1324 for arg in args {
1325 this.visit_operand(&arg.node, location);
1326 }
1327 });
1328 }
1329
1330 TerminatorKind::Yield { value, resume: _, resume_arg, drop: _ } => {
1331 self.check_assigned_place(*resume_arg, |this| this.visit_operand(value, location));
1332 }
1333
1334 TerminatorKind::InlineAsm { .. } => {}
1336
1337 TerminatorKind::Call { .. }
1338 | TerminatorKind::Goto { .. }
1339 | TerminatorKind::SwitchInt { .. }
1340 | TerminatorKind::UnwindResume
1341 | TerminatorKind::UnwindTerminate(_)
1342 | TerminatorKind::Return
1343 | TerminatorKind::TailCall { .. }
1344 | TerminatorKind::Unreachable
1345 | TerminatorKind::Drop { .. }
1346 | TerminatorKind::Assert { .. }
1347 | TerminatorKind::CoroutineDrop
1348 | TerminatorKind::FalseEdge { .. }
1349 | TerminatorKind::FalseUnwind { .. } => {}
1350 }
1351 }
1352}