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