1mod by_move_body;
54use std::{iter, ops};
55
56pub(super) use by_move_body::coroutine_by_move_body_def_id;
57use rustc_abi::{FieldIdx, VariantIdx};
58use rustc_data_structures::fx::FxHashSet;
59use rustc_errors::pluralize;
60use rustc_hir as hir;
61use rustc_hir::lang_items::LangItem;
62use rustc_hir::{CoroutineDesugaring, CoroutineKind};
63use rustc_index::bit_set::{BitMatrix, DenseBitSet, GrowableBitSet};
64use rustc_index::{Idx, IndexVec};
65use rustc_middle::mir::visit::{MutVisitor, PlaceContext, Visitor};
66use rustc_middle::mir::*;
67use rustc_middle::ty::{
68 self, CoroutineArgs, CoroutineArgsExt, GenericArgsRef, InstanceKind, Ty, TyCtxt, TypingMode,
69};
70use rustc_middle::{bug, span_bug};
71use rustc_mir_dataflow::impls::{
72 MaybeBorrowedLocals, MaybeLiveLocals, MaybeRequiresStorage, MaybeStorageLive,
73 always_storage_live_locals,
74};
75use rustc_mir_dataflow::{Analysis, Results, ResultsVisitor};
76use rustc_span::def_id::{DefId, LocalDefId};
77use rustc_span::{Span, sym};
78use rustc_target::spec::PanicStrategy;
79use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
80use rustc_trait_selection::infer::TyCtxtInferExt as _;
81use rustc_trait_selection::traits::{ObligationCause, ObligationCauseCode, ObligationCtxt};
82use tracing::{debug, instrument, trace};
83
84use crate::deref_separator::deref_finder;
85use crate::{abort_unwinding_calls, errors, pass_manager as pm, simplify};
86
87pub(super) struct StateTransform;
88
89struct RenameLocalVisitor<'tcx> {
90 from: Local,
91 to: Local,
92 tcx: TyCtxt<'tcx>,
93}
94
95impl<'tcx> MutVisitor<'tcx> for RenameLocalVisitor<'tcx> {
96 fn tcx(&self) -> TyCtxt<'tcx> {
97 self.tcx
98 }
99
100 fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
101 if *local == self.from {
102 *local = self.to;
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>, elem: ProjectionElem<Local, Ty<'tcx>>) -> Self {
124 Self { tcx, new_base: Place { local: SELF_ARG, projection: tcx.mk_place_elems(&[elem]) } }
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>, context: PlaceContext, location: Location) {
138 if place.local == SELF_ARG {
139 replace_base(place, self.new_base, self.tcx);
140 } else {
141 self.visit_local(&mut place.local, context, location);
142
143 for elem in place.projection.iter() {
144 if let PlaceElem::Index(local) = elem {
145 assert_ne!(local, SELF_ARG);
146 }
147 }
148 }
149 }
150}
151
152fn replace_base<'tcx>(place: &mut Place<'tcx>, new_base: Place<'tcx>, tcx: TyCtxt<'tcx>) {
153 place.local = new_base.local;
154
155 let mut new_projection = new_base.projection.to_vec();
156 new_projection.append(&mut place.projection.to_vec());
157
158 place.projection = tcx.mk_place_elems(&new_projection);
159}
160
161const SELF_ARG: Local = Local::from_u32(1);
162
163struct SuspensionPoint<'tcx> {
165 state: usize,
167 resume: BasicBlock,
169 resume_arg: Place<'tcx>,
171 drop: Option<BasicBlock>,
173 storage_liveness: GrowableBitSet<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 old_ret_local: Local,
198
199 old_yield_ty: Ty<'tcx>,
200
201 old_ret_ty: Ty<'tcx>,
202}
203
204impl<'tcx> TransformVisitor<'tcx> {
205 fn insert_none_ret_block(&self, body: &mut Body<'tcx>) -> BasicBlock {
206 let block = BasicBlock::new(body.basic_blocks.len());
207 let source_info = SourceInfo::outermost(body.span);
208
209 let none_value = match self.coroutine_kind {
210 CoroutineKind::Desugared(CoroutineDesugaring::Async, _) => {
211 span_bug!(body.span, "`Future`s are not fused inherently")
212 }
213 CoroutineKind::Coroutine(_) => span_bug!(body.span, "`Coroutine`s cannot be fused"),
214 CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
216 let option_def_id = self.tcx.require_lang_item(LangItem::Option, None);
217 make_aggregate_adt(
218 option_def_id,
219 VariantIdx::ZERO,
220 self.tcx.mk_args(&[self.old_yield_ty.into()]),
221 IndexVec::new(),
222 )
223 }
224 CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => {
226 let ty::Adt(_poll_adt, args) = *self.old_yield_ty.kind() else { bug!() };
227 let ty::Adt(_option_adt, args) = *args.type_at(0).kind() else { bug!() };
228 let yield_ty = args.type_at(0);
229 Rvalue::Use(Operand::Constant(Box::new(ConstOperand {
230 span: source_info.span,
231 const_: Const::Unevaluated(
232 UnevaluatedConst::new(
233 self.tcx.require_lang_item(LangItem::AsyncGenFinished, None),
234 self.tcx.mk_args(&[yield_ty.into()]),
235 ),
236 self.old_yield_ty,
237 ),
238 user_ty: None,
239 })))
240 }
241 };
242
243 let statements = vec![Statement {
244 kind: StatementKind::Assign(Box::new((Place::return_place(), none_value))),
245 source_info,
246 }];
247
248 body.basic_blocks_mut().push(BasicBlockData {
249 statements,
250 terminator: Some(Terminator { source_info, kind: TerminatorKind::Return }),
251 is_cleanup: false,
252 });
253
254 block
255 }
256
257 fn make_state(
263 &self,
264 val: Operand<'tcx>,
265 source_info: SourceInfo,
266 is_return: bool,
267 statements: &mut Vec<Statement<'tcx>>,
268 ) {
269 const ZERO: VariantIdx = VariantIdx::ZERO;
270 const ONE: VariantIdx = VariantIdx::from_usize(1);
271 let rvalue = match self.coroutine_kind {
272 CoroutineKind::Desugared(CoroutineDesugaring::Async, _) => {
273 let poll_def_id = self.tcx.require_lang_item(LangItem::Poll, None);
274 let args = self.tcx.mk_args(&[self.old_ret_ty.into()]);
275 let (variant_idx, operands) = if is_return {
276 (ZERO, IndexVec::from_raw(vec![val])) } else {
278 (ONE, IndexVec::new()) };
280 make_aggregate_adt(poll_def_id, variant_idx, args, operands)
281 }
282 CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
283 let option_def_id = self.tcx.require_lang_item(LangItem::Option, None);
284 let args = self.tcx.mk_args(&[self.old_yield_ty.into()]);
285 let (variant_idx, operands) = if is_return {
286 (ZERO, IndexVec::new()) } else {
288 (ONE, IndexVec::from_raw(vec![val])) };
290 make_aggregate_adt(option_def_id, variant_idx, args, operands)
291 }
292 CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => {
293 if is_return {
294 let ty::Adt(_poll_adt, args) = *self.old_yield_ty.kind() else { bug!() };
295 let ty::Adt(_option_adt, args) = *args.type_at(0).kind() else { bug!() };
296 let yield_ty = args.type_at(0);
297 Rvalue::Use(Operand::Constant(Box::new(ConstOperand {
298 span: source_info.span,
299 const_: Const::Unevaluated(
300 UnevaluatedConst::new(
301 self.tcx.require_lang_item(LangItem::AsyncGenFinished, None),
302 self.tcx.mk_args(&[yield_ty.into()]),
303 ),
304 self.old_yield_ty,
305 ),
306 user_ty: None,
307 })))
308 } else {
309 Rvalue::Use(val)
310 }
311 }
312 CoroutineKind::Coroutine(_) => {
313 let coroutine_state_def_id =
314 self.tcx.require_lang_item(LangItem::CoroutineState, None);
315 let args = self.tcx.mk_args(&[self.old_yield_ty.into(), self.old_ret_ty.into()]);
316 let variant_idx = if is_return {
317 ONE } else {
319 ZERO };
321 make_aggregate_adt(
322 coroutine_state_def_id,
323 variant_idx,
324 args,
325 IndexVec::from_raw(vec![val]),
326 )
327 }
328 };
329
330 statements.push(Statement {
331 kind: StatementKind::Assign(Box::new((Place::return_place(), rvalue))),
332 source_info,
333 });
334 }
335
336 fn make_field(&self, variant_index: VariantIdx, idx: FieldIdx, ty: Ty<'tcx>) -> Place<'tcx> {
338 let self_place = Place::from(SELF_ARG);
339 let base = self.tcx.mk_place_downcast_unnamed(self_place, variant_index);
340 let mut projection = base.projection.to_vec();
341 projection.push(ProjectionElem::Field(idx, ty));
342
343 Place { local: base.local, projection: self.tcx.mk_place_elems(&projection) }
344 }
345
346 fn set_discr(&self, state_disc: VariantIdx, source_info: SourceInfo) -> Statement<'tcx> {
348 let self_place = Place::from(SELF_ARG);
349 Statement {
350 source_info,
351 kind: StatementKind::SetDiscriminant {
352 place: Box::new(self_place),
353 variant_index: state_disc,
354 },
355 }
356 }
357
358 fn get_discr(&self, body: &mut Body<'tcx>) -> (Statement<'tcx>, Place<'tcx>) {
360 let temp_decl = LocalDecl::new(self.discr_ty, body.span);
361 let local_decls_len = body.local_decls.push(temp_decl);
362 let temp = Place::from(local_decls_len);
363
364 let self_place = Place::from(SELF_ARG);
365 let assign = Statement {
366 source_info: SourceInfo::outermost(body.span),
367 kind: StatementKind::Assign(Box::new((temp, Rvalue::Discriminant(self_place)))),
368 };
369 (assign, temp)
370 }
371}
372
373impl<'tcx> MutVisitor<'tcx> for TransformVisitor<'tcx> {
374 fn tcx(&self) -> TyCtxt<'tcx> {
375 self.tcx
376 }
377
378 fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
379 assert!(!self.remap.contains(*local));
380 }
381
382 fn visit_place(
383 &mut self,
384 place: &mut Place<'tcx>,
385 _context: PlaceContext,
386 _location: Location,
387 ) {
388 if let Some(&Some((ty, variant_index, idx))) = self.remap.get(place.local) {
390 replace_base(place, self.make_field(variant_index, idx, ty), self.tcx);
391 }
392 }
393
394 fn visit_basic_block_data(&mut self, block: BasicBlock, data: &mut BasicBlockData<'tcx>) {
395 data.retain_statements(|s| match s.kind {
397 StatementKind::StorageLive(l) | StatementKind::StorageDead(l) => {
398 !self.remap.contains(l)
399 }
400 _ => true,
401 });
402
403 let ret_val = match data.terminator().kind {
404 TerminatorKind::Return => {
405 Some((true, None, Operand::Move(Place::from(self.old_ret_local)), None))
406 }
407 TerminatorKind::Yield { ref value, resume, resume_arg, drop } => {
408 Some((false, Some((resume, resume_arg)), value.clone(), drop))
409 }
410 _ => None,
411 };
412
413 if let Some((is_return, resume, v, drop)) = ret_val {
414 let source_info = data.terminator().source_info;
415 self.make_state(v, source_info, is_return, &mut data.statements);
417 let state = if let Some((resume, mut resume_arg)) = resume {
418 let state = CoroutineArgs::RESERVED_VARIANTS + self.suspension_points.len();
420
421 if let Some(&Some((ty, variant, idx))) = self.remap.get(resume_arg.local) {
424 replace_base(&mut resume_arg, self.make_field(variant, idx, ty), self.tcx);
425 }
426
427 let storage_liveness: GrowableBitSet<Local> =
428 self.storage_liveness[block].clone().unwrap().into();
429
430 for i in 0..self.always_live_locals.domain_size() {
431 let l = Local::new(i);
432 let needs_storage_dead = storage_liveness.contains(l)
433 && !self.remap.contains(l)
434 && !self.always_live_locals.contains(l);
435 if needs_storage_dead {
436 data.statements
437 .push(Statement { source_info, kind: StatementKind::StorageDead(l) });
438 }
439 }
440
441 self.suspension_points.push(SuspensionPoint {
442 state,
443 resume,
444 resume_arg,
445 drop,
446 storage_liveness,
447 });
448
449 VariantIdx::new(state)
450 } else {
451 VariantIdx::new(CoroutineArgs::RETURNED) };
454 data.statements.push(self.set_discr(state, source_info));
455 data.terminator_mut().kind = TerminatorKind::Return;
456 }
457
458 self.super_basic_block_data(block, data);
459 }
460}
461
462fn make_aggregate_adt<'tcx>(
463 def_id: DefId,
464 variant_idx: VariantIdx,
465 args: GenericArgsRef<'tcx>,
466 operands: IndexVec<FieldIdx, Operand<'tcx>>,
467) -> Rvalue<'tcx> {
468 Rvalue::Aggregate(Box::new(AggregateKind::Adt(def_id, variant_idx, args, None, None)), operands)
469}
470
471fn make_coroutine_state_argument_indirect<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
472 let coroutine_ty = body.local_decls.raw[1].ty;
473
474 let ref_coroutine_ty = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, coroutine_ty);
475
476 body.local_decls.raw[1].ty = ref_coroutine_ty;
478
479 SelfArgVisitor::new(tcx, ProjectionElem::Deref).visit_body(body);
481}
482
483fn make_coroutine_state_argument_pinned<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
484 let ref_coroutine_ty = body.local_decls.raw[1].ty;
485
486 let pin_did = tcx.require_lang_item(LangItem::Pin, Some(body.span));
487 let pin_adt_ref = tcx.adt_def(pin_did);
488 let args = tcx.mk_args(&[ref_coroutine_ty.into()]);
489 let pin_ref_coroutine_ty = Ty::new_adt(tcx, pin_adt_ref, args);
490
491 body.local_decls.raw[1].ty = pin_ref_coroutine_ty;
493
494 SelfArgVisitor::new(tcx, ProjectionElem::Field(FieldIdx::ZERO, ref_coroutine_ty))
496 .visit_body(body);
497}
498
499fn replace_local<'tcx>(
506 local: Local,
507 ty: Ty<'tcx>,
508 body: &mut Body<'tcx>,
509 tcx: TyCtxt<'tcx>,
510) -> Local {
511 let new_decl = LocalDecl::new(ty, body.span);
512 let new_local = body.local_decls.push(new_decl);
513 body.local_decls.swap(local, new_local);
514
515 RenameLocalVisitor { from: local, to: new_local, tcx }.visit_body(body);
516
517 new_local
518}
519
520fn transform_async_context<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
542 let context_mut_ref = Ty::new_task_context(tcx);
543
544 replace_resume_ty_local(tcx, body, Local::new(2), context_mut_ref);
546
547 let get_context_def_id = tcx.require_lang_item(LangItem::GetContext, None);
548
549 for bb in START_BLOCK..body.basic_blocks.next_index() {
550 let bb_data = &body[bb];
551 if bb_data.is_cleanup {
552 continue;
553 }
554
555 match &bb_data.terminator().kind {
556 TerminatorKind::Call { func, .. } => {
557 let func_ty = func.ty(body, tcx);
558 if let ty::FnDef(def_id, _) = *func_ty.kind() {
559 if def_id == get_context_def_id {
560 let local = eliminate_get_context_call(&mut body[bb]);
561 replace_resume_ty_local(tcx, body, local, context_mut_ref);
562 }
563 }
564 }
565 TerminatorKind::Yield { resume_arg, .. } => {
566 replace_resume_ty_local(tcx, body, resume_arg.local, context_mut_ref);
567 }
568 _ => {}
569 }
570 }
571}
572
573fn eliminate_get_context_call<'tcx>(bb_data: &mut BasicBlockData<'tcx>) -> Local {
574 let terminator = bb_data.terminator.take().unwrap();
575 let TerminatorKind::Call { args, destination, target, .. } = terminator.kind else {
576 bug!();
577 };
578 let [arg] = *Box::try_from(args).unwrap();
579 let local = arg.node.place().unwrap().local;
580
581 let arg = Rvalue::Use(arg.node);
582 let assign = Statement {
583 source_info: terminator.source_info,
584 kind: StatementKind::Assign(Box::new((destination, arg))),
585 };
586 bb_data.statements.push(assign);
587 bb_data.terminator = Some(Terminator {
588 source_info: terminator.source_info,
589 kind: TerminatorKind::Goto { target: target.unwrap() },
590 });
591 local
592}
593
594#[cfg_attr(not(debug_assertions), allow(unused))]
595fn replace_resume_ty_local<'tcx>(
596 tcx: TyCtxt<'tcx>,
597 body: &mut Body<'tcx>,
598 local: Local,
599 context_mut_ref: Ty<'tcx>,
600) {
601 let local_ty = std::mem::replace(&mut body.local_decls[local].ty, context_mut_ref);
602 #[cfg(debug_assertions)]
605 {
606 if let ty::Adt(resume_ty_adt, _) = local_ty.kind() {
607 let expected_adt = tcx.adt_def(tcx.require_lang_item(LangItem::ResumeTy, None));
608 assert_eq!(*resume_ty_adt, expected_adt);
609 } else {
610 panic!("expected `ResumeTy`, found `{:?}`", local_ty);
611 };
612 }
613}
614
615fn transform_gen_context<'tcx>(body: &mut Body<'tcx>) {
625 body.arg_count = 1;
629}
630
631struct LivenessInfo {
632 saved_locals: CoroutineSavedLocals,
634
635 live_locals_at_suspension_points: Vec<DenseBitSet<CoroutineSavedLocal>>,
637
638 source_info_at_suspension_points: Vec<SourceInfo>,
640
641 storage_conflicts: BitMatrix<CoroutineSavedLocal, CoroutineSavedLocal>,
645
646 storage_liveness: IndexVec<BasicBlock, Option<DenseBitSet<Local>>>,
649}
650
651fn locals_live_across_suspend_points<'tcx>(
660 tcx: TyCtxt<'tcx>,
661 body: &Body<'tcx>,
662 always_live_locals: &DenseBitSet<Local>,
663 movable: bool,
664) -> LivenessInfo {
665 let mut storage_live = MaybeStorageLive::new(std::borrow::Cow::Borrowed(always_live_locals))
668 .iterate_to_fixpoint(tcx, body, None)
669 .into_results_cursor(body);
670
671 let borrowed_locals_results =
674 MaybeBorrowedLocals.iterate_to_fixpoint(tcx, body, Some("coroutine"));
675
676 let mut borrowed_locals_cursor = borrowed_locals_results.clone().into_results_cursor(body);
677
678 let mut requires_storage_results =
680 MaybeRequiresStorage::new(borrowed_locals_results.into_results_cursor(body))
681 .iterate_to_fixpoint(tcx, body, None);
682 let mut requires_storage_cursor = requires_storage_results.as_results_cursor(body);
683
684 let mut liveness =
686 MaybeLiveLocals.iterate_to_fixpoint(tcx, body, Some("coroutine")).into_results_cursor(body);
687
688 let mut storage_liveness_map = IndexVec::from_elem(None, &body.basic_blocks);
689 let mut live_locals_at_suspension_points = Vec::new();
690 let mut source_info_at_suspension_points = Vec::new();
691 let mut live_locals_at_any_suspension_point = DenseBitSet::new_empty(body.local_decls.len());
692
693 for (block, data) in body.basic_blocks.iter_enumerated() {
694 if let TerminatorKind::Yield { .. } = data.terminator().kind {
695 let loc = Location { block, statement_index: data.statements.len() };
696
697 liveness.seek_to_block_end(block);
698 let mut live_locals = liveness.get().clone();
699
700 if !movable {
701 borrowed_locals_cursor.seek_before_primary_effect(loc);
712 live_locals.union(borrowed_locals_cursor.get());
713 }
714
715 storage_live.seek_before_primary_effect(loc);
718 storage_liveness_map[block] = Some(storage_live.get().clone());
719
720 requires_storage_cursor.seek_before_primary_effect(loc);
724 live_locals.intersect(requires_storage_cursor.get());
725
726 live_locals.remove(SELF_ARG);
728
729 debug!("loc = {:?}, live_locals = {:?}", loc, live_locals);
730
731 live_locals_at_any_suspension_point.union(&live_locals);
734
735 live_locals_at_suspension_points.push(live_locals);
736 source_info_at_suspension_points.push(data.terminator().source_info);
737 }
738 }
739
740 debug!("live_locals_anywhere = {:?}", live_locals_at_any_suspension_point);
741 let saved_locals = CoroutineSavedLocals(live_locals_at_any_suspension_point);
742
743 let live_locals_at_suspension_points = live_locals_at_suspension_points
746 .iter()
747 .map(|live_here| saved_locals.renumber_bitset(live_here))
748 .collect();
749
750 let storage_conflicts = compute_storage_conflicts(
751 body,
752 &saved_locals,
753 always_live_locals.clone(),
754 requires_storage_results,
755 );
756
757 LivenessInfo {
758 saved_locals,
759 live_locals_at_suspension_points,
760 source_info_at_suspension_points,
761 storage_conflicts,
762 storage_liveness: storage_liveness_map,
763 }
764}
765
766struct CoroutineSavedLocals(DenseBitSet<Local>);
772
773impl CoroutineSavedLocals {
774 fn iter_enumerated(&self) -> impl '_ + Iterator<Item = (CoroutineSavedLocal, Local)> {
777 self.iter().enumerate().map(|(i, l)| (CoroutineSavedLocal::from(i), l))
778 }
779
780 fn renumber_bitset(&self, input: &DenseBitSet<Local>) -> DenseBitSet<CoroutineSavedLocal> {
783 assert!(self.superset(input), "{:?} not a superset of {:?}", self.0, input);
784 let mut out = DenseBitSet::new_empty(self.count());
785 for (saved_local, local) in self.iter_enumerated() {
786 if input.contains(local) {
787 out.insert(saved_local);
788 }
789 }
790 out
791 }
792
793 fn get(&self, local: Local) -> Option<CoroutineSavedLocal> {
794 if !self.contains(local) {
795 return None;
796 }
797
798 let idx = self.iter().take_while(|&l| l < local).count();
799 Some(CoroutineSavedLocal::new(idx))
800 }
801}
802
803impl ops::Deref for CoroutineSavedLocals {
804 type Target = DenseBitSet<Local>;
805
806 fn deref(&self) -> &Self::Target {
807 &self.0
808 }
809}
810
811fn compute_storage_conflicts<'mir, 'tcx>(
816 body: &'mir Body<'tcx>,
817 saved_locals: &'mir CoroutineSavedLocals,
818 always_live_locals: DenseBitSet<Local>,
819 mut requires_storage: Results<'tcx, MaybeRequiresStorage<'mir, 'tcx>>,
820) -> BitMatrix<CoroutineSavedLocal, CoroutineSavedLocal> {
821 assert_eq!(body.local_decls.len(), saved_locals.domain_size());
822
823 debug!("compute_storage_conflicts({:?})", body.span);
824 debug!("always_live = {:?}", always_live_locals);
825
826 let mut ineligible_locals = always_live_locals;
829 ineligible_locals.intersect(&**saved_locals);
830
831 let mut visitor = StorageConflictVisitor {
833 body,
834 saved_locals,
835 local_conflicts: BitMatrix::from_row_n(&ineligible_locals, body.local_decls.len()),
836 eligible_storage_live: DenseBitSet::new_empty(body.local_decls.len()),
837 };
838
839 requires_storage.visit_reachable_with(body, &mut visitor);
840
841 let local_conflicts = visitor.local_conflicts;
842
843 let mut storage_conflicts = BitMatrix::new(saved_locals.count(), saved_locals.count());
851 for (saved_local_a, local_a) in saved_locals.iter_enumerated() {
852 if ineligible_locals.contains(local_a) {
853 storage_conflicts.insert_all_into_row(saved_local_a);
855 } else {
856 for (saved_local_b, local_b) in saved_locals.iter_enumerated() {
858 if local_conflicts.contains(local_a, local_b) {
859 storage_conflicts.insert(saved_local_a, saved_local_b);
860 }
861 }
862 }
863 }
864 storage_conflicts
865}
866
867struct StorageConflictVisitor<'a, 'tcx> {
868 body: &'a Body<'tcx>,
869 saved_locals: &'a CoroutineSavedLocals,
870 local_conflicts: BitMatrix<Local, Local>,
873 eligible_storage_live: DenseBitSet<Local>,
875}
876
877impl<'a, 'tcx> ResultsVisitor<'a, 'tcx, MaybeRequiresStorage<'a, 'tcx>>
878 for StorageConflictVisitor<'a, 'tcx>
879{
880 fn visit_after_early_statement_effect(
881 &mut self,
882 _results: &mut Results<'tcx, MaybeRequiresStorage<'a, 'tcx>>,
883 state: &DenseBitSet<Local>,
884 _statement: &'a Statement<'tcx>,
885 loc: Location,
886 ) {
887 self.apply_state(state, loc);
888 }
889
890 fn visit_after_early_terminator_effect(
891 &mut self,
892 _results: &mut Results<'tcx, MaybeRequiresStorage<'a, 'tcx>>,
893 state: &DenseBitSet<Local>,
894 _terminator: &'a Terminator<'tcx>,
895 loc: Location,
896 ) {
897 self.apply_state(state, loc);
898 }
899}
900
901impl StorageConflictVisitor<'_, '_> {
902 fn apply_state(&mut self, state: &DenseBitSet<Local>, loc: Location) {
903 if let TerminatorKind::Unreachable = self.body.basic_blocks[loc.block].terminator().kind {
905 return;
906 }
907
908 self.eligible_storage_live.clone_from(state);
909 self.eligible_storage_live.intersect(&**self.saved_locals);
910
911 for local in self.eligible_storage_live.iter() {
912 self.local_conflicts.union_row_with(&self.eligible_storage_live, local);
913 }
914
915 if self.eligible_storage_live.count() > 1 {
916 trace!("at {:?}, eligible_storage_live={:?}", loc, self.eligible_storage_live);
917 }
918 }
919}
920
921fn compute_layout<'tcx>(
922 liveness: LivenessInfo,
923 body: &Body<'tcx>,
924) -> (
925 IndexVec<Local, Option<(Ty<'tcx>, VariantIdx, FieldIdx)>>,
926 CoroutineLayout<'tcx>,
927 IndexVec<BasicBlock, Option<DenseBitSet<Local>>>,
928) {
929 let LivenessInfo {
930 saved_locals,
931 live_locals_at_suspension_points,
932 source_info_at_suspension_points,
933 storage_conflicts,
934 storage_liveness,
935 } = liveness;
936
937 let mut locals = IndexVec::<CoroutineSavedLocal, _>::new();
939 let mut tys = IndexVec::<CoroutineSavedLocal, _>::new();
940 for (saved_local, local) in saved_locals.iter_enumerated() {
941 debug!("coroutine saved local {:?} => {:?}", saved_local, local);
942
943 locals.push(local);
944 let decl = &body.local_decls[local];
945 debug!(?decl);
946
947 let ignore_for_traits = match decl.local_info {
952 ClearCrossCrate::Set(box LocalInfo::StaticRef { is_thread_local, .. }) => {
955 !is_thread_local
956 }
957 ClearCrossCrate::Set(box LocalInfo::FakeBorrow) => true,
960 _ => false,
961 };
962 let decl =
963 CoroutineSavedTy { ty: decl.ty, source_info: decl.source_info, ignore_for_traits };
964 debug!(?decl);
965
966 tys.push(decl);
967 }
968
969 let body_span = body.source_scopes[OUTERMOST_SOURCE_SCOPE].span;
973 let mut variant_source_info: IndexVec<VariantIdx, SourceInfo> = [
974 SourceInfo::outermost(body_span.shrink_to_lo()),
975 SourceInfo::outermost(body_span.shrink_to_hi()),
976 SourceInfo::outermost(body_span.shrink_to_hi()),
977 ]
978 .iter()
979 .copied()
980 .collect();
981
982 let mut variant_fields: IndexVec<VariantIdx, IndexVec<FieldIdx, CoroutineSavedLocal>> =
985 iter::repeat(IndexVec::new()).take(CoroutineArgs::RESERVED_VARIANTS).collect();
986 let mut remap = IndexVec::from_elem_n(None, saved_locals.domain_size());
987 for (suspension_point_idx, live_locals) in live_locals_at_suspension_points.iter().enumerate() {
988 let variant_index =
989 VariantIdx::from(CoroutineArgs::RESERVED_VARIANTS + suspension_point_idx);
990 let mut fields = IndexVec::new();
991 for (idx, saved_local) in live_locals.iter().enumerate() {
992 fields.push(saved_local);
993 let idx = FieldIdx::from_usize(idx);
998 remap[locals[saved_local]] = Some((tys[saved_local].ty, variant_index, idx));
999 }
1000 variant_fields.push(fields);
1001 variant_source_info.push(source_info_at_suspension_points[suspension_point_idx]);
1002 }
1003 debug!("coroutine variant_fields = {:?}", variant_fields);
1004 debug!("coroutine storage_conflicts = {:#?}", storage_conflicts);
1005
1006 let mut field_names = IndexVec::from_elem(None, &tys);
1007 for var in &body.var_debug_info {
1008 let VarDebugInfoContents::Place(place) = &var.value else { continue };
1009 let Some(local) = place.as_local() else { continue };
1010 let Some(&Some((_, variant, field))) = remap.get(local) else {
1011 continue;
1012 };
1013
1014 let saved_local = variant_fields[variant][field];
1015 field_names.get_or_insert_with(saved_local, || var.name);
1016 }
1017
1018 let layout = CoroutineLayout {
1019 field_tys: tys,
1020 field_names,
1021 variant_fields,
1022 variant_source_info,
1023 storage_conflicts,
1024 };
1025 debug!(?layout);
1026
1027 (remap, layout, storage_liveness)
1028}
1029
1030fn insert_switch<'tcx>(
1035 body: &mut Body<'tcx>,
1036 cases: Vec<(usize, BasicBlock)>,
1037 transform: &TransformVisitor<'tcx>,
1038 default: TerminatorKind<'tcx>,
1039) {
1040 let default_block = insert_term_block(body, default);
1041 let (assign, discr) = transform.get_discr(body);
1042 let switch_targets =
1043 SwitchTargets::new(cases.iter().map(|(i, bb)| ((*i) as u128, *bb)), default_block);
1044 let switch = TerminatorKind::SwitchInt { discr: Operand::Move(discr), targets: switch_targets };
1045
1046 let source_info = SourceInfo::outermost(body.span);
1047 body.basic_blocks_mut().raw.insert(
1048 0,
1049 BasicBlockData {
1050 statements: vec![assign],
1051 terminator: Some(Terminator { source_info, kind: switch }),
1052 is_cleanup: false,
1053 },
1054 );
1055
1056 let blocks = body.basic_blocks_mut().iter_mut();
1057
1058 for target in blocks.flat_map(|b| b.terminator_mut().successors_mut()) {
1059 *target = BasicBlock::new(target.index() + 1);
1060 }
1061}
1062
1063fn elaborate_coroutine_drops<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
1064 use crate::elaborate_drop::{Unwind, elaborate_drop};
1065 use crate::patch::MirPatch;
1066 use crate::shim::DropShimElaborator;
1067
1068 let typing_env = body.typing_env(tcx);
1072
1073 let mut elaborator = DropShimElaborator { body, patch: MirPatch::new(body), tcx, typing_env };
1074
1075 for (block, block_data) in body.basic_blocks.iter_enumerated() {
1076 let (target, unwind, source_info) = match block_data.terminator() {
1077 Terminator {
1078 source_info,
1079 kind: TerminatorKind::Drop { place, target, unwind, replace: _ },
1080 } => {
1081 if let Some(local) = place.as_local()
1082 && local == SELF_ARG
1083 {
1084 (target, unwind, source_info)
1085 } else {
1086 continue;
1087 }
1088 }
1089 _ => continue,
1090 };
1091 let unwind = if block_data.is_cleanup {
1092 Unwind::InCleanup
1093 } else {
1094 Unwind::To(match *unwind {
1095 UnwindAction::Cleanup(tgt) => tgt,
1096 UnwindAction::Continue => elaborator.patch.resume_block(),
1097 UnwindAction::Unreachable => elaborator.patch.unreachable_cleanup_block(),
1098 UnwindAction::Terminate(reason) => elaborator.patch.terminate_block(reason),
1099 })
1100 };
1101 elaborate_drop(
1102 &mut elaborator,
1103 *source_info,
1104 Place::from(SELF_ARG),
1105 (),
1106 *target,
1107 unwind,
1108 block,
1109 );
1110 }
1111 elaborator.patch.apply(body);
1112}
1113
1114fn create_coroutine_drop_shim<'tcx>(
1115 tcx: TyCtxt<'tcx>,
1116 transform: &TransformVisitor<'tcx>,
1117 coroutine_ty: Ty<'tcx>,
1118 body: &Body<'tcx>,
1119 drop_clean: BasicBlock,
1120) -> Body<'tcx> {
1121 let mut body = body.clone();
1122 let _ = body.coroutine.take();
1125 body.arg_count = 1;
1128
1129 let source_info = SourceInfo::outermost(body.span);
1130
1131 let mut cases = create_cases(&mut body, transform, Operation::Drop);
1132
1133 cases.insert(0, (CoroutineArgs::UNRESUMED, drop_clean));
1134
1135 insert_switch(&mut body, cases, transform, TerminatorKind::Return);
1139
1140 for block in body.basic_blocks_mut() {
1141 let kind = &mut block.terminator_mut().kind;
1142 if let TerminatorKind::CoroutineDrop = *kind {
1143 *kind = TerminatorKind::Return;
1144 }
1145 }
1146
1147 body.local_decls[RETURN_PLACE] = LocalDecl::with_source_info(tcx.types.unit, source_info);
1149
1150 make_coroutine_state_argument_indirect(tcx, &mut body);
1151
1152 body.local_decls[SELF_ARG] =
1154 LocalDecl::with_source_info(Ty::new_mut_ptr(tcx, coroutine_ty), source_info);
1155
1156 simplify::remove_dead_blocks(&mut body);
1159
1160 let coroutine_instance = body.source.instance;
1162 let drop_in_place = tcx.require_lang_item(LangItem::DropInPlace, None);
1163 let drop_instance = InstanceKind::DropGlue(drop_in_place, Some(coroutine_ty));
1164
1165 body.source.instance = coroutine_instance;
1168 dump_mir(tcx, false, "coroutine_drop", &0, &body, |_, _| Ok(()));
1169 body.source.instance = drop_instance;
1170
1171 body
1172}
1173
1174fn insert_term_block<'tcx>(body: &mut Body<'tcx>, kind: TerminatorKind<'tcx>) -> BasicBlock {
1175 let source_info = SourceInfo::outermost(body.span);
1176 body.basic_blocks_mut().push(BasicBlockData {
1177 statements: Vec::new(),
1178 terminator: Some(Terminator { source_info, kind }),
1179 is_cleanup: false,
1180 })
1181}
1182
1183fn insert_panic_block<'tcx>(
1184 tcx: TyCtxt<'tcx>,
1185 body: &mut Body<'tcx>,
1186 message: AssertMessage<'tcx>,
1187) -> BasicBlock {
1188 let assert_block = BasicBlock::new(body.basic_blocks.len());
1189 let kind = TerminatorKind::Assert {
1190 cond: Operand::Constant(Box::new(ConstOperand {
1191 span: body.span,
1192 user_ty: None,
1193 const_: Const::from_bool(tcx, false),
1194 })),
1195 expected: true,
1196 msg: Box::new(message),
1197 target: assert_block,
1198 unwind: UnwindAction::Continue,
1199 };
1200
1201 insert_term_block(body, kind)
1202}
1203
1204fn can_return<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, typing_env: ty::TypingEnv<'tcx>) -> bool {
1205 if body.return_ty().is_privately_uninhabited(tcx, typing_env) {
1207 return false;
1208 }
1209
1210 for block in body.basic_blocks.iter() {
1212 if let TerminatorKind::Return = block.terminator().kind {
1213 return true;
1214 }
1215 }
1216
1217 false
1219}
1220
1221fn can_unwind<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>) -> bool {
1222 if tcx.sess.panic_strategy() == PanicStrategy::Abort {
1224 return false;
1225 }
1226
1227 for block in body.basic_blocks.iter() {
1229 match block.terminator().kind {
1230 TerminatorKind::Goto { .. }
1232 | TerminatorKind::SwitchInt { .. }
1233 | TerminatorKind::UnwindTerminate(_)
1234 | TerminatorKind::Return
1235 | TerminatorKind::Unreachable
1236 | TerminatorKind::CoroutineDrop
1237 | TerminatorKind::FalseEdge { .. }
1238 | TerminatorKind::FalseUnwind { .. } => {}
1239
1240 TerminatorKind::UnwindResume => {}
1243
1244 TerminatorKind::Yield { .. } => {
1245 unreachable!("`can_unwind` called before coroutine transform")
1246 }
1247
1248 TerminatorKind::Drop { .. }
1250 | TerminatorKind::Call { .. }
1251 | TerminatorKind::InlineAsm { .. }
1252 | TerminatorKind::Assert { .. } => return true,
1253
1254 TerminatorKind::TailCall { .. } => {
1255 unreachable!("tail calls can't be present in generators")
1256 }
1257 }
1258 }
1259
1260 false
1262}
1263
1264fn create_coroutine_resume_function<'tcx>(
1265 tcx: TyCtxt<'tcx>,
1266 transform: TransformVisitor<'tcx>,
1267 body: &mut Body<'tcx>,
1268 can_return: bool,
1269) {
1270 let can_unwind = can_unwind(tcx, body);
1271
1272 if can_unwind {
1274 let source_info = SourceInfo::outermost(body.span);
1275 let poison_block = body.basic_blocks_mut().push(BasicBlockData {
1276 statements: vec![
1277 transform.set_discr(VariantIdx::new(CoroutineArgs::POISONED), source_info),
1278 ],
1279 terminator: Some(Terminator { source_info, kind: TerminatorKind::UnwindResume }),
1280 is_cleanup: true,
1281 });
1282
1283 for (idx, block) in body.basic_blocks_mut().iter_enumerated_mut() {
1284 let source_info = block.terminator().source_info;
1285
1286 if let TerminatorKind::UnwindResume = block.terminator().kind {
1287 if idx != poison_block {
1290 *block.terminator_mut() = Terminator {
1291 source_info,
1292 kind: TerminatorKind::Goto { target: poison_block },
1293 };
1294 }
1295 } else if !block.is_cleanup {
1296 if let Some(unwind @ UnwindAction::Continue) = block.terminator_mut().unwind_mut() {
1299 *unwind = UnwindAction::Cleanup(poison_block);
1300 }
1301 }
1302 }
1303 }
1304
1305 let mut cases = create_cases(body, &transform, Operation::Resume);
1306
1307 use rustc_middle::mir::AssertKind::{ResumedAfterPanic, ResumedAfterReturn};
1308
1309 cases.insert(0, (CoroutineArgs::UNRESUMED, START_BLOCK));
1311
1312 if can_unwind {
1314 cases.insert(
1315 1,
1316 (
1317 CoroutineArgs::POISONED,
1318 insert_panic_block(tcx, body, ResumedAfterPanic(transform.coroutine_kind)),
1319 ),
1320 );
1321 }
1322
1323 if can_return {
1324 let block = match transform.coroutine_kind {
1325 CoroutineKind::Desugared(CoroutineDesugaring::Async, _)
1326 | CoroutineKind::Coroutine(_) => {
1327 insert_panic_block(tcx, body, ResumedAfterReturn(transform.coroutine_kind))
1328 }
1329 CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _)
1330 | CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
1331 transform.insert_none_ret_block(body)
1332 }
1333 };
1334 cases.insert(1, (CoroutineArgs::RETURNED, block));
1335 }
1336
1337 insert_switch(body, cases, &transform, TerminatorKind::Unreachable);
1338
1339 make_coroutine_state_argument_indirect(tcx, body);
1340
1341 match transform.coroutine_kind {
1342 CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {}
1345 _ => {
1346 make_coroutine_state_argument_pinned(tcx, body);
1347 }
1348 }
1349
1350 simplify::remove_dead_blocks(body);
1353
1354 pm::run_passes_no_validate(tcx, body, &[&abort_unwinding_calls::AbortUnwindingCalls], None);
1355
1356 dump_mir(tcx, false, "coroutine_resume", &0, body, |_, _| Ok(()));
1357}
1358
1359fn insert_clean_drop(body: &mut Body<'_>) -> BasicBlock {
1360 let return_block = insert_term_block(body, TerminatorKind::Return);
1361
1362 let term = TerminatorKind::Drop {
1363 place: Place::from(SELF_ARG),
1364 target: return_block,
1365 unwind: UnwindAction::Continue,
1366 replace: false,
1367 };
1368 let source_info = SourceInfo::outermost(body.span);
1369
1370 body.basic_blocks_mut().push(BasicBlockData {
1372 statements: Vec::new(),
1373 terminator: Some(Terminator { source_info, kind: term }),
1374 is_cleanup: false,
1375 })
1376}
1377
1378#[derive(PartialEq, Copy, Clone)]
1380enum Operation {
1381 Resume,
1382 Drop,
1383}
1384
1385impl Operation {
1386 fn target_block(self, point: &SuspensionPoint<'_>) -> Option<BasicBlock> {
1387 match self {
1388 Operation::Resume => Some(point.resume),
1389 Operation::Drop => point.drop,
1390 }
1391 }
1392}
1393
1394fn create_cases<'tcx>(
1395 body: &mut Body<'tcx>,
1396 transform: &TransformVisitor<'tcx>,
1397 operation: Operation,
1398) -> Vec<(usize, BasicBlock)> {
1399 let source_info = SourceInfo::outermost(body.span);
1400
1401 transform
1402 .suspension_points
1403 .iter()
1404 .filter_map(|point| {
1405 operation.target_block(point).map(|target| {
1407 let mut statements = Vec::new();
1408
1409 for i in 0..(body.local_decls.len()) {
1411 let l = Local::new(i);
1412 let needs_storage_live = point.storage_liveness.contains(l)
1413 && !transform.remap.contains(l)
1414 && !transform.always_live_locals.contains(l);
1415 if needs_storage_live {
1416 statements
1417 .push(Statement { source_info, kind: StatementKind::StorageLive(l) });
1418 }
1419 }
1420
1421 if operation == Operation::Resume {
1422 let resume_arg = Local::new(2); statements.push(Statement {
1425 source_info,
1426 kind: StatementKind::Assign(Box::new((
1427 point.resume_arg,
1428 Rvalue::Use(Operand::Move(resume_arg.into())),
1429 ))),
1430 });
1431 }
1432
1433 let block = body.basic_blocks_mut().push(BasicBlockData {
1435 statements,
1436 terminator: Some(Terminator {
1437 source_info,
1438 kind: TerminatorKind::Goto { target },
1439 }),
1440 is_cleanup: false,
1441 });
1442
1443 (point.state, block)
1444 })
1445 })
1446 .collect()
1447}
1448
1449#[instrument(level = "debug", skip(tcx), ret)]
1450pub(crate) fn mir_coroutine_witnesses<'tcx>(
1451 tcx: TyCtxt<'tcx>,
1452 def_id: LocalDefId,
1453) -> Option<CoroutineLayout<'tcx>> {
1454 let (body, _) = tcx.mir_promoted(def_id);
1455 let body = body.borrow();
1456 let body = &*body;
1457
1458 let coroutine_ty = body.local_decls[ty::CAPTURE_STRUCT_LOCAL].ty;
1460
1461 let movable = match *coroutine_ty.kind() {
1462 ty::Coroutine(def_id, _) => tcx.coroutine_movability(def_id) == hir::Movability::Movable,
1463 ty::Error(_) => return None,
1464 _ => span_bug!(body.span, "unexpected coroutine type {}", coroutine_ty),
1465 };
1466
1467 let always_live_locals = always_storage_live_locals(body);
1470 let liveness_info = locals_live_across_suspend_points(tcx, body, &always_live_locals, movable);
1471
1472 let (_, coroutine_layout, _) = compute_layout(liveness_info, body);
1476
1477 check_suspend_tys(tcx, &coroutine_layout, body);
1478 check_field_tys_sized(tcx, &coroutine_layout, def_id);
1479
1480 Some(coroutine_layout)
1481}
1482
1483fn check_field_tys_sized<'tcx>(
1484 tcx: TyCtxt<'tcx>,
1485 coroutine_layout: &CoroutineLayout<'tcx>,
1486 def_id: LocalDefId,
1487) {
1488 if !tcx.features().unsized_locals() && !tcx.features().unsized_fn_params() {
1491 return;
1492 }
1493
1494 let infcx = tcx.infer_ctxt().ignoring_regions().build(TypingMode::non_body_analysis());
1499 let param_env = tcx.param_env(def_id);
1500
1501 let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
1502 for field_ty in &coroutine_layout.field_tys {
1503 ocx.register_bound(
1504 ObligationCause::new(
1505 field_ty.source_info.span,
1506 def_id,
1507 ObligationCauseCode::SizedCoroutineInterior(def_id),
1508 ),
1509 param_env,
1510 field_ty.ty,
1511 tcx.require_lang_item(hir::LangItem::Sized, Some(field_ty.source_info.span)),
1512 );
1513 }
1514
1515 let errors = ocx.select_all_or_error();
1516 debug!(?errors);
1517 if !errors.is_empty() {
1518 infcx.err_ctxt().report_fulfillment_errors(errors);
1519 }
1520}
1521
1522impl<'tcx> crate::MirPass<'tcx> for StateTransform {
1523 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
1524 let Some(old_yield_ty) = body.yield_ty() else {
1525 return;
1527 };
1528 let old_ret_ty = body.return_ty();
1529
1530 assert!(body.coroutine_drop().is_none());
1531
1532 let coroutine_ty = body.local_decls.raw[1].ty;
1534 let coroutine_kind = body.coroutine_kind().unwrap();
1535
1536 let (discr_ty, movable) = match *coroutine_ty.kind() {
1538 ty::Coroutine(_, args) => {
1539 let args = args.as_coroutine();
1540 (args.discr_ty(tcx), coroutine_kind.movability() == hir::Movability::Movable)
1541 }
1542 _ => {
1543 tcx.dcx().span_bug(body.span, format!("unexpected coroutine type {coroutine_ty}"));
1544 }
1545 };
1546
1547 let new_ret_ty = match coroutine_kind {
1548 CoroutineKind::Desugared(CoroutineDesugaring::Async, _) => {
1549 let poll_did = tcx.require_lang_item(LangItem::Poll, None);
1551 let poll_adt_ref = tcx.adt_def(poll_did);
1552 let poll_args = tcx.mk_args(&[old_ret_ty.into()]);
1553 Ty::new_adt(tcx, poll_adt_ref, poll_args)
1554 }
1555 CoroutineKind::Desugared(CoroutineDesugaring::Gen, _) => {
1556 let option_did = tcx.require_lang_item(LangItem::Option, None);
1558 let option_adt_ref = tcx.adt_def(option_did);
1559 let option_args = tcx.mk_args(&[old_yield_ty.into()]);
1560 Ty::new_adt(tcx, option_adt_ref, option_args)
1561 }
1562 CoroutineKind::Desugared(CoroutineDesugaring::AsyncGen, _) => {
1563 old_yield_ty
1565 }
1566 CoroutineKind::Coroutine(_) => {
1567 let state_did = tcx.require_lang_item(LangItem::CoroutineState, None);
1569 let state_adt_ref = tcx.adt_def(state_did);
1570 let state_args = tcx.mk_args(&[old_yield_ty.into(), old_ret_ty.into()]);
1571 Ty::new_adt(tcx, state_adt_ref, state_args)
1572 }
1573 };
1574
1575 let old_ret_local = replace_local(RETURN_PLACE, new_ret_ty, body, tcx);
1578
1579 if matches!(
1581 coroutine_kind,
1582 CoroutineKind::Desugared(CoroutineDesugaring::Async | CoroutineDesugaring::AsyncGen, _)
1583 ) {
1584 transform_async_context(tcx, body);
1585 }
1586
1587 let resume_local = Local::new(2);
1592 let resume_ty = body.local_decls[resume_local].ty;
1593 let old_resume_local = replace_local(resume_local, resume_ty, body, tcx);
1594
1595 let source_info = SourceInfo::outermost(body.span);
1598 let stmts = &mut body.basic_blocks_mut()[START_BLOCK].statements;
1599 stmts.insert(
1600 0,
1601 Statement {
1602 source_info,
1603 kind: StatementKind::Assign(Box::new((
1604 old_resume_local.into(),
1605 Rvalue::Use(Operand::Move(resume_local.into())),
1606 ))),
1607 },
1608 );
1609
1610 let always_live_locals = always_storage_live_locals(body);
1611
1612 let liveness_info =
1613 locals_live_across_suspend_points(tcx, body, &always_live_locals, movable);
1614
1615 if tcx.sess.opts.unstable_opts.validate_mir {
1616 let mut vis = EnsureCoroutineFieldAssignmentsNeverAlias {
1617 assigned_local: None,
1618 saved_locals: &liveness_info.saved_locals,
1619 storage_conflicts: &liveness_info.storage_conflicts,
1620 };
1621
1622 vis.visit_body(body);
1623 }
1624
1625 let (remap, layout, storage_liveness) = compute_layout(liveness_info, body);
1629
1630 let can_return = can_return(tcx, body, body.typing_env(tcx));
1631
1632 let mut transform = TransformVisitor {
1638 tcx,
1639 coroutine_kind,
1640 remap,
1641 storage_liveness,
1642 always_live_locals,
1643 suspension_points: Vec::new(),
1644 old_ret_local,
1645 discr_ty,
1646 old_ret_ty,
1647 old_yield_ty,
1648 };
1649 transform.visit_body(body);
1650
1651 body.arg_count = 2; body.spread_arg = None;
1654
1655 if matches!(coroutine_kind, CoroutineKind::Desugared(CoroutineDesugaring::Gen, _)) {
1657 transform_gen_context(body);
1658 }
1659
1660 for var in &mut body.var_debug_info {
1664 var.argument_index = None;
1665 }
1666
1667 body.coroutine.as_mut().unwrap().yield_ty = None;
1668 body.coroutine.as_mut().unwrap().resume_ty = None;
1669 body.coroutine.as_mut().unwrap().coroutine_layout = Some(layout);
1670
1671 let drop_clean = insert_clean_drop(body);
1675
1676 dump_mir(tcx, false, "coroutine_pre-elab", &0, body, |_, _| Ok(()));
1677
1678 elaborate_coroutine_drops(tcx, body);
1682
1683 dump_mir(tcx, false, "coroutine_post-transform", &0, body, |_, _| Ok(()));
1684
1685 let drop_shim = create_coroutine_drop_shim(tcx, &transform, coroutine_ty, body, drop_clean);
1687
1688 body.coroutine.as_mut().unwrap().coroutine_drop = Some(drop_shim);
1689
1690 create_coroutine_resume_function(tcx, transform, body, can_return);
1692
1693 deref_finder(tcx, body);
1695 }
1696
1697 fn is_required(&self) -> bool {
1698 true
1699 }
1700}
1701
1702struct EnsureCoroutineFieldAssignmentsNeverAlias<'a> {
1715 saved_locals: &'a CoroutineSavedLocals,
1716 storage_conflicts: &'a BitMatrix<CoroutineSavedLocal, CoroutineSavedLocal>,
1717 assigned_local: Option<CoroutineSavedLocal>,
1718}
1719
1720impl EnsureCoroutineFieldAssignmentsNeverAlias<'_> {
1721 fn saved_local_for_direct_place(&self, place: Place<'_>) -> Option<CoroutineSavedLocal> {
1722 if place.is_indirect() {
1723 return None;
1724 }
1725
1726 self.saved_locals.get(place.local)
1727 }
1728
1729 fn check_assigned_place(&mut self, place: Place<'_>, f: impl FnOnce(&mut Self)) {
1730 if let Some(assigned_local) = self.saved_local_for_direct_place(place) {
1731 assert!(self.assigned_local.is_none(), "`check_assigned_place` must not recurse");
1732
1733 self.assigned_local = Some(assigned_local);
1734 f(self);
1735 self.assigned_local = None;
1736 }
1737 }
1738}
1739
1740impl<'tcx> Visitor<'tcx> for EnsureCoroutineFieldAssignmentsNeverAlias<'_> {
1741 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
1742 let Some(lhs) = self.assigned_local else {
1743 assert!(!context.is_use());
1748 return;
1749 };
1750
1751 let Some(rhs) = self.saved_local_for_direct_place(*place) else { return };
1752
1753 if !self.storage_conflicts.contains(lhs, rhs) {
1754 bug!(
1755 "Assignment between coroutine saved locals whose storage is not \
1756 marked as conflicting: {:?}: {:?} = {:?}",
1757 location,
1758 lhs,
1759 rhs,
1760 );
1761 }
1762 }
1763
1764 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
1765 match &statement.kind {
1766 StatementKind::Assign(box (lhs, rhs)) => {
1767 self.check_assigned_place(*lhs, |this| this.visit_rvalue(rhs, location));
1768 }
1769
1770 StatementKind::FakeRead(..)
1771 | StatementKind::SetDiscriminant { .. }
1772 | StatementKind::Deinit(..)
1773 | StatementKind::StorageLive(_)
1774 | StatementKind::StorageDead(_)
1775 | StatementKind::Retag(..)
1776 | StatementKind::AscribeUserType(..)
1777 | StatementKind::PlaceMention(..)
1778 | StatementKind::Coverage(..)
1779 | StatementKind::Intrinsic(..)
1780 | StatementKind::ConstEvalCounter
1781 | StatementKind::BackwardIncompatibleDropHint { .. }
1782 | StatementKind::Nop => {}
1783 }
1784 }
1785
1786 fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
1787 match &terminator.kind {
1790 TerminatorKind::Call {
1791 func,
1792 args,
1793 destination,
1794 target: Some(_),
1795 unwind: _,
1796 call_source: _,
1797 fn_span: _,
1798 } => {
1799 self.check_assigned_place(*destination, |this| {
1800 this.visit_operand(func, location);
1801 for arg in args {
1802 this.visit_operand(&arg.node, location);
1803 }
1804 });
1805 }
1806
1807 TerminatorKind::Yield { value, resume: _, resume_arg, drop: _ } => {
1808 self.check_assigned_place(*resume_arg, |this| this.visit_operand(value, location));
1809 }
1810
1811 TerminatorKind::InlineAsm { .. } => {}
1813
1814 TerminatorKind::Call { .. }
1815 | TerminatorKind::Goto { .. }
1816 | TerminatorKind::SwitchInt { .. }
1817 | TerminatorKind::UnwindResume
1818 | TerminatorKind::UnwindTerminate(_)
1819 | TerminatorKind::Return
1820 | TerminatorKind::TailCall { .. }
1821 | TerminatorKind::Unreachable
1822 | TerminatorKind::Drop { .. }
1823 | TerminatorKind::Assert { .. }
1824 | TerminatorKind::CoroutineDrop
1825 | TerminatorKind::FalseEdge { .. }
1826 | TerminatorKind::FalseUnwind { .. } => {}
1827 }
1828 }
1829}
1830
1831fn check_suspend_tys<'tcx>(tcx: TyCtxt<'tcx>, layout: &CoroutineLayout<'tcx>, body: &Body<'tcx>) {
1832 let mut linted_tys = FxHashSet::default();
1833
1834 for (variant, yield_source_info) in
1835 layout.variant_fields.iter().zip(&layout.variant_source_info)
1836 {
1837 debug!(?variant);
1838 for &local in variant {
1839 let decl = &layout.field_tys[local];
1840 debug!(?decl);
1841
1842 if !decl.ignore_for_traits && linted_tys.insert(decl.ty) {
1843 let Some(hir_id) = decl.source_info.scope.lint_root(&body.source_scopes) else {
1844 continue;
1845 };
1846
1847 check_must_not_suspend_ty(
1848 tcx,
1849 decl.ty,
1850 hir_id,
1851 SuspendCheckData {
1852 source_span: decl.source_info.span,
1853 yield_span: yield_source_info.span,
1854 plural_len: 1,
1855 ..Default::default()
1856 },
1857 );
1858 }
1859 }
1860 }
1861}
1862
1863#[derive(Default)]
1864struct SuspendCheckData<'a> {
1865 source_span: Span,
1866 yield_span: Span,
1867 descr_pre: &'a str,
1868 descr_post: &'a str,
1869 plural_len: usize,
1870}
1871
1872fn check_must_not_suspend_ty<'tcx>(
1879 tcx: TyCtxt<'tcx>,
1880 ty: Ty<'tcx>,
1881 hir_id: hir::HirId,
1882 data: SuspendCheckData<'_>,
1883) -> bool {
1884 if ty.is_unit() {
1885 return false;
1886 }
1887
1888 let plural_suffix = pluralize!(data.plural_len);
1889
1890 debug!("Checking must_not_suspend for {}", ty);
1891
1892 match *ty.kind() {
1893 ty::Adt(_, args) if ty.is_box() => {
1894 let boxed_ty = args.type_at(0);
1895 let allocator_ty = args.type_at(1);
1896 check_must_not_suspend_ty(
1897 tcx,
1898 boxed_ty,
1899 hir_id,
1900 SuspendCheckData { descr_pre: &format!("{}boxed ", data.descr_pre), ..data },
1901 ) || check_must_not_suspend_ty(
1902 tcx,
1903 allocator_ty,
1904 hir_id,
1905 SuspendCheckData { descr_pre: &format!("{}allocator ", data.descr_pre), ..data },
1906 )
1907 }
1908 ty::Adt(def, _) => check_must_not_suspend_def(tcx, def.did(), hir_id, data),
1909 ty::Alias(ty::Opaque, ty::AliasTy { def_id: def, .. }) => {
1911 let mut has_emitted = false;
1912 for &(predicate, _) in tcx.explicit_item_bounds(def).skip_binder() {
1913 if let ty::ClauseKind::Trait(ref poly_trait_predicate) =
1915 predicate.kind().skip_binder()
1916 {
1917 let def_id = poly_trait_predicate.trait_ref.def_id;
1918 let descr_pre = &format!("{}implementer{} of ", data.descr_pre, plural_suffix);
1919 if check_must_not_suspend_def(
1920 tcx,
1921 def_id,
1922 hir_id,
1923 SuspendCheckData { descr_pre, ..data },
1924 ) {
1925 has_emitted = true;
1926 break;
1927 }
1928 }
1929 }
1930 has_emitted
1931 }
1932 ty::Dynamic(binder, _, _) => {
1933 let mut has_emitted = false;
1934 for predicate in binder.iter() {
1935 if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate.skip_binder() {
1936 let def_id = trait_ref.def_id;
1937 let descr_post = &format!(" trait object{}{}", plural_suffix, data.descr_post);
1938 if check_must_not_suspend_def(
1939 tcx,
1940 def_id,
1941 hir_id,
1942 SuspendCheckData { descr_post, ..data },
1943 ) {
1944 has_emitted = true;
1945 break;
1946 }
1947 }
1948 }
1949 has_emitted
1950 }
1951 ty::Tuple(fields) => {
1952 let mut has_emitted = false;
1953 for (i, ty) in fields.iter().enumerate() {
1954 let descr_post = &format!(" in tuple element {i}");
1955 if check_must_not_suspend_ty(
1956 tcx,
1957 ty,
1958 hir_id,
1959 SuspendCheckData { descr_post, ..data },
1960 ) {
1961 has_emitted = true;
1962 }
1963 }
1964 has_emitted
1965 }
1966 ty::Array(ty, len) => {
1967 let descr_pre = &format!("{}array{} of ", data.descr_pre, plural_suffix);
1968 check_must_not_suspend_ty(
1969 tcx,
1970 ty,
1971 hir_id,
1972 SuspendCheckData {
1973 descr_pre,
1974 plural_len: len.try_to_target_usize(tcx).unwrap_or(0) as usize + 1,
1976 ..data
1977 },
1978 )
1979 }
1980 ty::Ref(_region, ty, _mutability) => {
1983 let descr_pre = &format!("{}reference{} to ", data.descr_pre, plural_suffix);
1984 check_must_not_suspend_ty(tcx, ty, hir_id, SuspendCheckData { descr_pre, ..data })
1985 }
1986 _ => false,
1987 }
1988}
1989
1990fn check_must_not_suspend_def(
1991 tcx: TyCtxt<'_>,
1992 def_id: DefId,
1993 hir_id: hir::HirId,
1994 data: SuspendCheckData<'_>,
1995) -> bool {
1996 if let Some(attr) = tcx.get_attr(def_id, sym::must_not_suspend) {
1997 let reason = attr.value_str().map(|s| errors::MustNotSuspendReason {
1998 span: data.source_span,
1999 reason: s.as_str().to_string(),
2000 });
2001 tcx.emit_node_span_lint(
2002 rustc_session::lint::builtin::MUST_NOT_SUSPEND,
2003 hir_id,
2004 data.source_span,
2005 errors::MustNotSupend {
2006 tcx,
2007 yield_sp: data.yield_span,
2008 reason,
2009 src_sp: data.source_span,
2010 pre: data.descr_pre,
2011 def_id,
2012 post: data.descr_post,
2013 },
2014 );
2015
2016 true
2017 } else {
2018 false
2019 }
2020}