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_attr_ir::lang_items::LangItem;
67use rustc_hir::{self as hir, CoroutineDesugaring, CoroutineKind};
68use rustc_index::bit_set::{BitMatrix, DenseBitSet};
69use rustc_index::{Idx, IndexVec, indexvec};
70use rustc_middle::mir::visit::{MutVisitor, MutatingUseContext, PlaceContext, Visitor};
71use rustc_middle::mir::*;
72use rustc_middle::ty::{
73 self, CoroutineArgs, CoroutineArgsExt, GenericArgs, InstanceKind, ShimKind, Ty, TyCtxt,
74};
75use rustc_mir_dataflow::impls::always_storage_live_locals;
76use rustc_span::def_id::DefId;
77use rustc_span::{bug, span_bug};
78use tracing::{debug, instrument};
79
80use crate::deref_separator::deref_finder;
81use crate::patch::MirPatch;
82use crate::{PassPolicy, abort_unwinding_calls, pass_manager as pm, simplify};
83
84pub(super) struct StateTransform;
85
86struct RenameLocalVisitor<'tcx> {
87 from: Local,
88 to: Local,
89 tcx: TyCtxt<'tcx>,
90}
91
92impl<'tcx> MutVisitor<'tcx> for RenameLocalVisitor<'tcx> {
93 fn tcx(&self) -> TyCtxt<'tcx> {
94 self.tcx
95 }
96
97 fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
98 if *local == self.from {
99 *local = self.to;
100 } else if *local == self.to {
101 *local = self.from;
102 }
103 }
104
105 fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, location: Location) {
106 match terminator.kind {
107 TerminatorKind::Return => {
108 }
111 _ => self.super_terminator(terminator, location),
112 }
113 }
114}
115
116struct SelfArgVisitor<'tcx> {
117 tcx: TyCtxt<'tcx>,
118 new_base: Place<'tcx>,
119}
120
121impl<'tcx> SelfArgVisitor<'tcx> {
122 fn new(tcx: TyCtxt<'tcx>, new_base: Place<'tcx>) -> Self {
123 Self { tcx, new_base }
124 }
125}
126
127impl<'tcx> MutVisitor<'tcx> for SelfArgVisitor<'tcx> {
128 fn tcx(&self) -> TyCtxt<'tcx> {
129 self.tcx
130 }
131
132 fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
133 assert_ne!(*local, SELF_ARG);
134 }
135
136 fn visit_place(&mut self, place: &mut Place<'tcx>, _: PlaceContext, _: Location) {
137 if place.local == SELF_ARG {
138 replace_base(place, self.new_base, self.tcx);
139 }
140
141 for elem in place.projection.iter() {
142 if let PlaceElem::Index(local) = elem {
143 assert_ne!(local, SELF_ARG);
144 }
145 }
146 }
147}
148
149#[tracing::instrument(level = "trace", skip(tcx))]
150fn replace_base<'tcx>(place: &mut Place<'tcx>, new_base: Place<'tcx>, tcx: TyCtxt<'tcx>) {
151 place.local = new_base.local;
152
153 let mut new_projection = new_base.projection.to_vec();
154 new_projection.append(&mut place.projection.to_vec());
155
156 place.projection = tcx.mk_place_elems(&new_projection);
157 tracing::trace!(?place);
158}
159
160const SELF_ARG: Local = Local::arg(0);
161pub(crate) const CTX_ARG: Local = Local::arg(1);
162
163struct SuspensionPoint<'tcx> {
165 state: usize,
167 resume: BasicBlock,
169 resume_arg: Place<'tcx>,
171 drop: Option<BasicBlock>,
173 storage_liveness: DenseBitSet<Local>,
175}
176
177struct TransformVisitor<'tcx> {
178 tcx: TyCtxt<'tcx>,
179 coroutine_kind: hir::CoroutineKind,
180
181 discr_ty: Ty<'tcx>,
183
184 remap: IndexVec<Local, Option<(Ty<'tcx>, VariantIdx, FieldIdx)>>,
186
187 storage_liveness: IndexVec<BasicBlock, Option<DenseBitSet<Local>>>,
189
190 suspension_points: Vec<SuspensionPoint<'tcx>>,
192
193 always_live_locals: DenseBitSet<Local>,
195
196 new_ret_local: Local,
198
199 old_yield_ty: Ty<'tcx>,
200
201 old_ret_ty: Ty<'tcx>,
202
203 patch: Option<MirPatch<'tcx>>,
204}
205
206impl<'tcx> TransformVisitor<'tcx> {
207 fn insert_none_ret_block(&self, body: &mut Body<'tcx>) -> BasicBlock {
208 let block = body.basic_blocks.next_index();
209 let source_info = SourceInfo::outermost(body.span);
210
211 let none_value = match self.coroutine_kind {
212 CoroutineKind::Desugared(CoroutineDesugaring::Async, _) => {
213 span_bug!(body.span, "`Future`s are not fused inherently")
214 }
215 CoroutineKind::Coroutine(_) => span_bug!(body.span, "`Coroutine`s cannot be fused"),
216 CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
218 let option_def_id = self.tcx.require_lang_item(LangItem::Option, body.span);
219 make_aggregate_adt(
220 option_def_id,
221 VariantIdx::ZERO,
222 self.tcx.mk_args(&[self.old_yield_ty.into()]),
223 IndexVec::new(),
224 )
225 }
226 CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => {
228 let ty::Adt(_poll_adt, args) = *self.old_yield_ty.kind() else { bug!() };
229 let ty::Adt(_option_adt, args) = *args.type_at(0).kind() else { bug!() };
230 let yield_ty = args.type_at(0);
231 Rvalue::Use(
232 Operand::Constant(Box::new(ConstOperand {
233 span: source_info.span,
234 const_: Const::Unevaluated(
235 UnevaluatedConst::new(
236 self.tcx.require_lang_item(LangItem::AsyncGenFinished, body.span),
237 self.tcx.mk_args(&[yield_ty.into()]),
238 ),
239 self.old_yield_ty,
240 ),
241 user_ty: None,
242 })),
243 WithRetag::Yes,
244 )
245 }
246 };
247
248 let statements = vec![Statement::new(
249 source_info,
250 StatementKind::Assign(Box::new((Place::return_place(), none_value))),
251 )];
252
253 body.basic_blocks_mut().push(BasicBlockData::new_stmts(
254 statements,
255 Some(Terminator { source_info, kind: TerminatorKind::Return }),
256 false,
257 ));
258
259 block
260 }
261
262 #[tracing::instrument(level = "trace", skip(self, statements))]
268 fn make_state(
269 &self,
270 val: Operand<'tcx>,
271 source_info: SourceInfo,
272 is_return: bool,
273 statements: &mut Vec<Statement<'tcx>>,
274 ) {
275 const ZERO: VariantIdx = VariantIdx::ZERO;
276 const ONE: VariantIdx = VariantIdx::from_usize(1);
277 let rvalue = match self.coroutine_kind {
278 CoroutineKind::Desugared(CoroutineDesugaring::Async, _) => {
279 let poll_def_id = self.tcx.require_lang_item(LangItem::Poll, source_info.span);
280 let args = self.tcx.mk_args(&[self.old_ret_ty.into()]);
281 let (variant_idx, operands) = if is_return {
282 (ZERO, indexvec![val]) } else {
284 (ONE, IndexVec::new()) };
286 make_aggregate_adt(poll_def_id, variant_idx, args, operands)
287 }
288 CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
289 let option_def_id = self.tcx.require_lang_item(LangItem::Option, source_info.span);
290 let args = self.tcx.mk_args(&[self.old_yield_ty.into()]);
291 let (variant_idx, operands) = if is_return {
292 (ZERO, IndexVec::new()) } else {
294 (ONE, indexvec![val]) };
296 make_aggregate_adt(option_def_id, variant_idx, args, operands)
297 }
298 CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => {
299 if is_return {
300 let ty::Adt(_poll_adt, args) = *self.old_yield_ty.kind() else { bug!() };
301 let ty::Adt(_option_adt, args) = *args.type_at(0).kind() else { bug!() };
302 let yield_ty = args.type_at(0);
303 Rvalue::Use(
304 Operand::Constant(Box::new(ConstOperand {
305 span: source_info.span,
306 const_: Const::Unevaluated(
307 UnevaluatedConst::new(
308 self.tcx.require_lang_item(
309 LangItem::AsyncGenFinished,
310 source_info.span,
311 ),
312 self.tcx.mk_args(&[yield_ty.into()]),
313 ),
314 self.old_yield_ty,
315 ),
316 user_ty: None,
317 })),
318 WithRetag::Yes,
319 )
320 } else {
321 Rvalue::Use(val, WithRetag::Yes)
322 }
323 }
324 CoroutineKind::Coroutine(_) => {
325 let coroutine_state_def_id =
326 self.tcx.require_lang_item(LangItem::CoroutineState, source_info.span);
327 let args = self.tcx.mk_args(&[self.old_yield_ty.into(), self.old_ret_ty.into()]);
328 let variant_idx = if is_return {
329 ONE } else {
331 ZERO };
333 make_aggregate_adt(coroutine_state_def_id, variant_idx, args, indexvec![val])
334 }
335 };
336
337 statements.push(Statement::new(
339 source_info,
340 StatementKind::Assign(Box::new((self.new_ret_local.into(), rvalue))),
341 ));
342 }
343
344 #[tracing::instrument(level = "trace", skip(self), ret)]
346 fn make_field(&self, variant_index: VariantIdx, idx: FieldIdx, ty: Ty<'tcx>) -> Place<'tcx> {
347 let self_place = Place::from(SELF_ARG);
348 let base = self.tcx.mk_place_downcast_unnamed(self_place, variant_index);
349 let mut projection = base.projection.to_vec();
350 projection.push(ProjectionElem::Field(idx, ty));
351
352 Place { local: base.local, projection: self.tcx.mk_place_elems(&projection) }
353 }
354
355 #[tracing::instrument(level = "trace", skip(self))]
357 fn set_discr(&self, state_disc: VariantIdx, source_info: SourceInfo) -> Statement<'tcx> {
358 let self_place = Place::from(SELF_ARG);
359 Statement::new(
360 source_info,
361 StatementKind::SetDiscriminant {
362 place: Box::new(self_place),
363 variant_index: state_disc,
364 },
365 )
366 }
367
368 #[tracing::instrument(level = "trace", skip(self, body))]
370 fn get_discr(&self, body: &mut Body<'tcx>) -> (Statement<'tcx>, Place<'tcx>) {
371 let temp_decl = LocalDecl::new(self.discr_ty, body.span);
372 let local_decls_len = body.local_decls.push(temp_decl);
373 let temp = Place::from(local_decls_len);
374
375 let self_place = Place::from(SELF_ARG);
376 let assign = Statement::new(
377 SourceInfo::outermost(body.span),
378 StatementKind::Assign(Box::new((temp, Rvalue::Discriminant(self_place)))),
379 );
380 (assign, temp)
381 }
382
383 #[tracing::instrument(level = "trace", skip(self, body))]
385 fn replace_local(&mut self, old_local: Local, new_local: Local, body: &mut Body<'tcx>) {
386 body.local_decls.swap(old_local, new_local);
387
388 let mut visitor = RenameLocalVisitor { from: old_local, to: new_local, tcx: self.tcx };
389 visitor.visit_body(body);
390 for suspension in &mut self.suspension_points {
391 let ctxt = PlaceContext::MutatingUse(MutatingUseContext::Yield);
392 let location = Location::START;
393 visitor.visit_place(&mut suspension.resume_arg, ctxt, location);
394 }
395 }
396}
397
398impl<'tcx> MutVisitor<'tcx> for TransformVisitor<'tcx> {
399 fn tcx(&self) -> TyCtxt<'tcx> {
400 self.tcx
401 }
402
403 #[tracing::instrument(level = "trace", skip(self), ret)]
404 fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _location: Location) {
405 assert!(!self.remap.contains(*local));
406 }
407
408 #[tracing::instrument(level = "trace", skip(self), ret)]
409 fn visit_place(&mut self, place: &mut Place<'tcx>, _: PlaceContext, location: Location) {
410 if let Some(&Some((ty, variant_index, idx))) = self.remap.get(place.local) {
412 replace_base(place, self.make_field(variant_index, idx, ty), self.tcx);
413 }
414 if let Some(new_projection) = self.process_projection(&place.projection, location) {
415 place.projection = self.tcx.mk_place_elems(&new_projection);
416 }
417 }
418
419 fn process_projection_elem(
420 &mut self,
421 elem: PlaceElem<'tcx>,
422 location: Location,
423 ) -> Option<PlaceElem<'tcx>> {
424 match elem {
425 PlaceElem::Index(local) => {
426 if let Some(&Some((ty, variant, idx))) = self.remap.get(local) {
427 let field = self.make_field(variant, idx, ty);
438 self.patch.as_mut().unwrap().add_assign(
439 location,
440 Place::from(local),
441 Rvalue::Use(Operand::Copy(field), WithRetag::No),
442 );
443 }
444 None
445 }
446 PlaceElem::Field(..)
447 | PlaceElem::OpaqueCast(..)
448 | PlaceElem::UnwrapUnsafeBinder(..)
449 | PlaceElem::Deref
450 | PlaceElem::ConstantIndex { .. }
451 | PlaceElem::Subslice { .. }
452 | PlaceElem::Downcast(..)
453 | PlaceElem::PhantomDeref => None,
454 }
455 }
456
457 #[tracing::instrument(level = "trace", skip(self, stmt), ret)]
458 fn visit_statement(&mut self, stmt: &mut Statement<'tcx>, location: Location) {
459 if let StatementKind::StorageLive(l) | StatementKind::StorageDead(l) = stmt.kind
461 && self.remap.contains(l)
462 {
463 stmt.make_nop(true);
464 }
465 self.super_statement(stmt, location);
466 }
467
468 #[tracing::instrument(level = "trace", skip(self, term), ret)]
469 fn visit_terminator(&mut self, term: &mut Terminator<'tcx>, location: Location) {
470 if let TerminatorKind::Return = term.kind {
471 return;
474 }
475 self.super_terminator(term, location);
476 }
477
478 #[tracing::instrument(level = "trace", skip(self, data), ret)]
479 fn visit_basic_block_data(&mut self, block: BasicBlock, data: &mut BasicBlockData<'tcx>) {
480 match data.terminator().kind {
481 TerminatorKind::Return => {
482 let source_info = data.terminator().source_info;
483 self.make_state(
485 Operand::Move(Place::return_place()),
486 source_info,
487 true,
488 &mut data.statements,
489 );
490 let state = VariantIdx::new(CoroutineArgs::RETURNED);
492 data.statements.push(self.set_discr(state, source_info));
493 data.terminator_mut().kind = TerminatorKind::Return;
494 }
495 TerminatorKind::Yield { ref value, resume, mut resume_arg, drop } => {
496 let source_info = data.terminator().source_info;
497 self.make_state(value.clone(), source_info, false, &mut data.statements);
499 let state = CoroutineArgs::RESERVED_VARIANTS + self.suspension_points.len();
501
502 if let Some(&Some((ty, variant, idx))) = self.remap.get(resume_arg.local) {
505 replace_base(&mut resume_arg, self.make_field(variant, idx, ty), self.tcx);
506 }
507
508 let storage_liveness: DenseBitSet<Local> =
509 self.storage_liveness[block].clone().unwrap();
510
511 for i in 0..self.always_live_locals.domain_size() {
512 let l = Local::new(i);
513 let needs_storage_dead = storage_liveness.contains(l)
514 && !self.remap.contains(l)
515 && !self.always_live_locals.contains(l);
516 if needs_storage_dead {
517 data.statements
518 .push(Statement::new(source_info, StatementKind::StorageDead(l)));
519 }
520 }
521
522 self.suspension_points.push(SuspensionPoint {
523 state,
524 resume,
525 resume_arg,
526 drop,
527 storage_liveness,
528 });
529
530 let state = VariantIdx::new(state);
531 data.statements.push(self.set_discr(state, source_info));
532 data.terminator_mut().kind = TerminatorKind::Return;
533 }
534 _ => {}
535 }
536
537 self.super_basic_block_data(block, data);
538 }
539}
540
541fn make_aggregate_adt<'tcx>(
542 def_id: DefId,
543 variant_idx: VariantIdx,
544 args: GenericArgs<'tcx>,
545 operands: IndexVec<FieldIdx, Operand<'tcx>>,
546) -> Rvalue<'tcx> {
547 Rvalue::Aggregate(Box::new(AggregateKind::Adt(def_id, variant_idx, args, None, None)), operands)
548}
549
550#[tracing::instrument(level = "trace", skip(tcx, body))]
551fn make_coroutine_state_argument_indirect<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
552 let coroutine_ty = body.local_decls[SELF_ARG].ty;
553
554 let ref_coroutine_ty = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, coroutine_ty);
555
556 body.local_decls[SELF_ARG].ty = ref_coroutine_ty;
558
559 SelfArgVisitor::new(tcx, tcx.mk_place_deref(SELF_ARG.into())).visit_body(body);
561}
562
563#[tracing::instrument(level = "trace", skip(tcx, body))]
564fn make_coroutine_state_argument_pinned<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
565 let coroutine_ty = body.local_decls[SELF_ARG].ty;
566
567 let ref_coroutine_ty = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, coroutine_ty);
568
569 let pin_did = tcx.require_lang_item(LangItem::Pin, body.span);
570 let pin_adt_ref = tcx.adt_def(pin_did);
571 let args = tcx.mk_args(&[ref_coroutine_ty.into()]);
572 let pin_ref_coroutine_ty = Ty::new_adt(tcx, pin_adt_ref, args);
573
574 body.local_decls[SELF_ARG].ty = pin_ref_coroutine_ty;
576
577 let unpinned_local = body.local_decls.push(LocalDecl::new(ref_coroutine_ty, body.span));
578
579 SelfArgVisitor::new(tcx, tcx.mk_place_deref(unpinned_local.into())).visit_body(body);
581
582 let source_info = SourceInfo::outermost(body.span);
583 let pin_field = tcx.mk_place_field(SELF_ARG.into(), FieldIdx::ZERO, ref_coroutine_ty);
584
585 let statements = &mut body.basic_blocks.as_mut_preserves_cfg()[START_BLOCK].statements;
586 statements.insert(
587 0,
588 Statement::new(
589 source_info,
590 StatementKind::Assign(Box::new((
591 unpinned_local.into(),
592 Rvalue::Use(Operand::Copy(pin_field), WithRetag::Yes),
593 ))),
594 ),
595 );
596}
597
598#[tracing::instrument(level = "trace", skip(tcx, body), ret)]
616fn transform_async_context<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
617 let context_mut_ref = Ty::new_task_context(tcx);
618 let resume_ty_def_id = tcx.require_lang_item(LangItem::ResumeTy, body.span);
619 let resume_nonnull_ty = tcx.instantiate_and_normalize_erasing_regions(
620 ty::GenericArgs::empty(),
621 body.typing_env(tcx),
622 tcx.type_of(tcx.adt_def(resume_ty_def_id).non_enum_variant().fields[FieldIdx::ZERO].did),
623 );
624
625 let resume_local = body.local_decls.push(LocalDecl::new(context_mut_ref, body.span));
628 body.local_decls.swap(CTX_ARG, resume_local);
629 RenameLocalVisitor { from: CTX_ARG, to: resume_local, tcx }.visit_body(body);
630
631 let source_info = SourceInfo::outermost(body.span);
635 let nonnull_local = body.local_decls.push(LocalDecl::new(resume_nonnull_ty, body.span));
636 let nonnull_rhs =
637 Rvalue::Cast(CastKind::Transmute, Operand::Move(CTX_ARG.into()), resume_nonnull_ty);
638 let nonnull_assign = StatementKind::Assign(Box::new((nonnull_local.into(), nonnull_rhs)));
639 let resume_rhs = Rvalue::Aggregate(
640 Box::new(AggregateKind::Adt(
641 resume_ty_def_id,
642 VariantIdx::ZERO,
643 ty::GenericArgs::empty(),
644 None,
645 None,
646 )),
647 indexvec![Operand::Move(nonnull_local.into())],
648 );
649 let resume_assign = StatementKind::Assign(Box::new((resume_local.into(), resume_rhs)));
650 body.basic_blocks.as_mut_preserves_cfg()[START_BLOCK].statements.splice(
651 0..0,
652 [Statement::new(source_info, nonnull_assign), Statement::new(source_info, resume_assign)],
653 );
654}
655
656fn eliminate_get_context_calls<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
661 let context_mut_ref = Ty::new_task_context(tcx);
662 let resume_ty_def_id = tcx.require_lang_item(LangItem::ResumeTy, body.span);
663 let resume_nonnull_ty = tcx.instantiate_and_normalize_erasing_regions(
664 ty::GenericArgs::empty(),
665 body.typing_env(tcx),
666 tcx.type_of(tcx.adt_def(resume_ty_def_id).non_enum_variant().fields[FieldIdx::ZERO].did),
667 );
668
669 let get_context_def_id = tcx.require_lang_item(LangItem::GetContext, body.span);
670 for bb_data in body.basic_blocks.as_mut().iter_mut() {
671 if bb_data.is_cleanup {
672 continue;
673 }
674
675 let terminator = bb_data.terminator_mut();
676 if let TerminatorKind::Call { func, args, destination, target, .. } = &terminator.kind
677 && let func_ty = func.ty(&body.local_decls, tcx)
678 && let ty::FnDef(def_id, _) = *func_ty.kind()
679 && def_id == get_context_def_id
680 && let [arg] = &**args
681 && let Some(place) = arg.node.place()
682 {
683 let arg =
684 Rvalue::Cast(
685 CastKind::Transmute,
686 Operand::Copy(place.project_deeper(
687 &[PlaceElem::Field(FieldIdx::ZERO, resume_nonnull_ty)],
688 tcx,
689 )),
690 context_mut_ref,
691 );
692 let assign = Statement::new(
693 terminator.source_info,
694 StatementKind::Assign(Box::new((*destination, arg))),
695 );
696 terminator.kind = TerminatorKind::goto(target.unwrap());
697 bb_data.statements.push(assign);
698 }
699 }
700}
701
702fn insert_switch<'tcx>(
707 body: &mut Body<'tcx>,
708 cases: Vec<(usize, BasicBlock)>,
709 transform: &TransformVisitor<'tcx>,
710 default_block: BasicBlock,
711) {
712 let (assign, discr) = transform.get_discr(body);
713
714 #[cfg(debug_assertions)]
716 for bb in body.basic_blocks.iter() {
717 for target in bb.terminator().successors() {
718 assert_ne!(target, START_BLOCK);
719 }
720 }
721
722 let former_entry = std::mem::replace(
724 &mut body.basic_blocks_mut()[START_BLOCK],
725 BasicBlockData::new_stmts(vec![assign], None, false),
726 );
727 let former_entry = body.basic_blocks_mut().push(former_entry);
728
729 let mut switch_targets =
731 SwitchTargets::new(cases.iter().map(|(i, bb)| ((*i) as u128, *bb)), default_block);
732 for bb in switch_targets.all_targets_mut() {
733 if *bb == START_BLOCK {
734 *bb = former_entry;
735 }
736 }
737
738 let switch = TerminatorKind::SwitchInt { discr: Operand::Move(discr), targets: switch_targets };
739 body.basic_blocks_mut()[START_BLOCK].terminator =
740 Some(Terminator { source_info: SourceInfo::outermost(body.span), kind: switch });
741}
742
743fn insert_term_block<'tcx>(body: &mut Body<'tcx>, kind: TerminatorKind<'tcx>) -> BasicBlock {
744 let source_info = SourceInfo::outermost(body.span);
745 body.basic_blocks_mut().push(BasicBlockData::new(Some(Terminator { source_info, kind }), false))
746}
747
748fn return_poll_ready_assign<'tcx>(tcx: TyCtxt<'tcx>, source_info: SourceInfo) -> Statement<'tcx> {
749 let poll_def_id = tcx.require_lang_item(LangItem::Poll, source_info.span);
751 let args = tcx.mk_args(&[tcx.types.unit.into()]);
752 let val = Operand::zero_sized_constant(tcx.types.unit, source_info.span);
753 let ready_val = Rvalue::Aggregate(
754 Box::new(AggregateKind::Adt(poll_def_id, VariantIdx::from_usize(0), args, None, None)),
755 indexvec![val],
756 );
757 Statement::new(source_info, StatementKind::Assign(Box::new((Place::return_place(), ready_val))))
758}
759
760fn insert_poll_ready_block<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) -> BasicBlock {
761 let source_info = SourceInfo::outermost(body.span);
762 body.basic_blocks_mut().push(BasicBlockData::new_stmts(
763 [return_poll_ready_assign(tcx, source_info)].to_vec(),
764 Some(Terminator { source_info, kind: TerminatorKind::Return }),
765 false,
766 ))
767}
768
769fn insert_panic_block<'tcx>(
770 tcx: TyCtxt<'tcx>,
771 body: &mut Body<'tcx>,
772 message: AssertMessage<'tcx>,
773) -> BasicBlock {
774 let assert_block = body.basic_blocks.next_index();
775 let kind = TerminatorKind::Assert {
776 cond: Operand::Constant(Box::new(ConstOperand {
777 span: body.span,
778 user_ty: None,
779 const_: Const::from_bool(tcx, false),
780 })),
781 expected: true,
782 msg: Box::new(message),
783 target: assert_block,
784 unwind: UnwindAction::Continue,
785 };
786
787 insert_term_block(body, kind)
788}
789
790fn return_poll_pending<'tcx>(
791 tcx: TyCtxt<'tcx>,
792 source_info: SourceInfo,
793 return_type: Ty<'tcx>,
794) -> Statement<'tcx> {
795 let poll_def_id = tcx.require_lang_item(LangItem::Poll, source_info.span);
797 let args = tcx.mk_args(&[return_type.into()]);
798 let pending_val = Rvalue::Aggregate(
799 Box::new(AggregateKind::Adt(poll_def_id, VariantIdx::from_usize(1), args, None, None)),
800 indexvec![],
801 );
802 Statement::new(
803 source_info,
804 StatementKind::Assign(Box::new((Place::return_place(), pending_val))),
805 )
806}
807
808fn insert_poll_pending_block<'tcx>(
809 tcx: TyCtxt<'tcx>,
810 body: &mut Body<'tcx>,
811 return_type: Ty<'tcx>,
812) -> BasicBlock {
813 let source_info = SourceInfo::outermost(body.span);
814 body.basic_blocks_mut().push(BasicBlockData::new_stmts(
815 [return_poll_pending(tcx, source_info, return_type)].to_vec(),
816 Some(Terminator { source_info, kind: TerminatorKind::Return }),
817 false,
818 ))
819}
820
821fn can_return<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
822 if body.return_ty().is_privately_uninhabited(tcx, typing_env) {
824 return false;
825 }
826
827 body.basic_blocks.iter().any(|block| matches!(block.terminator().kind, TerminatorKind::Return))
829 }
831
832fn can_unwind<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>) -> bool {
833 if !tcx.sess.panic_strategy().unwinds() {
835 return false;
836 }
837
838 body.basic_blocks.iter().any(|block| block.terminator().unwind().is_some())
840}
841
842fn generate_poison_block_and_redirect_unwinds_there<'tcx>(
844 transform: &TransformVisitor<'tcx>,
845 body: &mut Body<'tcx>,
846) {
847 let source_info = SourceInfo::outermost(body.span);
848 let poison_block = body.basic_blocks_mut().push(BasicBlockData::new_stmts(
849 vec![transform.set_discr(VariantIdx::new(CoroutineArgs::POISONED), source_info)],
850 Some(Terminator { source_info, kind: TerminatorKind::UnwindResume }),
851 true,
852 ));
853
854 for (idx, block) in body.basic_blocks_mut().iter_enumerated_mut() {
855 let source_info = block.terminator().source_info;
856
857 if let TerminatorKind::UnwindResume = block.terminator().kind {
858 if idx != poison_block {
861 *block.terminator_mut() =
862 Terminator { source_info, kind: TerminatorKind::goto(poison_block) };
863 }
864 } else if !block.is_cleanup
865 && let Some(unwind @ UnwindAction::Continue) = block.terminator_mut().unwind_mut()
868 {
869 *unwind = UnwindAction::Cleanup(poison_block);
870 }
871 }
872}
873
874#[tracing::instrument(level = "trace", skip(tcx, transform, body))]
875fn create_coroutine_resume_function<'tcx>(
876 tcx: TyCtxt<'tcx>,
877 transform: TransformVisitor<'tcx>,
878 body: &mut Body<'tcx>,
879 can_return: bool,
880 can_unwind: bool,
881) {
882 if can_unwind {
884 generate_poison_block_and_redirect_unwinds_there(&transform, body);
885 }
886
887 let mut cases = create_cases(body, &transform, Operation::Resume);
888
889 use rustc_middle::mir::AssertKind::{ResumedAfterPanic, ResumedAfterReturn};
890
891 cases.insert(0, (CoroutineArgs::UNRESUMED, START_BLOCK));
893
894 if can_unwind {
896 cases.insert(
897 1,
898 (
899 CoroutineArgs::POISONED,
900 if tcx.sess.opts.unstable_opts.async_panic {
901 insert_panic_block(tcx, body, ResumedAfterPanic(transform.coroutine_kind))
902 } else {
903 insert_poll_pending_block(tcx, body, transform.old_ret_ty)
904 },
905 ),
906 );
907 }
908
909 if can_return {
910 let block = match transform.coroutine_kind {
911 CoroutineKind::Desugared(CoroutineDesugaring::Async, _)
912 | CoroutineKind::Coroutine(_) => {
913 if tcx.is_async_drop_in_place_coroutine(body.source.def_id()) {
916 insert_poll_ready_block(tcx, body)
917 } else {
918 if tcx.sess.opts.unstable_opts.async_panic {
919 insert_panic_block(tcx, body, ResumedAfterReturn(transform.coroutine_kind))
920 } else {
921 insert_poll_pending_block(tcx, body, transform.old_ret_ty)
922 }
923 }
924 }
925 CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _)
926 | CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
927 transform.insert_none_ret_block(body)
928 }
929 };
930 cases.insert(1, (CoroutineArgs::RETURNED, block));
931 }
932
933 let default_block = insert_term_block(body, TerminatorKind::Unreachable);
934 insert_switch(body, cases, &transform, default_block);
935
936 match transform.coroutine_kind {
937 CoroutineKind::Coroutine(_)
938 | CoroutineKind::Desugared(CoroutineDesugaring::Async | CoroutineDesugaring::AsyncGen, _) =>
939 {
940 make_coroutine_state_argument_pinned(tcx, body);
941 }
942 CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
945 make_coroutine_state_argument_indirect(tcx, body);
946 }
947 }
948
949 if let CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) = transform.coroutine_kind {
952 let source_info = SourceInfo::outermost(body.span);
953 body.basic_blocks_mut()[START_BLOCK].statements.insert(
954 0,
955 Statement::new(
956 source_info,
957 StatementKind::Assign(Box::new((
958 CTX_ARG.into(),
959 Rvalue::Use(
960 Operand::zero_sized_constant(tcx.types.unit, source_info.span),
961 WithRetag::Yes,
962 ),
963 ))),
964 ),
965 );
966 }
967
968 simplify::remove_dead_blocks(body);
971
972 pm::run_passes_no_validate(tcx, body, &[&abort_unwinding_calls::AbortUnwindingCalls], None);
973
974 deref_finder(tcx, body, false);
976
977 if transform.coroutine_kind.is_async_desugaring() {
978 transform_async_context(tcx, body);
979 }
980
981 if let Some(dumper) = MirDumper::new(tcx, "coroutine_resume", body) {
982 dumper.dump_mir(body);
983 }
984}
985
986#[derive(PartialEq, Copy, Clone, Debug)]
988enum Operation {
989 Resume,
990 Drop,
991 AsyncDrop,
992}
993
994impl Operation {
995 fn target_block(self, point: &SuspensionPoint<'_>) -> Option<BasicBlock> {
996 match self {
997 Operation::Resume => Some(point.resume),
998 Operation::Drop | Operation::AsyncDrop => point.drop,
999 }
1000 }
1001
1002 fn resume_place<'tcx>(self, point: &SuspensionPoint<'tcx>) -> Option<Place<'tcx>> {
1003 match self {
1004 Operation::Resume | Operation::AsyncDrop => Some(point.resume_arg),
1005 Operation::Drop => None,
1006 }
1007 }
1008}
1009
1010#[tracing::instrument(level = "trace", skip(transform, body))]
1011fn create_cases<'tcx>(
1012 body: &mut Body<'tcx>,
1013 transform: &TransformVisitor<'tcx>,
1014 operation: Operation,
1015) -> Vec<(usize, BasicBlock)> {
1016 let source_info = SourceInfo::outermost(body.span);
1017
1018 transform
1019 .suspension_points
1020 .iter()
1021 .filter_map(|point| {
1022 operation.target_block(point).map(|target| {
1024 let mut statements = Vec::new();
1025
1026 for l in body.local_decls.indices() {
1028 let needs_storage_live = point.storage_liveness.contains_loose(l)
1029 && !transform.remap.contains(l)
1030 && !transform.always_live_locals.contains(l);
1031 if needs_storage_live {
1032 statements.push(Statement::new(source_info, StatementKind::StorageLive(l)));
1033 }
1034 }
1035
1036 if let Some(resume_arg) = operation.resume_place(point)
1038 && resume_arg != CTX_ARG.into()
1039 {
1040 statements.push(Statement::new(
1041 source_info,
1042 StatementKind::Assign(Box::new((
1043 resume_arg,
1044 Rvalue::Use(Operand::Move(CTX_ARG.into()), WithRetag::Yes),
1045 ))),
1046 ));
1047 }
1048
1049 let block = body.basic_blocks_mut().push(BasicBlockData::new_stmts(
1051 statements,
1052 Some(Terminator { source_info, kind: TerminatorKind::goto(target) }),
1053 false,
1054 ));
1055
1056 (point.state, block)
1057 })
1058 })
1059 .collect()
1060}
1061
1062impl<'tcx> crate::MirPass<'tcx> for StateTransform {
1063 #[instrument(level = "debug", skip(self, tcx, body), ret)]
1064 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
1065 debug!(def_id = ?body.source.def_id());
1066
1067 let Some(old_yield_ty) = body.yield_ty() else {
1068 return;
1070 };
1071 tracing::trace!(def_id = ?body.source.def_id());
1072
1073 let old_ret_ty = body.return_ty();
1074
1075 assert!(body.coroutine_drop().is_none() && body.coroutine_drop_async().is_none());
1076
1077 if let Some(dumper) = MirDumper::new(tcx, "coroutine_before", body) {
1078 dumper.dump_mir(body);
1079 }
1080
1081 let coroutine_ty = body.local_decls.raw[1].ty;
1083 let coroutine_kind = body.coroutine_kind().unwrap();
1084
1085 let ty::Coroutine(_, args) = coroutine_ty.kind() else {
1087 tcx.dcx().span_bug(body.span, format!("unexpected coroutine type {coroutine_ty}"));
1088 };
1089 let discr_ty = args.as_coroutine().discr_ty(tcx);
1090
1091 let new_ret_ty = match coroutine_kind {
1092 CoroutineKind::Desugared(CoroutineDesugaring::Async, _) => {
1093 let poll_did = tcx.require_lang_item(LangItem::Poll, body.span);
1095 let poll_adt_ref = tcx.adt_def(poll_did);
1096 let poll_args = tcx.mk_args(&[old_ret_ty.into()]);
1097 Ty::new_adt(tcx, poll_adt_ref, poll_args)
1098 }
1099 CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
1100 let option_did = tcx.require_lang_item(LangItem::Option, body.span);
1102 let option_adt_ref = tcx.adt_def(option_did);
1103 let option_args = tcx.mk_args(&[old_yield_ty.into()]);
1104 Ty::new_adt(tcx, option_adt_ref, option_args)
1105 }
1106 CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => {
1107 old_yield_ty
1109 }
1110 CoroutineKind::Coroutine(_) => {
1111 let state_did = tcx.require_lang_item(LangItem::CoroutineState, body.span);
1113 let state_adt_ref = tcx.adt_def(state_did);
1114 let state_args = tcx.mk_args(&[old_yield_ty.into(), old_ret_ty.into()]);
1115 Ty::new_adt(tcx, state_adt_ref, state_args)
1116 }
1117 };
1118
1119 let has_async_drops = has_async_drops(body);
1124
1125 if coroutine_kind.is_async_desugaring() {
1126 eliminate_get_context_calls(tcx, body);
1127 }
1128
1129 let always_live_locals = always_storage_live_locals(body);
1130 let movable = coroutine_kind.movability() == hir::Movability::Movable;
1131 let liveness_info =
1132 locals_live_across_suspend_points(tcx, body, &always_live_locals, movable);
1133
1134 if tcx.sess.opts.unstable_opts.validate_mir {
1135 let mut vis = EnsureCoroutineFieldAssignmentsNeverAlias {
1136 assigned_local: None,
1137 saved_locals: &liveness_info.saved_locals,
1138 storage_conflicts: &liveness_info.storage_conflicts,
1139 };
1140
1141 vis.visit_body(body);
1142 }
1143
1144 let (remap, layout, storage_liveness) = compute_layout(liveness_info, body);
1148
1149 let can_return = can_return(tcx, body, body.typing_env(tcx));
1150
1151 let new_ret_local = body.local_decls.push(LocalDecl::new(new_ret_ty, body.span));
1154 tracing::trace!(?new_ret_local);
1155
1156 let mut transform = TransformVisitor {
1162 tcx,
1163 coroutine_kind,
1164 remap,
1165 storage_liveness,
1166 always_live_locals,
1167 suspension_points: Vec::new(),
1168 discr_ty,
1169 new_ret_local,
1170 old_ret_ty,
1171 old_yield_ty,
1172 patch: Some(MirPatch::new(body)),
1173 };
1174 transform.visit_body(body);
1175
1176 transform.replace_local(RETURN_PLACE, new_ret_local, body);
1178
1179 let source_info = SourceInfo::outermost(body.span);
1182 let args_iter = body.args_iter();
1183 body.basic_blocks.as_mut()[START_BLOCK].statements.splice(
1184 0..0,
1185 args_iter.filter_map(|local| {
1186 let (ty, variant_index, idx) = transform.remap[local]?;
1187 let lhs = transform.make_field(variant_index, idx, ty);
1188 let rhs = Rvalue::Use(Operand::Move(local.into()), WithRetag::Yes);
1189 let assign = StatementKind::Assign(Box::new((lhs, rhs)));
1190 Some(Statement::new(source_info, assign))
1191 }),
1192 );
1193 transform.patch.take().unwrap().apply(body);
1194
1195 if matches!(coroutine_kind, CoroutineKind::Desugared(CoroutineDesugaring::Gen, _)) {
1197 body.arg_count = 1;
1198 }
1199
1200 for var in &mut body.var_debug_info {
1204 var.argument_index = None;
1205 }
1206
1207 body.coroutine.as_mut().unwrap().yield_ty = None;
1208 body.coroutine.as_mut().unwrap().resume_ty = None;
1209 body.coroutine.as_mut().unwrap().coroutine_layout = Some(layout);
1210
1211 let drop_clean = insert_clean_drop(tcx, body, has_async_drops);
1215
1216 if let Some(dumper) = MirDumper::new(tcx, "coroutine_pre-elab", body) {
1217 dumper.dump_mir(body);
1218 }
1219
1220 elaborate_coroutine_drops(tcx, body);
1224
1225 if let Some(dumper) = MirDumper::new(tcx, "coroutine_post-transform", body) {
1226 dumper.dump_mir(body);
1227 }
1228
1229 let can_unwind = can_unwind(tcx, body);
1230
1231 if has_async_drops {
1233 let drop_shim =
1235 create_coroutine_drop_shim_async(tcx, &transform, body, drop_clean, can_unwind);
1236 body.coroutine.as_mut().unwrap().coroutine_drop_async = Some(drop_shim);
1237 } else {
1238 let drop_shim =
1240 create_coroutine_drop_shim(tcx, &transform, coroutine_ty, body, drop_clean);
1241 body.coroutine.as_mut().unwrap().coroutine_drop = Some(drop_shim);
1242
1243 let proxy_shim = create_coroutine_drop_shim_proxy_async(tcx, body, coroutine_kind);
1245 body.coroutine.as_mut().unwrap().coroutine_drop_proxy_async = Some(proxy_shim);
1246 }
1247
1248 create_coroutine_resume_function(tcx, transform, body, can_return, can_unwind);
1250 }
1251
1252 fn policy(&self, _ctx: &crate::PassCtx<'_>) -> PassPolicy {
1253 PassPolicy::Required
1255 }
1256}
1257
1258struct EnsureCoroutineFieldAssignmentsNeverAlias<'a> {
1271 saved_locals: &'a CoroutineSavedLocals,
1272 storage_conflicts: &'a BitMatrix<CoroutineSavedLocal, CoroutineSavedLocal>,
1273 assigned_local: Option<CoroutineSavedLocal>,
1274}
1275
1276impl EnsureCoroutineFieldAssignmentsNeverAlias<'_> {
1277 fn saved_local_for_direct_place(&self, place: Place<'_>) -> Option<CoroutineSavedLocal> {
1278 if place.is_indirect() {
1279 return None;
1280 }
1281
1282 self.saved_locals.get(place.local)
1283 }
1284
1285 fn check_assigned_place(&mut self, place: Place<'_>, f: impl FnOnce(&mut Self)) {
1286 if let Some(assigned_local) = self.saved_local_for_direct_place(place) {
1287 assert!(self.assigned_local.is_none(), "`check_assigned_place` must not recurse");
1288
1289 self.assigned_local = Some(assigned_local);
1290 f(self);
1291 self.assigned_local = None;
1292 }
1293 }
1294}
1295
1296impl<'tcx> Visitor<'tcx> for EnsureCoroutineFieldAssignmentsNeverAlias<'_> {
1297 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
1298 let Some(lhs) = self.assigned_local else {
1299 assert!(!context.is_use());
1304 return;
1305 };
1306
1307 let Some(rhs) = self.saved_local_for_direct_place(*place) else { return };
1308
1309 if !self.storage_conflicts.contains(lhs, rhs) {
1310 bug!(
1311 "Assignment between coroutine saved locals whose storage is not \
1312 marked as conflicting: {:?}: {:?} = {:?}",
1313 location,
1314 lhs,
1315 rhs,
1316 );
1317 }
1318 }
1319
1320 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
1321 match &statement.kind {
1322 StatementKind::Assign((lhs, rhs)) => {
1323 self.check_assigned_place(*lhs, |this| this.visit_rvalue(rhs, location));
1324 }
1325
1326 StatementKind::FakeRead(..)
1327 | StatementKind::SetDiscriminant { .. }
1328 | StatementKind::StorageLive(_)
1329 | StatementKind::StorageDead(_)
1330 | StatementKind::AscribeUserType(..)
1331 | StatementKind::PlaceMention(..)
1332 | StatementKind::Coverage(..)
1333 | StatementKind::Intrinsic(..)
1334 | StatementKind::ConstEvalCounter
1335 | StatementKind::BackwardIncompatibleDropHint { .. }
1336 | StatementKind::Nop => {}
1337 }
1338 }
1339
1340 fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
1341 match &terminator.kind {
1344 TerminatorKind::Call {
1345 func,
1346 args,
1347 destination,
1348 target: Some(_),
1349 unwind: _,
1350 call_source: _,
1351 fn_span: _,
1352 } => {
1353 self.check_assigned_place(*destination, |this| {
1354 this.visit_operand(func, location);
1355 for arg in args {
1356 this.visit_operand(&arg.node, location);
1357 }
1358 });
1359 }
1360
1361 TerminatorKind::Yield { value, resume: _, resume_arg, drop: _ } => {
1362 self.check_assigned_place(*resume_arg, |this| this.visit_operand(value, location));
1363 }
1364
1365 TerminatorKind::InlineAsm { .. } => {}
1367
1368 TerminatorKind::Call { .. }
1369 | TerminatorKind::Goto { .. }
1370 | TerminatorKind::SwitchInt { .. }
1371 | TerminatorKind::UnwindResume
1372 | TerminatorKind::UnwindTerminate(_)
1373 | TerminatorKind::Return
1374 | TerminatorKind::TailCall { .. }
1375 | TerminatorKind::Unreachable
1376 | TerminatorKind::Drop { .. }
1377 | TerminatorKind::Assert { .. }
1378 | TerminatorKind::CoroutineDrop
1379 | TerminatorKind::FalseEdge { .. }
1380 | TerminatorKind::FalseUnwind { .. } => {}
1381 }
1382 }
1383}