1use std::cell::Cell;
14use std::{assert_matches, cmp, iter, mem};
15
16use either::{Left, Right};
17use rustc_const_eval::check_consts::{ConstCx, qualifs};
18use rustc_data_structures::fx::FxHashSet;
19use rustc_data_structures::thin_vec::ThinVec;
20use rustc_hir as hir;
21use rustc_hir::def::DefKind;
22use rustc_index::{IndexSlice, IndexVec};
23use rustc_middle::mir;
24use rustc_middle::mir::visit::{MutVisitor, MutatingUseContext, PlaceContext, Visitor};
25use rustc_middle::mir::*;
26use rustc_middle::ty::consts::ConstExt;
27use rustc_middle::ty::{self, GenericArgs, List, Ty, TyCtxt, TypeVisitableExt};
28use rustc_span::{Span, Spanned, bug, span_bug};
29use tracing::{debug, instrument};
30
31use crate::PassPolicy;
32
33#[derive(Default)]
41pub(super) struct PromoteTemps<'tcx> {
42 pub promoted_fragments: Cell<IndexVec<Promoted, Body<'tcx>>>,
44}
45
46impl<'tcx> crate::MirPass<'tcx> for PromoteTemps<'tcx> {
47 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
48 if let Err(_) = body.return_ty().error_reported() {
52 debug!("PromoteTemps: MIR had errors");
53 return;
54 }
55 if body.source.promoted.is_some() {
56 return;
57 }
58
59 let ccx = ConstCx::new(tcx, body);
60 let (mut temps, all_candidates) = collect_temps_and_candidates(&ccx);
61
62 let promotable_candidates = validate_candidates(&ccx, &mut temps, all_candidates);
63
64 let promoted = promote_candidates(body, tcx, temps, promotable_candidates);
65 self.promoted_fragments.set(promoted);
66 }
67
68 fn policy(&self, _ctx: &crate::PassCtx<'_>) -> PassPolicy {
69 PassPolicy::Required
71 }
72}
73
74#[derive(Copy, Clone, PartialEq, Eq, Debug)]
76enum TempState {
77 Undefined,
79 Defined { location: Location, uses: usize, valid: Result<(), ()> },
83 Unpromotable,
85 PromotedOut,
88}
89
90#[derive(Copy, Clone, PartialEq, Eq, Debug)]
94struct Candidate {
95 location: Location,
96}
97
98struct Collector<'a, 'tcx> {
99 ccx: &'a ConstCx<'a, 'tcx>,
100 temps: IndexVec<Local, TempState>,
101 candidates: Vec<Candidate>,
102}
103
104impl<'tcx> Visitor<'tcx> for Collector<'_, 'tcx> {
105 #[instrument(level = "debug", skip(self))]
106 fn visit_local(&mut self, index: Local, context: PlaceContext, location: Location) {
107 match self.ccx.body.local_kind(index) {
109 LocalKind::Arg => return,
110 LocalKind::Temp if self.ccx.body.local_decls[index].is_user_variable() => return,
111 LocalKind::ReturnPointer | LocalKind::Temp => {}
112 }
113
114 if context.is_drop() || !context.is_use() {
118 debug!(is_drop = context.is_drop(), is_use = context.is_use());
119 return;
120 }
121
122 let temp = &mut self.temps[index];
123 debug!(?temp);
124 *temp = match *temp {
125 TempState::Undefined => match context {
126 PlaceContext::MutatingUse(MutatingUseContext::Store | MutatingUseContext::Call) => {
127 TempState::Defined { location, uses: 0, valid: Err(()) }
128 }
129 _ => TempState::Unpromotable,
130 },
131 TempState::Defined { ref mut uses, .. } => {
132 let allowed_use = match context {
135 PlaceContext::MutatingUse(MutatingUseContext::Borrow)
136 | PlaceContext::NonMutatingUse(_) => true,
137 PlaceContext::MutatingUse(_) | PlaceContext::NonUse(_) => false,
138 };
139 debug!(?allowed_use);
140 if allowed_use {
141 *uses += 1;
142 return;
143 }
144 TempState::Unpromotable
145 }
146 TempState::Unpromotable | TempState::PromotedOut => TempState::Unpromotable,
147 };
148 debug!(?temp);
149 }
150
151 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
152 self.super_rvalue(rvalue, location);
153
154 if let Rvalue::Ref(..) = *rvalue {
155 self.candidates.push(Candidate { location });
156 }
157 }
158}
159
160fn collect_temps_and_candidates<'tcx>(
161 ccx: &ConstCx<'_, 'tcx>,
162) -> (IndexVec<Local, TempState>, Vec<Candidate>) {
163 let mut collector = Collector {
164 temps: IndexVec::from_elem(TempState::Undefined, &ccx.body.local_decls),
165 candidates: vec![],
166 ccx,
167 };
168 for (bb, data) in traversal::reverse_postorder(ccx.body) {
169 collector.visit_basic_block_data(bb, data);
170 }
171 (collector.temps, collector.candidates)
172}
173
174struct Validator<'a, 'tcx> {
178 ccx: &'a ConstCx<'a, 'tcx>,
179 temps: &'a mut IndexSlice<Local, TempState>,
180 promotion_safe_blocks: Option<FxHashSet<BasicBlock>>,
186}
187
188impl<'a, 'tcx> std::ops::Deref for Validator<'a, 'tcx> {
189 type Target = ConstCx<'a, 'tcx>;
190
191 fn deref(&self) -> &Self::Target {
192 self.ccx
193 }
194}
195
196struct Unpromotable;
197
198impl<'tcx> Validator<'_, 'tcx> {
199 fn validate_candidate(&mut self, candidate: Candidate) -> Result<(), Unpromotable> {
200 let Left(statement) = self.body.stmt_at(candidate.location) else { bug!() };
201 let Some((_, Rvalue::Ref(_, kind, place))) = statement.kind.as_assign() else { bug!() };
202
203 self.validate_local(place.local)?;
206
207 self.validate_ref(*kind, place)?;
210
211 if place.projection.contains(&ProjectionElem::Deref) {
214 return Err(Unpromotable);
215 }
216
217 Ok(())
218 }
219
220 fn qualif_local<Q: qualifs::Qualif>(&mut self, local: Local) -> bool {
222 let TempState::Defined { location: loc, .. } = self.temps[local] else {
223 return false;
224 };
225
226 let stmt_or_term = self.body.stmt_at(loc);
227 match stmt_or_term {
228 Left(statement) => {
229 let Some((_, rhs)) = statement.kind.as_assign() else {
230 span_bug!(statement.source_info.span, "{:?} is not an assignment", statement)
231 };
232 qualifs::in_rvalue::<Q, _>(self.ccx, &mut |l| self.qualif_local::<Q>(l), rhs)
233 }
234 Right(terminator) => {
235 assert_matches!(terminator.kind, TerminatorKind::Call { .. });
236 let return_ty = self.body.local_decls[local].ty;
237 Q::in_any_value_of_ty(self.ccx, return_ty)
238 }
239 }
240 }
241
242 fn validate_local(&mut self, local: Local) -> Result<(), Unpromotable> {
243 let TempState::Defined { location: loc, uses, valid } = self.temps[local] else {
244 return Err(Unpromotable);
245 };
246
247 if self.qualif_local::<qualifs::NeedsDrop>(local) {
250 return Err(Unpromotable);
251 }
252
253 if valid.is_ok() {
254 return Ok(());
255 }
256
257 let ok = {
258 let stmt_or_term = self.body.stmt_at(loc);
259 match stmt_or_term {
260 Left(statement) => {
261 let Some((_, rhs)) = statement.kind.as_assign() else {
262 span_bug!(
263 statement.source_info.span,
264 "{:?} is not an assignment",
265 statement
266 )
267 };
268 self.validate_rvalue(rhs)
269 }
270 Right(terminator) => match &terminator.kind {
271 TerminatorKind::Call { func, args, .. } => {
272 self.validate_call(func, args, loc.block)
273 }
274 TerminatorKind::Yield { .. } => Err(Unpromotable),
275 kind => {
276 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
277 }
278 },
279 }
280 };
281
282 self.temps[local] = match ok {
283 Ok(()) => TempState::Defined { location: loc, uses, valid: Ok(()) },
284 Err(_) => TempState::Unpromotable,
285 };
286
287 ok
288 }
289
290 fn validate_place(&mut self, place: PlaceRef<'tcx>) -> Result<(), Unpromotable> {
291 let Some((place_base, elem)) = place.last_projection() else {
292 return self.validate_local(place.local);
293 };
294
295 match elem {
297 ProjectionElem::ConstantIndex { .. }
299 | ProjectionElem::Subslice { .. }
300 | ProjectionElem::UnwrapUnsafeBinder(_) => {}
301
302 ProjectionElem::PhantomDeref
304 | ProjectionElem::OpaqueCast(..)
305 | ProjectionElem::Downcast(..) => {
306 return Err(Unpromotable);
307 }
308
309 ProjectionElem::Deref => {
310 if let Some(local) = place_base.as_local()
318 && let TempState::Defined { location, .. } = self.temps[local]
319 && let Left(def_stmt) = self.body.stmt_at(location)
320 && let Some((_, Rvalue::Use(Operand::Constant(c), _))) = def_stmt.kind.as_assign()
321 && let Some(did) = c.check_static_ptr(self.tcx)
322 && let Some(hir::ConstContext::Static(..)) = self.const_kind
326 && !self.tcx.is_thread_local_static(did)
327 && !self.tcx.is_foreign_item(did)
329 {
330 } else {
332 return Err(Unpromotable);
333 }
334 }
335 ProjectionElem::Index(local) => {
336 if let TempState::Defined { location: loc, .. } = self.temps[local]
338 && let Left(statement) = self.body.stmt_at(loc)
339 && let Some((_, Rvalue::Use(Operand::Constant(c), _))) = statement.kind.as_assign()
340 && self.should_evaluate_for_promotion_checks(c.const_)
341 && let Some(idx) = c.const_.try_eval_target_usize(self.tcx, self.typing_env)
342 && let ty::Array(_, len) = place_base.ty(self.body, self.tcx).ty.kind()
344 && let Some(len) = len.try_to_target_usize(self.tcx)
346 && idx < len
348 {
349 self.validate_local(local)?;
350 } else {
352 return Err(Unpromotable);
353 }
354 }
355
356 ProjectionElem::Field(..) => {
357 let base_ty = place_base.ty(self.body, self.tcx).ty;
358 if base_ty.is_union() {
359 return Err(Unpromotable);
361 }
362 }
363 }
364
365 self.validate_place(place_base)
366 }
367
368 fn validate_operand(&mut self, operand: &Operand<'tcx>) -> Result<(), Unpromotable> {
369 match operand {
370 Operand::Copy(place) | Operand::Move(place) => self.validate_place(place.as_ref()),
371
372 Operand::RuntimeChecks(_) => Err(Unpromotable),
375
376 Operand::Constant(c) => {
379 if let Some(def_id) = c.check_static_ptr(self.tcx) {
380 let is_static = matches!(self.const_kind, Some(hir::ConstContext::Static(_)));
387 if !is_static {
388 return Err(Unpromotable);
389 }
390
391 let is_thread_local = self.tcx.is_thread_local_static(def_id);
392 if is_thread_local {
393 return Err(Unpromotable);
394 }
395 }
396
397 Ok(())
398 }
399 }
400 }
401
402 fn validate_ref(&mut self, kind: BorrowKind, place: &Place<'tcx>) -> Result<(), Unpromotable> {
403 match kind {
404 BorrowKind::Fake(_) | BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture } => {
408 return Err(Unpromotable);
409 }
410
411 BorrowKind::Shared => {
412 let has_mut_interior = self.qualif_local::<qualifs::HasMutInterior>(place.local);
413 if has_mut_interior {
414 return Err(Unpromotable);
415 }
416 }
417
418 BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow } => {
421 let ty = place.ty(self.body, self.tcx).ty;
422
423 let ty::Array(_, len) = ty.kind() else { return Err(Unpromotable) };
427 let Some(0) = len.try_to_target_usize(self.tcx) else { return Err(Unpromotable) };
428 }
429 }
430
431 Ok(())
432 }
433
434 fn validate_rvalue(&mut self, rvalue: &Rvalue<'tcx>) -> Result<(), Unpromotable> {
435 match rvalue {
436 Rvalue::Use(_operand, WithRetag::No) => {
437 return Err(Unpromotable);
440 }
441 Rvalue::Use(operand, _)
442 | Rvalue::Repeat(operand, _)
443 | Rvalue::WrapUnsafeBinder(operand, _) => {
444 self.validate_operand(operand)?;
445 }
446 Rvalue::CopyForDeref(place) => {
447 let op = &Operand::Copy(*place);
448 self.validate_operand(op)?
449 }
450
451 Rvalue::Discriminant(place) => self.validate_place(place.as_ref())?,
452
453 Rvalue::ThreadLocalRef(_) => return Err(Unpromotable),
454
455 Rvalue::Cast(CastKind::PointerExposeProvenance, _, _) => return Err(Unpromotable),
457
458 Rvalue::Cast(_, operand, _) => {
461 self.validate_operand(operand)?;
462 }
463
464 Rvalue::UnaryOp(op, operand) => {
465 match op {
466 UnOp::Neg | UnOp::Not | UnOp::PtrMetadata => {}
468 }
469
470 self.validate_operand(operand)?;
471 }
472
473 Rvalue::BinaryOp(op, (lhs, rhs)) => {
474 let op = *op;
475 let lhs_ty = lhs.ty(self.body, self.tcx);
476
477 if let ty::RawPtr(_, _) | ty::FnPtr(..) = lhs_ty.kind() {
478 assert_matches!(
481 op,
482 BinOp::Eq
483 | BinOp::Ne
484 | BinOp::Le
485 | BinOp::Lt
486 | BinOp::Ge
487 | BinOp::Gt
488 | BinOp::Offset
489 );
490 return Err(Unpromotable);
491 }
492
493 match op {
494 BinOp::Div | BinOp::Rem => {
495 if lhs_ty.is_integral() {
496 let sz = lhs_ty.primitive_size(self.tcx);
497 let rhs_val = if let Operand::Constant(rhs_c) = rhs
499 && self.should_evaluate_for_promotion_checks(rhs_c.const_)
500 && let Some(rhs_val) =
501 rhs_c.const_.try_eval_scalar_int(self.tcx, self.typing_env)
502 && rhs_val.to_uint(sz) != 0
504 {
505 rhs_val
506 } else {
507 return Err(Unpromotable);
509 };
510 if lhs_ty.is_signed() && rhs_val.to_int(sz) == -1 {
513 if let Operand::Constant(lhs_c) = lhs
515 && self.should_evaluate_for_promotion_checks(lhs_c.const_)
516 && let Some(lhs_val) =
517 lhs_c.const_.try_eval_scalar_int(self.tcx, self.typing_env)
518 && let lhs_min = sz.signed_int_min()
519 && lhs_val.to_int(sz) != lhs_min
520 {
521 } else {
523 return Err(Unpromotable);
525 }
526 }
527 }
528 }
529 BinOp::Eq
531 | BinOp::Ne
532 | BinOp::Le
533 | BinOp::Lt
534 | BinOp::Ge
535 | BinOp::Gt
536 | BinOp::Cmp
537 | BinOp::Offset
538 | BinOp::Add
539 | BinOp::AddUnchecked
540 | BinOp::AddWithOverflow
541 | BinOp::Sub
542 | BinOp::SubUnchecked
543 | BinOp::SubWithOverflow
544 | BinOp::Mul
545 | BinOp::MulUnchecked
546 | BinOp::MulWithOverflow
547 | BinOp::BitXor
548 | BinOp::BitAnd
549 | BinOp::BitOr
550 | BinOp::Shl
551 | BinOp::ShlUnchecked
552 | BinOp::Shr
553 | BinOp::ShrUnchecked => {}
554 }
555
556 self.validate_operand(lhs)?;
557 self.validate_operand(rhs)?;
558 }
559
560 Rvalue::RawPtr(_, place) => {
561 if let Some((place_base, ProjectionElem::Deref)) = place.as_ref().last_projection()
564 {
565 let base_ty = place_base.ty(self.body, self.tcx).ty;
566 if let ty::Ref(..) = base_ty.kind() {
567 return self.validate_place(place_base);
568 }
569 }
570 return Err(Unpromotable);
571 }
572
573 Rvalue::Ref(_, kind, place) => {
574 let mut place_simplified = place.as_ref();
576 if let Some((place_base, ProjectionElem::Deref)) =
577 place_simplified.last_projection()
578 {
579 let base_ty = place_base.ty(self.body, self.tcx).ty;
580 if let ty::Ref(..) = base_ty.kind() {
581 place_simplified = place_base;
582 }
583 }
584
585 self.validate_place(place_simplified)?;
586
587 self.validate_ref(*kind, place)?;
590 }
591
592 Rvalue::Reborrow(..) => return Err(Unpromotable),
593
594 Rvalue::Aggregate(_, operands) => {
595 for o in operands {
596 self.validate_operand(o)?;
597 }
598 }
599 }
600
601 Ok(())
602 }
603
604 fn promotion_safe_blocks(body: &mir::Body<'tcx>) -> FxHashSet<BasicBlock> {
608 let mut safe_blocks = FxHashSet::default();
609 let mut safe_block = START_BLOCK;
610 loop {
611 safe_blocks.insert(safe_block);
612 safe_block = match body.basic_blocks[safe_block].terminator().kind {
614 TerminatorKind::Goto { target } => target,
615 TerminatorKind::Call { target: Some(target), .. }
616 | TerminatorKind::Drop { target, .. } => {
617 target
621 }
622 TerminatorKind::Assert { target, .. } => {
623 target
625 }
626 _ => {
627 break;
629 }
630 };
631 }
632 safe_blocks
633 }
634
635 fn is_promotion_safe_block(&mut self, block: BasicBlock) -> bool {
638 let body = self.body;
639 let safe_blocks =
640 self.promotion_safe_blocks.get_or_insert_with(|| Self::promotion_safe_blocks(body));
641 safe_blocks.contains(&block)
642 }
643
644 fn validate_call(
645 &mut self,
646 callee: &Operand<'tcx>,
647 args: &[Spanned<Operand<'tcx>>],
648 block: BasicBlock,
649 ) -> Result<(), Unpromotable> {
650 self.validate_operand(callee)?;
652 for arg in args {
653 self.validate_operand(&arg.node)?;
654 }
655
656 let fn_ty = callee.ty(self.body, self.tcx);
659 if let ty::FnDef(def_id, _) = *fn_ty.kind() {
660 if self.tcx.is_promotable_const_fn(def_id) {
661 return Ok(());
662 }
663 }
664
665 let promote_all_fn = matches!(
670 self.const_kind,
671 Some(
672 hir::ConstContext::Static(_)
673 | hir::ConstContext::Const { allow_const_fn_promotion: true }
674 )
675 );
676 if !promote_all_fn {
677 return Err(Unpromotable);
678 }
679 let is_const_fn = match *fn_ty.kind() {
681 ty::FnDef(def_id, _) => self.tcx.is_const_fn(def_id),
682 _ => false,
683 };
684 if !is_const_fn {
685 return Err(Unpromotable);
686 }
687 if !self.is_promotion_safe_block(block) {
691 return Err(Unpromotable);
692 }
693 Ok(())
695 }
696
697 fn should_evaluate_for_promotion_checks(&self, constant: Const<'tcx>) -> bool {
700 match constant {
701 Const::Ty(..) => false,
705 Const::Val(..) => true,
706 Const::Unevaluated(uc, _) => {
716 self.tcx.def_kind(uc.def) != DefKind::AnonConst
717 || self.tcx.anon_const_kind(uc.def) != ty::AnonConstKind::NonTypeSystemInline
718 }
719 }
720 }
721}
722
723fn validate_candidates(
724 ccx: &ConstCx<'_, '_>,
725 temps: &mut IndexSlice<Local, TempState>,
726 mut candidates: Vec<Candidate>,
727) -> Vec<Candidate> {
728 let mut validator = Validator { ccx, temps, promotion_safe_blocks: None };
729
730 candidates.retain(|&candidate| validator.validate_candidate(candidate).is_ok());
731 candidates
732}
733
734struct Promoter<'a, 'tcx> {
735 tcx: TyCtxt<'tcx>,
736 source: &'a mut Body<'tcx>,
737 promoted: Body<'tcx>,
738 temps: &'a mut IndexVec<Local, TempState>,
739 extra_statements: &'a mut Vec<(Location, Statement<'tcx>)>,
740
741 required_consts: Vec<ConstOperand<'tcx>>,
743
744 keep_original: bool,
747
748 add_to_required: bool,
751}
752
753impl<'a, 'tcx> Promoter<'a, 'tcx> {
754 fn new_block(&mut self) -> BasicBlock {
755 let span = self.promoted.span;
756 self.promoted.basic_blocks_mut().push(BasicBlockData::new(
757 Some(Terminator {
758 source_info: SourceInfo::outermost(span),
759 kind: TerminatorKind::Return,
760 attributes: ThinVec::new(),
761 }),
762 false,
763 ))
764 }
765
766 fn assign(&mut self, dest: Local, rvalue: Rvalue<'tcx>, span: Span) {
767 let last = self.promoted.basic_blocks.last_index().unwrap();
768 let data = &mut self.promoted[last];
769 data.statements.push(Statement::new(
770 SourceInfo::outermost(span),
771 StatementKind::Assign(Box::new((Place::from(dest), rvalue))),
772 ));
773 }
774
775 fn is_temp_kind(&self, local: Local) -> bool {
776 self.source.local_kind(local) == LocalKind::Temp
777 }
778
779 fn promote_temp(&mut self, temp: Local) -> Local {
782 let old_keep_original = self.keep_original;
783 let loc = match self.temps[temp] {
784 TempState::Defined { location, uses, .. } if uses > 0 => {
785 if uses > 1 {
786 self.keep_original = true;
787 }
788 location
789 }
790 state => {
791 span_bug!(self.promoted.span, "{:?} not promotable: {:?}", temp, state);
792 }
793 };
794 if !self.keep_original {
795 self.temps[temp] = TempState::PromotedOut;
796 }
797
798 let num_stmts = self.source[loc.block].statements.len();
799 let new_temp = self.promoted.local_decls.push(LocalDecl::new(
800 self.source.local_decls[temp].ty,
801 self.source.local_decls[temp].source_info.span,
802 ));
803
804 debug!("promote({:?} @ {:?}/{:?}, {:?})", temp, loc, num_stmts, self.keep_original);
805
806 if loc.statement_index < num_stmts {
809 let (mut rvalue, source_info) = {
810 let statement = &mut self.source[loc.block].statements[loc.statement_index];
811 let StatementKind::Assign((_, rhs)) = &mut statement.kind else {
812 span_bug!(statement.source_info.span, "{:?} is not an assignment", statement);
813 };
814
815 (
816 if self.keep_original {
817 rhs.clone()
818 } else {
819 let unit = Rvalue::Use(
820 Operand::Constant(Box::new(ConstOperand {
821 span: statement.source_info.span,
822 user_ty: None,
823 const_: Const::zero_sized(self.tcx.types.unit),
824 })),
825 WithRetag::Yes,
826 );
827 mem::replace(rhs, unit)
828 },
829 statement.source_info,
830 )
831 };
832
833 self.visit_rvalue(&mut rvalue, loc);
834 self.assign(new_temp, rvalue, source_info.span);
835 } else {
836 let terminator = if self.keep_original {
837 self.source[loc.block].terminator().clone()
838 } else {
839 let terminator = self.source[loc.block].terminator_mut();
840 let target = match &terminator.kind {
841 TerminatorKind::Call { target: Some(target), .. } => *target,
842 kind => {
843 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
844 }
845 };
846 Terminator {
847 source_info: terminator.source_info,
848 kind: mem::replace(&mut terminator.kind, TerminatorKind::Goto { target }),
849 attributes: ThinVec::new(),
850 }
851 };
852
853 match terminator.kind {
854 TerminatorKind::Call {
855 mut func, mut args, call_source: desugar, fn_span, ..
856 } => {
857 self.add_to_required = true;
860
861 self.visit_operand(&mut func, loc);
862 for arg in &mut args {
863 self.visit_operand(&mut arg.node, loc);
864 }
865
866 let last = self.promoted.basic_blocks.last_index().unwrap();
867 let new_target = self.new_block();
868
869 *self.promoted[last].terminator_mut() = Terminator {
870 kind: TerminatorKind::Call {
871 func,
872 args,
873 unwind: UnwindAction::Continue,
874 destination: Place::from(new_temp),
875 target: Some(new_target),
876 call_source: desugar,
877 fn_span,
878 },
879 source_info: SourceInfo::outermost(terminator.source_info.span),
880 ..terminator
881 };
882 }
883 kind => {
884 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
885 }
886 };
887 };
888
889 self.keep_original = old_keep_original;
890 new_temp
891 }
892
893 fn promote_candidate(
894 mut self,
895 candidate: Candidate,
896 next_promoted_index: Promoted,
897 ) -> Body<'tcx> {
898 let def = self.source.source.def_id();
899 let (mut rvalue, promoted_op) = {
900 let promoted = &mut self.promoted;
901 let tcx = self.tcx;
902 let mut promoted_operand = |ty, span| {
903 promoted.span = span;
904 promoted.local_decls[RETURN_PLACE] = LocalDecl::new(ty, span);
905 let args =
906 tcx.erase_and_anonymize_regions(GenericArgs::identity_for_item(tcx, def));
907 let uneval =
908 mir::UnevaluatedConst { def, args, promoted: Some(next_promoted_index) };
909
910 ConstOperand { span, user_ty: None, const_: Const::Unevaluated(uneval, ty) }
911 };
912
913 let blocks = self.source.basic_blocks.as_mut();
914 let local_decls = &mut self.source.local_decls;
915 let loc = candidate.location;
916 let statement = &mut blocks[loc.block].statements[loc.statement_index];
917 let StatementKind::Assign((_, Rvalue::Ref(region, borrow_kind, place))) =
918 &mut statement.kind
919 else {
920 bug!()
921 };
922
923 debug_assert!(region.is_erased());
925 let ty = local_decls[place.local].ty;
926 let span = statement.source_info.span;
927
928 let ref_ty =
929 Ty::new_ref(tcx, tcx.lifetimes.re_erased, ty, borrow_kind.to_mutbl_lossy());
930
931 let mut projection = vec![PlaceElem::Deref];
932 projection.extend(place.projection);
933 place.projection = tcx.mk_place_elems(&projection);
934
935 let mut promoted_ref = LocalDecl::new(ref_ty, span);
939 promoted_ref.source_info = statement.source_info;
940 let promoted_ref = local_decls.push(promoted_ref);
941 assert_eq!(self.temps.push(TempState::Unpromotable), promoted_ref);
942
943 let promoted_operand = promoted_operand(ref_ty, span);
944 let promoted_ref_statement = Statement::new(
945 statement.source_info,
946 StatementKind::Assign(Box::new((
947 Place::from(promoted_ref),
948 Rvalue::Use(Operand::Constant(Box::new(promoted_operand)), WithRetag::Yes),
951 ))),
952 );
953 self.extra_statements.push((loc, promoted_ref_statement));
954
955 (
956 Rvalue::Ref(
957 tcx.lifetimes.re_erased,
958 *borrow_kind,
959 Place {
960 local: mem::replace(&mut place.local, promoted_ref),
961 projection: List::empty(),
962 },
963 ),
964 promoted_operand,
965 )
966 };
967
968 assert_eq!(self.new_block(), START_BLOCK);
969 self.visit_rvalue(
970 &mut rvalue,
971 Location { block: START_BLOCK, statement_index: usize::MAX },
972 );
973
974 let span = self.promoted.span;
975 self.assign(RETURN_PLACE, rvalue, span);
976
977 if self.add_to_required {
980 self.source.required_consts.as_mut().unwrap().push(promoted_op);
981 }
982
983 self.promoted.set_required_consts(self.required_consts);
984
985 self.promoted
986 }
987}
988
989impl<'a, 'tcx> MutVisitor<'tcx> for Promoter<'a, 'tcx> {
991 fn tcx(&self) -> TyCtxt<'tcx> {
992 self.tcx
993 }
994
995 fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
996 if self.is_temp_kind(*local) {
997 *local = self.promote_temp(*local);
998 }
999 }
1000
1001 fn visit_const_operand(&mut self, constant: &mut ConstOperand<'tcx>, _location: Location) {
1002 if constant.const_.is_required_const() {
1003 self.required_consts.push(*constant);
1004 }
1005
1006 }
1008}
1009
1010fn promote_candidates<'tcx>(
1011 body: &mut Body<'tcx>,
1012 tcx: TyCtxt<'tcx>,
1013 mut temps: IndexVec<Local, TempState>,
1014 candidates: Vec<Candidate>,
1015) -> IndexVec<Promoted, Body<'tcx>> {
1016 debug!(promote_candidates = ?candidates);
1018
1019 if candidates.is_empty() {
1021 return IndexVec::new();
1022 }
1023
1024 let mut promotions = IndexVec::new();
1025
1026 let mut extra_statements = vec![];
1027 for candidate in candidates.into_iter().rev() {
1028 let Location { block, statement_index } = candidate.location;
1029 if let StatementKind::Assign((place, _)) = &body[block].statements[statement_index].kind
1030 && let Some(local) = place.as_local()
1031 {
1032 if temps[local] == TempState::PromotedOut {
1033 continue;
1035 }
1036 }
1037
1038 let initial_locals = iter::once(LocalDecl::new(tcx.types.never, body.span)).collect();
1040
1041 let mut scope = body.source_scopes[body.source_info(candidate.location).scope].clone();
1042 scope.parent_scope = None;
1043
1044 let mut promoted = Body::new(
1045 body.source, IndexVec::new(),
1047 IndexVec::from_elem_n(scope, 1),
1048 initial_locals,
1049 IndexVec::new(),
1050 0,
1051 vec![],
1052 body.span,
1053 None,
1054 body.tainted_by_errors,
1055 );
1056 promoted.phase = MirPhase::Analysis(AnalysisPhase::Initial);
1057
1058 let promoter = Promoter {
1059 promoted,
1060 tcx,
1061 source: body,
1062 temps: &mut temps,
1063 extra_statements: &mut extra_statements,
1064 keep_original: false,
1065 add_to_required: false,
1066 required_consts: Vec::new(),
1067 };
1068
1069 let mut promoted = promoter.promote_candidate(candidate, promotions.next_index());
1070 promoted.source.promoted = Some(promotions.next_index());
1071 promotions.push(promoted);
1072 }
1073
1074 extra_statements.sort_by_key(|&(loc, _)| cmp::Reverse(loc));
1077 for (loc, statement) in extra_statements {
1078 body[loc.block].statements.insert(loc.statement_index, statement);
1079 }
1080
1081 let promoted = |index: Local| temps[index] == TempState::PromotedOut;
1083 for block in body.basic_blocks_mut() {
1084 block.retain_statements(|statement| match &statement.kind {
1085 StatementKind::Assign((place, _)) => {
1086 if let Some(index) = place.as_local() {
1087 !promoted(index)
1088 } else {
1089 true
1090 }
1091 }
1092 StatementKind::StorageLive(index) | StatementKind::StorageDead(index) => {
1093 !promoted(*index)
1094 }
1095 _ => true,
1096 });
1097 let terminator = block.terminator_mut();
1098 if let TerminatorKind::Drop { place, target, .. } = &terminator.kind
1099 && let Some(index) = place.as_local()
1100 {
1101 if promoted(index) {
1102 terminator.kind = TerminatorKind::Goto { target: *target };
1103 }
1104 }
1105 }
1106
1107 promotions
1108}