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