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