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