1use std::assert_matches::assert_matches;
14use std::cell::Cell;
15use std::{cmp, iter, mem};
16
17use either::{Left, Right};
18use rustc_const_eval::check_consts::{ConstCx, qualifs};
19use rustc_data_structures::fx::FxHashSet;
20use rustc_hir as hir;
21use rustc_index::{IndexSlice, IndexVec};
22use rustc_middle::mir::visit::{MutVisitor, MutatingUseContext, PlaceContext, Visitor};
23use rustc_middle::mir::*;
24use rustc_middle::ty::{self, GenericArgs, List, Ty, TyCtxt, TypeVisitableExt};
25use rustc_middle::{bug, mir, span_bug};
26use rustc_span::Span;
27use rustc_span::source_map::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 && let Some(idx) = c.const_.try_eval_target_usize(self.tcx, self.typing_env)
333 && let ty::Array(_, len) = place_base.ty(self.body, self.tcx).ty.kind()
335 && let Some(len) = len.try_to_target_usize(self.tcx)
337 && idx < len
339 {
340 self.validate_local(local)?;
341 } else {
343 return Err(Unpromotable);
344 }
345 }
346
347 ProjectionElem::Field(..) => {
348 let base_ty = place_base.ty(self.body, self.tcx).ty;
349 if base_ty.is_union() {
350 return Err(Unpromotable);
352 }
353 }
354 }
355
356 self.validate_place(place_base)
357 }
358
359 fn validate_operand(&mut self, operand: &Operand<'tcx>) -> Result<(), Unpromotable> {
360 match operand {
361 Operand::Copy(place) | Operand::Move(place) => self.validate_place(place.as_ref()),
362
363 Operand::Constant(c) => {
366 if let Some(def_id) = c.check_static_ptr(self.tcx) {
367 let is_static = matches!(self.const_kind, Some(hir::ConstContext::Static(_)));
374 if !is_static {
375 return Err(Unpromotable);
376 }
377
378 let is_thread_local = self.tcx.is_thread_local_static(def_id);
379 if is_thread_local {
380 return Err(Unpromotable);
381 }
382 }
383
384 Ok(())
385 }
386 }
387 }
388
389 fn validate_ref(&mut self, kind: BorrowKind, place: &Place<'tcx>) -> Result<(), Unpromotable> {
390 match kind {
391 BorrowKind::Fake(_) | BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture } => {
395 return Err(Unpromotable);
396 }
397
398 BorrowKind::Shared => {
399 let has_mut_interior = self.qualif_local::<qualifs::HasMutInterior>(place.local);
400 if has_mut_interior {
401 return Err(Unpromotable);
402 }
403 }
404
405 BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow } => {
408 let ty = place.ty(self.body, self.tcx).ty;
409
410 if let ty::Array(_, len) = ty.kind() {
414 match len.try_to_target_usize(self.tcx) {
415 Some(0) => {}
416 _ => return Err(Unpromotable),
417 }
418 } else {
419 return Err(Unpromotable);
420 }
421 }
422 }
423
424 Ok(())
425 }
426
427 fn validate_rvalue(&mut self, rvalue: &Rvalue<'tcx>) -> Result<(), Unpromotable> {
428 match rvalue {
429 Rvalue::Use(operand)
430 | Rvalue::Repeat(operand, _)
431 | Rvalue::WrapUnsafeBinder(operand, _) => {
432 self.validate_operand(operand)?;
433 }
434 Rvalue::CopyForDeref(place) => {
435 let op = &Operand::Copy(*place);
436 self.validate_operand(op)?
437 }
438
439 Rvalue::Discriminant(place) => self.validate_place(place.as_ref())?,
440
441 Rvalue::ThreadLocalRef(_) => return Err(Unpromotable),
442
443 Rvalue::Cast(CastKind::PointerExposeProvenance, _, _) => return Err(Unpromotable),
445
446 Rvalue::Cast(_, operand, _) => {
449 self.validate_operand(operand)?;
450 }
451
452 Rvalue::NullaryOp(op, _) => match op {
453 NullOp::OffsetOf(_) => {}
454 NullOp::RuntimeChecks(_) => {}
455 },
456
457 Rvalue::ShallowInitBox(_, _) => return Err(Unpromotable),
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, box (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 = match rhs {
494 Operand::Constant(c) => {
495 c.const_.try_eval_scalar_int(self.tcx, self.typing_env)
496 }
497 _ => None,
498 };
499 match rhs_val.map(|x| x.to_uint(sz)) {
500 Some(x) if x != 0 => {} _ => return Err(Unpromotable), }
504 if lhs_ty.is_signed() {
507 match rhs_val.map(|x| x.to_int(sz)) {
508 Some(-1) | None => {
509 let lhs_val = match lhs {
512 Operand::Constant(c) => c
513 .const_
514 .try_eval_scalar_int(self.tcx, self.typing_env),
515 _ => None,
516 };
517 let lhs_min = sz.signed_int_min();
518 match lhs_val.map(|x| x.to_int(sz)) {
519 Some(x) if x != lhs_min => {}
521
522 _ => return Err(Unpromotable),
524 }
525 }
526 _ => {}
527 }
528 }
529 }
530 }
531 BinOp::Eq
533 | BinOp::Ne
534 | BinOp::Le
535 | BinOp::Lt
536 | BinOp::Ge
537 | BinOp::Gt
538 | BinOp::Cmp
539 | BinOp::Offset
540 | BinOp::Add
541 | BinOp::AddUnchecked
542 | BinOp::AddWithOverflow
543 | BinOp::Sub
544 | BinOp::SubUnchecked
545 | BinOp::SubWithOverflow
546 | BinOp::Mul
547 | BinOp::MulUnchecked
548 | BinOp::MulWithOverflow
549 | BinOp::BitXor
550 | BinOp::BitAnd
551 | BinOp::BitOr
552 | BinOp::Shl
553 | BinOp::ShlUnchecked
554 | BinOp::Shr
555 | BinOp::ShrUnchecked => {}
556 }
557
558 self.validate_operand(lhs)?;
559 self.validate_operand(rhs)?;
560 }
561
562 Rvalue::RawPtr(_, place) => {
563 if let Some((place_base, ProjectionElem::Deref)) = place.as_ref().last_projection()
566 {
567 let base_ty = place_base.ty(self.body, self.tcx).ty;
568 if let ty::Ref(..) = base_ty.kind() {
569 return self.validate_place(place_base);
570 }
571 }
572 return Err(Unpromotable);
573 }
574
575 Rvalue::Ref(_, kind, place) => {
576 let mut place_simplified = place.as_ref();
578 if let Some((place_base, ProjectionElem::Deref)) =
579 place_simplified.last_projection()
580 {
581 let base_ty = place_base.ty(self.body, self.tcx).ty;
582 if let ty::Ref(..) = base_ty.kind() {
583 place_simplified = place_base;
584 }
585 }
586
587 self.validate_place(place_simplified)?;
588
589 self.validate_ref(*kind, place)?;
592 }
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(hir::ConstContext::Static(_) | hir::ConstContext::Const { inline: false })
672 );
673 if !promote_all_fn {
674 return Err(Unpromotable);
675 }
676 let is_const_fn = match *fn_ty.kind() {
678 ty::FnDef(def_id, _) => self.tcx.is_const_fn(def_id),
679 _ => false,
680 };
681 if !is_const_fn {
682 return Err(Unpromotable);
683 }
684 if !self.is_promotion_safe_block(block) {
688 return Err(Unpromotable);
689 }
690 Ok(())
692 }
693}
694
695fn validate_candidates(
696 ccx: &ConstCx<'_, '_>,
697 temps: &mut IndexSlice<Local, TempState>,
698 mut candidates: Vec<Candidate>,
699) -> Vec<Candidate> {
700 let mut validator = Validator { ccx, temps, promotion_safe_blocks: None };
701
702 candidates.retain(|&candidate| validator.validate_candidate(candidate).is_ok());
703 candidates
704}
705
706struct Promoter<'a, 'tcx> {
707 tcx: TyCtxt<'tcx>,
708 source: &'a mut Body<'tcx>,
709 promoted: Body<'tcx>,
710 temps: &'a mut IndexVec<Local, TempState>,
711 extra_statements: &'a mut Vec<(Location, Statement<'tcx>)>,
712
713 required_consts: Vec<ConstOperand<'tcx>>,
715
716 keep_original: bool,
719
720 add_to_required: bool,
723}
724
725impl<'a, 'tcx> Promoter<'a, 'tcx> {
726 fn new_block(&mut self) -> BasicBlock {
727 let span = self.promoted.span;
728 self.promoted.basic_blocks_mut().push(BasicBlockData::new(
729 Some(Terminator {
730 source_info: SourceInfo::outermost(span),
731 kind: TerminatorKind::Return,
732 }),
733 false,
734 ))
735 }
736
737 fn assign(&mut self, dest: Local, rvalue: Rvalue<'tcx>, span: Span) {
738 let last = self.promoted.basic_blocks.last_index().unwrap();
739 let data = &mut self.promoted[last];
740 data.statements.push(Statement::new(
741 SourceInfo::outermost(span),
742 StatementKind::Assign(Box::new((Place::from(dest), rvalue))),
743 ));
744 }
745
746 fn is_temp_kind(&self, local: Local) -> bool {
747 self.source.local_kind(local) == LocalKind::Temp
748 }
749
750 fn promote_temp(&mut self, temp: Local) -> Local {
753 let old_keep_original = self.keep_original;
754 let loc = match self.temps[temp] {
755 TempState::Defined { location, uses, .. } if uses > 0 => {
756 if uses > 1 {
757 self.keep_original = true;
758 }
759 location
760 }
761 state => {
762 span_bug!(self.promoted.span, "{:?} not promotable: {:?}", temp, state);
763 }
764 };
765 if !self.keep_original {
766 self.temps[temp] = TempState::PromotedOut;
767 }
768
769 let num_stmts = self.source[loc.block].statements.len();
770 let new_temp = self.promoted.local_decls.push(LocalDecl::new(
771 self.source.local_decls[temp].ty,
772 self.source.local_decls[temp].source_info.span,
773 ));
774
775 debug!("promote({:?} @ {:?}/{:?}, {:?})", temp, loc, num_stmts, self.keep_original);
776
777 if loc.statement_index < num_stmts {
780 let (mut rvalue, source_info) = {
781 let statement = &mut self.source[loc.block].statements[loc.statement_index];
782 let StatementKind::Assign(box (_, rhs)) = &mut statement.kind else {
783 span_bug!(statement.source_info.span, "{:?} is not an assignment", statement);
784 };
785
786 (
787 if self.keep_original {
788 rhs.clone()
789 } else {
790 let unit = Rvalue::Use(Operand::Constant(Box::new(ConstOperand {
791 span: statement.source_info.span,
792 user_ty: None,
793 const_: Const::zero_sized(self.tcx.types.unit),
794 })));
795 mem::replace(rhs, unit)
796 },
797 statement.source_info,
798 )
799 };
800
801 self.visit_rvalue(&mut rvalue, loc);
802 self.assign(new_temp, rvalue, source_info.span);
803 } else {
804 let terminator = if self.keep_original {
805 self.source[loc.block].terminator().clone()
806 } else {
807 let terminator = self.source[loc.block].terminator_mut();
808 let target = match &terminator.kind {
809 TerminatorKind::Call { target: Some(target), .. } => *target,
810 kind => {
811 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
812 }
813 };
814 Terminator {
815 source_info: terminator.source_info,
816 kind: mem::replace(&mut terminator.kind, TerminatorKind::Goto { target }),
817 }
818 };
819
820 match terminator.kind {
821 TerminatorKind::Call {
822 mut func, mut args, call_source: desugar, fn_span, ..
823 } => {
824 self.add_to_required = true;
827
828 self.visit_operand(&mut func, loc);
829 for arg in &mut args {
830 self.visit_operand(&mut arg.node, loc);
831 }
832
833 let last = self.promoted.basic_blocks.last_index().unwrap();
834 let new_target = self.new_block();
835
836 *self.promoted[last].terminator_mut() = Terminator {
837 kind: TerminatorKind::Call {
838 func,
839 args,
840 unwind: UnwindAction::Continue,
841 destination: Place::from(new_temp),
842 target: Some(new_target),
843 call_source: desugar,
844 fn_span,
845 },
846 source_info: SourceInfo::outermost(terminator.source_info.span),
847 ..terminator
848 };
849 }
850 kind => {
851 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
852 }
853 };
854 };
855
856 self.keep_original = old_keep_original;
857 new_temp
858 }
859
860 fn promote_candidate(
861 mut self,
862 candidate: Candidate,
863 next_promoted_index: Promoted,
864 ) -> Body<'tcx> {
865 let def = self.source.source.def_id();
866 let (mut rvalue, promoted_op) = {
867 let promoted = &mut self.promoted;
868 let tcx = self.tcx;
869 let mut promoted_operand = |ty, span| {
870 promoted.span = span;
871 promoted.local_decls[RETURN_PLACE] = LocalDecl::new(ty, span);
872 let args =
873 tcx.erase_and_anonymize_regions(GenericArgs::identity_for_item(tcx, def));
874 let uneval =
875 mir::UnevaluatedConst { def, args, promoted: Some(next_promoted_index) };
876
877 ConstOperand { span, user_ty: None, const_: Const::Unevaluated(uneval, ty) }
878 };
879
880 let blocks = self.source.basic_blocks.as_mut();
881 let local_decls = &mut self.source.local_decls;
882 let loc = candidate.location;
883 let statement = &mut blocks[loc.block].statements[loc.statement_index];
884 let StatementKind::Assign(box (_, Rvalue::Ref(region, borrow_kind, place))) =
885 &mut statement.kind
886 else {
887 bug!()
888 };
889
890 debug_assert!(region.is_erased());
892 let ty = local_decls[place.local].ty;
893 let span = statement.source_info.span;
894
895 let ref_ty =
896 Ty::new_ref(tcx, tcx.lifetimes.re_erased, ty, borrow_kind.to_mutbl_lossy());
897
898 let mut projection = vec![PlaceElem::Deref];
899 projection.extend(place.projection);
900 place.projection = tcx.mk_place_elems(&projection);
901
902 let mut promoted_ref = LocalDecl::new(ref_ty, span);
906 promoted_ref.source_info = statement.source_info;
907 let promoted_ref = local_decls.push(promoted_ref);
908 assert_eq!(self.temps.push(TempState::Unpromotable), promoted_ref);
909
910 let promoted_operand = promoted_operand(ref_ty, span);
911 let promoted_ref_statement = Statement::new(
912 statement.source_info,
913 StatementKind::Assign(Box::new((
914 Place::from(promoted_ref),
915 Rvalue::Use(Operand::Constant(Box::new(promoted_operand))),
916 ))),
917 );
918 self.extra_statements.push((loc, promoted_ref_statement));
919
920 (
921 Rvalue::Ref(
922 tcx.lifetimes.re_erased,
923 *borrow_kind,
924 Place {
925 local: mem::replace(&mut place.local, promoted_ref),
926 projection: List::empty(),
927 },
928 ),
929 promoted_operand,
930 )
931 };
932
933 assert_eq!(self.new_block(), START_BLOCK);
934 self.visit_rvalue(
935 &mut rvalue,
936 Location { block: START_BLOCK, statement_index: usize::MAX },
937 );
938
939 let span = self.promoted.span;
940 self.assign(RETURN_PLACE, rvalue, span);
941
942 if self.add_to_required {
945 self.source.required_consts.as_mut().unwrap().push(promoted_op);
946 }
947
948 self.promoted.set_required_consts(self.required_consts);
949
950 self.promoted
951 }
952}
953
954impl<'a, 'tcx> MutVisitor<'tcx> for Promoter<'a, 'tcx> {
956 fn tcx(&self) -> TyCtxt<'tcx> {
957 self.tcx
958 }
959
960 fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
961 if self.is_temp_kind(*local) {
962 *local = self.promote_temp(*local);
963 }
964 }
965
966 fn visit_const_operand(&mut self, constant: &mut ConstOperand<'tcx>, _location: Location) {
967 if constant.const_.is_required_const() {
968 self.required_consts.push(*constant);
969 }
970
971 }
973}
974
975fn promote_candidates<'tcx>(
976 body: &mut Body<'tcx>,
977 tcx: TyCtxt<'tcx>,
978 mut temps: IndexVec<Local, TempState>,
979 candidates: Vec<Candidate>,
980) -> IndexVec<Promoted, Body<'tcx>> {
981 debug!(promote_candidates = ?candidates);
983
984 if candidates.is_empty() {
986 return IndexVec::new();
987 }
988
989 let mut promotions = IndexVec::new();
990
991 let mut extra_statements = vec![];
992 for candidate in candidates.into_iter().rev() {
993 let Location { block, statement_index } = candidate.location;
994 if let StatementKind::Assign(box (place, _)) = &body[block].statements[statement_index].kind
995 && let Some(local) = place.as_local()
996 {
997 if temps[local] == TempState::PromotedOut {
998 continue;
1000 }
1001 }
1002
1003 let initial_locals = iter::once(LocalDecl::new(tcx.types.never, body.span)).collect();
1005
1006 let mut scope = body.source_scopes[body.source_info(candidate.location).scope].clone();
1007 scope.parent_scope = None;
1008
1009 let mut promoted = Body::new(
1010 body.source, IndexVec::new(),
1012 IndexVec::from_elem_n(scope, 1),
1013 initial_locals,
1014 IndexVec::new(),
1015 0,
1016 vec![],
1017 body.span,
1018 None,
1019 body.tainted_by_errors,
1020 );
1021 promoted.phase = MirPhase::Analysis(AnalysisPhase::Initial);
1022
1023 let promoter = Promoter {
1024 promoted,
1025 tcx,
1026 source: body,
1027 temps: &mut temps,
1028 extra_statements: &mut extra_statements,
1029 keep_original: false,
1030 add_to_required: false,
1031 required_consts: Vec::new(),
1032 };
1033
1034 let mut promoted = promoter.promote_candidate(candidate, promotions.next_index());
1035 promoted.source.promoted = Some(promotions.next_index());
1036 promotions.push(promoted);
1037 }
1038
1039 extra_statements.sort_by_key(|&(loc, _)| cmp::Reverse(loc));
1042 for (loc, statement) in extra_statements {
1043 body[loc.block].statements.insert(loc.statement_index, statement);
1044 }
1045
1046 let promoted = |index: Local| temps[index] == TempState::PromotedOut;
1048 for block in body.basic_blocks_mut() {
1049 block.retain_statements(|statement| match &statement.kind {
1050 StatementKind::Assign(box (place, _)) => {
1051 if let Some(index) = place.as_local() {
1052 !promoted(index)
1053 } else {
1054 true
1055 }
1056 }
1057 StatementKind::StorageLive(index) | StatementKind::StorageDead(index) => {
1058 !promoted(*index)
1059 }
1060 _ => true,
1061 });
1062 let terminator = block.terminator_mut();
1063 if let TerminatorKind::Drop { place, target, .. } = &terminator.kind
1064 && let Some(index) = place.as_local()
1065 {
1066 if promoted(index) {
1067 terminator.kind = TerminatorKind::Goto { target: *target };
1068 }
1069 }
1070 }
1071
1072 promotions
1073}