1 //! A pass that promotes borrows of constant rvalues.
3 //! The rvalues considered constant are trees of temps,
4 //! each with exactly one initialization, and holding
5 //! a constant value with no interior mutability.
6 //! They are placed into a new MIR constant body in
7 //! `promoted` and the borrow rvalue is replaced with
8 //! a `Literal::Promoted` using the index into `promoted`
9 //! of that constant MIR.
11 //! This pass assumes that every use is dominated by an
12 //! initialization and can otherwise silence errors, if
13 //! move analysis runs after promotion on broken MIR.
16 use rustc_middle::mir;
17 use rustc_middle::mir::traversal::ReversePostorderIter;
18 use rustc_middle::mir::visit::{MutVisitor, MutatingUseContext, PlaceContext, Visitor};
19 use rustc_middle::mir::*;
20 use rustc_middle::ty::subst::InternalSubsts;
21 use rustc_middle::ty::{self, List, TyCtxt, TypeVisitable};
24 use rustc_index::vec::{Idx, IndexVec};
27 use std::{cmp, iter, mem};
29 use crate::transform::check_consts::{qualifs, ConstCx};
31 /// A `MirPass` for promotion.
33 /// Promotion is the extraction of promotable temps into separate MIR bodies so they can have
34 /// `'static` lifetime.
36 /// After this pass is run, `promoted_fragments` will hold the MIR body corresponding to each
37 /// newly created `Constant`.
39 pub struct PromoteTemps<'tcx> {
40 pub promoted_fragments: Cell<IndexVec<Promoted, Body<'tcx>>>,
43 impl<'tcx> MirPass<'tcx> for PromoteTemps<'tcx> {
44 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
45 // There's not really any point in promoting errorful MIR.
47 // This does not include MIR that failed const-checking, which we still try to promote.
48 if let Err(_) = body.return_ty().error_reported() {
49 debug!("PromoteTemps: MIR had errors");
52 if body.source.promoted.is_some() {
56 let mut rpo = traversal::reverse_postorder(body);
57 let ccx = ConstCx::new(tcx, body);
58 let (mut temps, all_candidates) = collect_temps_and_candidates(&ccx, &mut rpo);
60 let promotable_candidates = validate_candidates(&ccx, &mut temps, &all_candidates);
62 let promoted = promote_candidates(body, tcx, temps, promotable_candidates);
63 self.promoted_fragments.set(promoted);
67 /// State of a temporary during collection and promotion.
68 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
70 /// No references to this temp.
72 /// One direct assignment and any number of direct uses.
73 /// A borrow of this temp is promotable if the assigned
74 /// value is qualified as constant.
75 Defined { location: Location, uses: usize, valid: Result<(), ()> },
76 /// Any other combination of assignments/uses.
78 /// This temp was part of an rvalue which got extracted
79 /// during promotion and needs cleanup.
84 pub fn is_promotable(&self) -> bool {
85 debug!("is_promotable: self={:?}", self);
86 matches!(self, TempState::Defined { .. })
90 /// A "root candidate" for promotion, which will become the
91 /// returned value in a promoted MIR, unless it's a subset
92 /// of a larger candidate.
93 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
94 pub struct Candidate {
98 struct Collector<'a, 'tcx> {
99 ccx: &'a ConstCx<'a, 'tcx>,
100 temps: IndexVec<Local, TempState>,
101 candidates: Vec<Candidate>,
104 impl<'tcx> Visitor<'tcx> for Collector<'_, 'tcx> {
105 fn visit_local(&mut self, index: Local, context: PlaceContext, location: Location) {
106 debug!("visit_local: index={:?} context={:?} location={:?}", index, context, location);
107 // We're only interested in temporaries and the return place
108 match self.ccx.body.local_kind(index) {
109 LocalKind::Temp | LocalKind::ReturnPointer => {}
110 LocalKind::Arg | LocalKind::Var => return,
113 // Ignore drops, if the temp gets promoted,
114 // then it's constant and thus drop is noop.
115 // Non-uses are also irrelevant.
116 if context.is_drop() || !context.is_use() {
118 "visit_local: context.is_drop={:?} context.is_use={:?}",
125 let temp = &mut self.temps[index];
126 debug!("visit_local: temp={:?}", temp);
127 if *temp == TempState::Undefined {
129 PlaceContext::MutatingUse(MutatingUseContext::Store)
130 | PlaceContext::MutatingUse(MutatingUseContext::Call) => {
131 *temp = TempState::Defined { location, uses: 0, valid: Err(()) };
134 _ => { /* mark as unpromotable below */ }
136 } else if let TempState::Defined { uses, .. } = temp {
137 // We always allow borrows, even mutable ones, as we need
138 // to promote mutable borrows of some ZSTs e.g., `&mut []`.
139 let allowed_use = match context {
140 PlaceContext::MutatingUse(MutatingUseContext::Borrow)
141 | PlaceContext::NonMutatingUse(_) => true,
142 PlaceContext::MutatingUse(_) | PlaceContext::NonUse(_) => false,
144 debug!("visit_local: allowed_use={:?}", allowed_use);
149 /* mark as unpromotable below */
151 *temp = TempState::Unpromotable;
154 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
155 self.super_rvalue(rvalue, location);
159 self.candidates.push(Candidate { location });
166 pub fn collect_temps_and_candidates<'tcx>(
167 ccx: &ConstCx<'_, 'tcx>,
168 rpo: &mut ReversePostorderIter<'_, 'tcx>,
169 ) -> (IndexVec<Local, TempState>, Vec<Candidate>) {
170 let mut collector = Collector {
171 temps: IndexVec::from_elem(TempState::Undefined, &ccx.body.local_decls),
175 for (bb, data) in rpo {
176 collector.visit_basic_block_data(bb, data);
178 (collector.temps, collector.candidates)
181 /// Checks whether locals that appear in a promotion context (`Candidate`) are actually promotable.
183 /// This wraps an `Item`, and has access to all fields of that `Item` via `Deref` coercion.
184 struct Validator<'a, 'tcx> {
185 ccx: &'a ConstCx<'a, 'tcx>,
186 temps: &'a mut IndexVec<Local, TempState>,
189 impl<'a, 'tcx> std::ops::Deref for Validator<'a, 'tcx> {
190 type Target = ConstCx<'a, 'tcx>;
192 fn deref(&self) -> &Self::Target {
199 impl<'tcx> Validator<'_, 'tcx> {
200 fn validate_candidate(&mut self, candidate: Candidate) -> Result<(), Unpromotable> {
201 let loc = candidate.location;
202 let statement = &self.body[loc.block].statements[loc.statement_index];
203 match &statement.kind {
204 StatementKind::Assign(box (_, Rvalue::Ref(_, kind, place))) => {
205 // We can only promote interior borrows of promotable temps (non-temps
206 // don't get promoted anyway).
207 self.validate_local(place.local)?;
209 // The reference operation itself must be promotable.
210 // (Needs to come after `validate_local` to avoid ICEs.)
211 self.validate_ref(*kind, place)?;
213 // We do not check all the projections (they do not get promoted anyway),
214 // but we do stay away from promoting anything involving a dereference.
215 if place.projection.contains(&ProjectionElem::Deref) {
216 return Err(Unpromotable);
225 // FIXME(eddyb) maybe cache this?
226 fn qualif_local<Q: qualifs::Qualif>(&mut self, local: Local) -> bool {
227 if let TempState::Defined { location: loc, .. } = self.temps[local] {
228 let num_stmts = self.body[loc.block].statements.len();
230 if loc.statement_index < num_stmts {
231 let statement = &self.body[loc.block].statements[loc.statement_index];
232 match &statement.kind {
233 StatementKind::Assign(box (_, rhs)) => qualifs::in_rvalue::<Q, _>(
235 &mut |l| self.qualif_local::<Q>(l),
240 statement.source_info.span,
241 "{:?} is not an assignment",
247 let terminator = self.body[loc.block].terminator();
248 match &terminator.kind {
249 TerminatorKind::Call { .. } => {
250 let return_ty = self.body.local_decls[local].ty;
251 Q::in_any_value_of_ty(&self.ccx, return_ty)
254 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
263 fn validate_local(&mut self, local: Local) -> Result<(), Unpromotable> {
264 if let TempState::Defined { location: loc, uses, valid } = self.temps[local] {
265 // We cannot promote things that need dropping, since the promoted value
266 // would not get dropped.
267 if self.qualif_local::<qualifs::NeedsDrop>(local) {
268 return Err(Unpromotable);
272 let block = &self.body[loc.block];
273 let num_stmts = block.statements.len();
275 if loc.statement_index < num_stmts {
276 let statement = &block.statements[loc.statement_index];
277 match &statement.kind {
278 StatementKind::Assign(box (_, rhs)) => self.validate_rvalue(rhs),
281 statement.source_info.span,
282 "{:?} is not an assignment",
288 let terminator = block.terminator();
289 match &terminator.kind {
290 TerminatorKind::Call { func, args, .. } => {
291 self.validate_call(func, args)
293 TerminatorKind::Yield { .. } => Err(Unpromotable),
295 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
300 self.temps[local] = match ok {
301 Ok(()) => TempState::Defined { location: loc, uses, valid: Ok(()) },
302 Err(_) => TempState::Unpromotable,
311 fn validate_place(&mut self, place: PlaceRef<'tcx>) -> Result<(), Unpromotable> {
312 match place.last_projection() {
313 None => self.validate_local(place.local),
314 Some((place_base, elem)) => {
315 // Validate topmost projection, then recurse.
317 ProjectionElem::Deref => {
318 let mut promotable = false;
319 // When a static is used by-value, that gets desugared to `*STATIC_ADDR`,
320 // and we need to be able to promote this. So check if this deref matches
321 // that specific pattern.
323 // We need to make sure this is a `Deref` of a local with no further projections.
324 // Discussion can be found at
325 // https://github.com/rust-lang/rust/pull/74945#discussion_r463063247
326 if let Some(local) = place_base.as_local() {
327 if let TempState::Defined { location, .. } = self.temps[local] {
328 let def_stmt = self.body[location.block]
330 .get(location.statement_index);
331 if let Some(Statement {
333 StatementKind::Assign(box (
335 Rvalue::Use(Operand::Constant(c)),
340 if let Some(did) = c.check_static_ptr(self.tcx) {
341 // Evaluating a promoted may not read statics except if it got
342 // promoted from a static (this is a CTFE check). So we
343 // can only promote static accesses inside statics.
344 if let Some(hir::ConstContext::Static(..)) = self.const_kind
346 if !self.tcx.is_thread_local_static(did) {
355 return Err(Unpromotable);
358 ProjectionElem::OpaqueCast(..) | ProjectionElem::Downcast(..) => {
359 return Err(Unpromotable);
362 ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } => {}
364 ProjectionElem::Index(local) => {
365 let mut promotable = false;
366 // Only accept if we can predict the index and are indexing an array.
368 if let TempState::Defined { location: loc, .. } = self.temps[local] {
369 let block = &self.body[loc.block];
370 if loc.statement_index < block.statements.len() {
371 let statement = &block.statements[loc.statement_index];
372 match &statement.kind {
373 StatementKind::Assign(box (
375 Rvalue::Use(Operand::Constant(c)),
376 )) => c.literal.try_eval_usize(self.tcx, self.param_env),
385 if let Some(idx) = val {
386 // Determine the type of the thing we are indexing.
387 let ty = place_base.ty(self.body, self.tcx).ty;
389 ty::Array(_, len) => {
390 // It's an array; determine its length.
391 if let Some(len) = len.try_eval_usize(self.tcx, self.param_env)
393 // If the index is in-bounds, go ahead.
403 return Err(Unpromotable);
406 self.validate_local(local)?;
409 ProjectionElem::Field(..) => {
410 let base_ty = place_base.ty(self.body, self.tcx).ty;
411 if base_ty.is_union() {
412 // No promotion of union field accesses.
413 return Err(Unpromotable);
418 self.validate_place(place_base)
423 fn validate_operand(&mut self, operand: &Operand<'tcx>) -> Result<(), Unpromotable> {
425 Operand::Copy(place) | Operand::Move(place) => self.validate_place(place.as_ref()),
427 // The qualifs for a constant (e.g. `HasMutInterior`) are checked in
428 // `validate_rvalue` upon access.
429 Operand::Constant(c) => {
430 if let Some(def_id) = c.check_static_ptr(self.tcx) {
431 // Only allow statics (not consts) to refer to other statics.
432 // FIXME(eddyb) does this matter at all for promotion?
433 // FIXME(RalfJung) it makes little sense to not promote this in `fn`/`const fn`,
434 // and in `const` this cannot occur anyway. The only concern is that we might
435 // promote even `let x = &STATIC` which would be useless, but this applies to
436 // promotion inside statics as well.
437 let is_static = matches!(self.const_kind, Some(hir::ConstContext::Static(_)));
439 return Err(Unpromotable);
442 let is_thread_local = self.tcx.is_thread_local_static(def_id);
444 return Err(Unpromotable);
453 fn validate_ref(&mut self, kind: BorrowKind, place: &Place<'tcx>) -> Result<(), Unpromotable> {
455 // Reject these borrow types just to be safe.
456 // FIXME(RalfJung): could we allow them? Should we? No point in it until we have a usecase.
457 BorrowKind::Shallow | BorrowKind::Unique => return Err(Unpromotable),
459 BorrowKind::Shared => {
460 let has_mut_interior = self.qualif_local::<qualifs::HasMutInterior>(place.local);
461 if has_mut_interior {
462 return Err(Unpromotable);
466 BorrowKind::Mut { .. } => {
467 let ty = place.ty(self.body, self.tcx).ty;
469 // In theory, any zero-sized value could be borrowed
470 // mutably without consequences. However, only &mut []
471 // is allowed right now.
472 if let ty::Array(_, len) = ty.kind() {
473 match len.try_eval_usize(self.tcx, self.param_env) {
475 _ => return Err(Unpromotable),
478 return Err(Unpromotable);
486 fn validate_rvalue(&mut self, rvalue: &Rvalue<'tcx>) -> Result<(), Unpromotable> {
488 Rvalue::Use(operand) | Rvalue::Repeat(operand, _) => {
489 self.validate_operand(operand)?;
491 Rvalue::CopyForDeref(place) => {
492 let op = &Operand::Copy(*place);
493 self.validate_operand(op)?
496 Rvalue::Discriminant(place) | Rvalue::Len(place) => {
497 self.validate_place(place.as_ref())?
500 Rvalue::ThreadLocalRef(_) => return Err(Unpromotable),
502 // ptr-to-int casts are not possible in consts and thus not promotable
503 Rvalue::Cast(CastKind::PointerExposeAddress, _, _) => return Err(Unpromotable),
505 // all other casts including int-to-ptr casts are fine, they just use the integer value
507 Rvalue::Cast(_, operand, _) => {
508 self.validate_operand(operand)?;
511 Rvalue::NullaryOp(op, _) => match op {
513 NullOp::AlignOf => {}
516 Rvalue::ShallowInitBox(_, _) => return Err(Unpromotable),
518 Rvalue::UnaryOp(op, operand) => {
520 // These operations can never fail.
521 UnOp::Neg | UnOp::Not => {}
524 self.validate_operand(operand)?;
527 Rvalue::BinaryOp(op, box (lhs, rhs)) | Rvalue::CheckedBinaryOp(op, box (lhs, rhs)) => {
529 let lhs_ty = lhs.ty(self.body, self.tcx);
531 if let ty::RawPtr(_) | ty::FnPtr(..) = lhs_ty.kind() {
532 // Raw and fn pointer operations are not allowed inside consts and thus not promotable.
543 return Err(Unpromotable);
547 BinOp::Div | BinOp::Rem => {
548 if lhs_ty.is_integral() {
549 // Integer division: the RHS must be a non-zero const.
550 let const_val = match rhs {
551 Operand::Constant(c) => {
552 c.literal.try_eval_bits(self.tcx, self.param_env, lhs_ty)
557 Some(x) if x != 0 => {} // okay
558 _ => return Err(Unpromotable), // value not known or 0 -- not okay
562 // The remaining operations can never fail.
580 self.validate_operand(lhs)?;
581 self.validate_operand(rhs)?;
584 Rvalue::AddressOf(_, place) => {
585 // We accept `&raw *`, i.e., raw reborrows -- creating a raw pointer is
586 // no problem, only using it is.
587 if let Some((place_base, ProjectionElem::Deref)) = place.as_ref().last_projection()
589 let base_ty = place_base.ty(self.body, self.tcx).ty;
590 if let ty::Ref(..) = base_ty.kind() {
591 return self.validate_place(place_base);
594 return Err(Unpromotable);
597 Rvalue::Ref(_, kind, place) => {
598 // Special-case reborrows to be more like a copy of the reference.
599 let mut place_simplified = place.as_ref();
600 if let Some((place_base, ProjectionElem::Deref)) =
601 place_simplified.last_projection()
603 let base_ty = place_base.ty(self.body, self.tcx).ty;
604 if let ty::Ref(..) = base_ty.kind() {
605 place_simplified = place_base;
609 self.validate_place(place_simplified)?;
611 // Check that the reference is fine (using the original place!).
612 // (Needs to come after `validate_place` to avoid ICEs.)
613 self.validate_ref(*kind, place)?;
616 Rvalue::Aggregate(_, operands) => {
618 self.validate_operand(o)?;
628 callee: &Operand<'tcx>,
629 args: &[Operand<'tcx>],
630 ) -> Result<(), Unpromotable> {
631 let fn_ty = callee.ty(self.body, self.tcx);
633 // Inside const/static items, we promote all (eligible) function calls.
634 // Everywhere else, we require `#[rustc_promotable]` on the callee.
635 let promote_all_const_fn = matches!(
637 Some(hir::ConstContext::Static(_) | hir::ConstContext::Const)
639 if !promote_all_const_fn {
640 if let ty::FnDef(def_id, _) = *fn_ty.kind() {
641 // Never promote runtime `const fn` calls of
642 // functions without `#[rustc_promotable]`.
643 if !self.tcx.is_promotable_const_fn(def_id) {
644 return Err(Unpromotable);
649 let is_const_fn = match *fn_ty.kind() {
650 ty::FnDef(def_id, _) => self.tcx.is_const_fn_raw(def_id),
654 return Err(Unpromotable);
657 self.validate_operand(callee)?;
659 self.validate_operand(arg)?;
666 // FIXME(eddyb) remove the differences for promotability in `static`, `const`, `const fn`.
667 pub fn validate_candidates(
668 ccx: &ConstCx<'_, '_>,
669 temps: &mut IndexVec<Local, TempState>,
670 candidates: &[Candidate],
671 ) -> Vec<Candidate> {
672 let mut validator = Validator { ccx, temps };
677 .filter(|&candidate| validator.validate_candidate(candidate).is_ok())
681 struct Promoter<'a, 'tcx> {
683 source: &'a mut Body<'tcx>,
684 promoted: Body<'tcx>,
685 temps: &'a mut IndexVec<Local, TempState>,
686 extra_statements: &'a mut Vec<(Location, Statement<'tcx>)>,
688 /// If true, all nested temps are also kept in the
689 /// source MIR, not moved to the promoted MIR.
693 impl<'a, 'tcx> Promoter<'a, 'tcx> {
694 fn new_block(&mut self) -> BasicBlock {
695 let span = self.promoted.span;
696 self.promoted.basic_blocks_mut().push(BasicBlockData {
698 terminator: Some(Terminator {
699 source_info: SourceInfo::outermost(span),
700 kind: TerminatorKind::Return,
706 fn assign(&mut self, dest: Local, rvalue: Rvalue<'tcx>, span: Span) {
707 let last = self.promoted.basic_blocks.last().unwrap();
708 let data = &mut self.promoted[last];
709 data.statements.push(Statement {
710 source_info: SourceInfo::outermost(span),
711 kind: StatementKind::Assign(Box::new((Place::from(dest), rvalue))),
715 fn is_temp_kind(&self, local: Local) -> bool {
716 self.source.local_kind(local) == LocalKind::Temp
719 /// Copies the initialization of this temp to the
720 /// promoted MIR, recursing through temps.
721 fn promote_temp(&mut self, temp: Local) -> Local {
722 let old_keep_original = self.keep_original;
723 let loc = match self.temps[temp] {
724 TempState::Defined { location, uses, .. } if uses > 0 => {
726 self.keep_original = true;
731 span_bug!(self.promoted.span, "{:?} not promotable: {:?}", temp, state);
734 if !self.keep_original {
735 self.temps[temp] = TempState::PromotedOut;
738 let num_stmts = self.source[loc.block].statements.len();
739 let new_temp = self.promoted.local_decls.push(LocalDecl::new(
740 self.source.local_decls[temp].ty,
741 self.source.local_decls[temp].source_info.span,
744 debug!("promote({:?} @ {:?}/{:?}, {:?})", temp, loc, num_stmts, self.keep_original);
746 // First, take the Rvalue or Call out of the source MIR,
747 // or duplicate it, depending on keep_original.
748 if loc.statement_index < num_stmts {
749 let (mut rvalue, source_info) = {
750 let statement = &mut self.source[loc.block].statements[loc.statement_index];
751 let StatementKind::Assign(box (_, rhs)) = &mut statement.kind else {
753 statement.source_info.span,
754 "{:?} is not an assignment",
760 if self.keep_original {
763 let unit = Rvalue::Use(Operand::Constant(Box::new(Constant {
764 span: statement.source_info.span,
766 literal: ConstantKind::zero_sized(self.tcx.types.unit),
768 mem::replace(rhs, unit)
770 statement.source_info,
774 self.visit_rvalue(&mut rvalue, loc);
775 self.assign(new_temp, rvalue, source_info.span);
777 let terminator = if self.keep_original {
778 self.source[loc.block].terminator().clone()
780 let terminator = self.source[loc.block].terminator_mut();
781 let target = match &terminator.kind {
782 TerminatorKind::Call { target: Some(target), .. } => *target,
784 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
788 source_info: terminator.source_info,
789 kind: mem::replace(&mut terminator.kind, TerminatorKind::Goto { target }),
793 match terminator.kind {
794 TerminatorKind::Call { mut func, mut args, from_hir_call, fn_span, .. } => {
795 self.visit_operand(&mut func, loc);
796 for arg in &mut args {
797 self.visit_operand(arg, loc);
800 let last = self.promoted.basic_blocks.last().unwrap();
801 let new_target = self.new_block();
803 *self.promoted[last].terminator_mut() = Terminator {
804 kind: TerminatorKind::Call {
808 destination: Place::from(new_temp),
809 target: Some(new_target),
813 source_info: SourceInfo::outermost(terminator.source_info.span),
818 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
823 self.keep_original = old_keep_original;
827 fn promote_candidate(mut self, candidate: Candidate, next_promoted_id: usize) -> Body<'tcx> {
828 let def = self.source.source.with_opt_param();
830 let promoted = &mut self.promoted;
831 let promoted_id = Promoted::new(next_promoted_id);
833 let mut promoted_operand = |ty, span| {
834 promoted.span = span;
835 promoted.local_decls[RETURN_PLACE] = LocalDecl::new(ty, span);
836 let substs = tcx.erase_regions(InternalSubsts::identity_for_item(tcx, def.did));
837 let uneval = mir::UnevaluatedConst { def, substs, promoted: Some(promoted_id) };
839 Operand::Constant(Box::new(Constant {
842 literal: ConstantKind::Unevaluated(uneval, ty),
846 let blocks = self.source.basic_blocks.as_mut();
847 let local_decls = &mut self.source.local_decls;
848 let loc = candidate.location;
849 let statement = &mut blocks[loc.block].statements[loc.statement_index];
850 let StatementKind::Assign(box (_, Rvalue::Ref(region, borrow_kind, place))) = &mut statement.kind else {
854 // Use the underlying local for this (necessarily interior) borrow.
855 let ty = local_decls[place.local].ty;
856 let span = statement.source_info.span;
858 let ref_ty = tcx.mk_ref(
859 tcx.lifetimes.re_erased,
860 ty::TypeAndMut { ty, mutbl: borrow_kind.to_mutbl_lossy() },
863 *region = tcx.lifetimes.re_erased;
865 let mut projection = vec![PlaceElem::Deref];
866 projection.extend(place.projection);
867 place.projection = tcx.intern_place_elems(&projection);
869 // Create a temp to hold the promoted reference.
870 // This is because `*r` requires `r` to be a local,
871 // otherwise we would use the `promoted` directly.
872 let mut promoted_ref = LocalDecl::new(ref_ty, span);
873 promoted_ref.source_info = statement.source_info;
874 let promoted_ref = local_decls.push(promoted_ref);
875 assert_eq!(self.temps.push(TempState::Unpromotable), promoted_ref);
877 let promoted_ref_statement = Statement {
878 source_info: statement.source_info,
879 kind: StatementKind::Assign(Box::new((
880 Place::from(promoted_ref),
881 Rvalue::Use(promoted_operand(ref_ty, span)),
884 self.extra_statements.push((loc, promoted_ref_statement));
887 tcx.lifetimes.re_erased,
890 local: mem::replace(&mut place.local, promoted_ref),
891 projection: List::empty(),
896 assert_eq!(self.new_block(), START_BLOCK);
899 Location { block: BasicBlock::new(0), statement_index: usize::MAX },
902 let span = self.promoted.span;
903 self.assign(RETURN_PLACE, rvalue, span);
908 /// Replaces all temporaries with their promoted counterparts.
909 impl<'a, 'tcx> MutVisitor<'tcx> for Promoter<'a, 'tcx> {
910 fn tcx(&self) -> TyCtxt<'tcx> {
914 fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
915 if self.is_temp_kind(*local) {
916 *local = self.promote_temp(*local);
921 pub fn promote_candidates<'tcx>(
922 body: &mut Body<'tcx>,
924 mut temps: IndexVec<Local, TempState>,
925 candidates: Vec<Candidate>,
926 ) -> IndexVec<Promoted, Body<'tcx>> {
927 // Visit candidates in reverse, in case they're nested.
928 debug!("promote_candidates({:?})", candidates);
930 let mut promotions = IndexVec::new();
932 let mut extra_statements = vec![];
933 for candidate in candidates.into_iter().rev() {
934 let Location { block, statement_index } = candidate.location;
935 if let StatementKind::Assign(box (place, _)) = &body[block].statements[statement_index].kind
937 if let Some(local) = place.as_local() {
938 if temps[local] == TempState::PromotedOut {
945 // Declare return place local so that `mir::Body::new` doesn't complain.
946 let initial_locals = iter::once(LocalDecl::new(tcx.types.never, body.span)).collect();
948 let mut scope = body.source_scopes[body.source_info(candidate.location).scope].clone();
949 scope.parent_scope = None;
951 let mut promoted = Body::new(
952 body.source, // `promoted` gets filled in below
954 IndexVec::from_elem_n(scope, 1),
960 body.generator_kind(),
961 body.tainted_by_errors,
963 promoted.phase = MirPhase::Analysis(AnalysisPhase::Initial);
965 let promoter = Promoter {
970 extra_statements: &mut extra_statements,
971 keep_original: false,
974 let mut promoted = promoter.promote_candidate(candidate, promotions.len());
975 promoted.source.promoted = Some(promotions.next_index());
976 promotions.push(promoted);
979 // Insert each of `extra_statements` before its indicated location, which
980 // has to be done in reverse location order, to not invalidate the rest.
981 extra_statements.sort_by_key(|&(loc, _)| cmp::Reverse(loc));
982 for (loc, statement) in extra_statements {
983 body[loc.block].statements.insert(loc.statement_index, statement);
986 // Eliminate assignments to, and drops of promoted temps.
987 let promoted = |index: Local| temps[index] == TempState::PromotedOut;
988 for block in body.basic_blocks_mut() {
989 block.statements.retain(|statement| match &statement.kind {
990 StatementKind::Assign(box (place, _)) => {
991 if let Some(index) = place.as_local() {
997 StatementKind::StorageLive(index) | StatementKind::StorageDead(index) => {
1002 let terminator = block.terminator_mut();
1003 if let TerminatorKind::Drop { place, target, .. } = &terminator.kind {
1004 if let Some(index) = place.as_local() {
1005 if promoted(index) {
1006 terminator.kind = TerminatorKind::Goto { target: *target };
1015 /// This function returns `true` if the function being called in the array
1016 /// repeat expression is a `const` function.
1017 pub fn is_const_fn_in_array_repeat_expression<'tcx>(
1018 ccx: &ConstCx<'_, 'tcx>,
1019 place: &Place<'tcx>,
1022 match place.as_local() {
1023 // rule out cases such as: `let my_var = some_fn(); [my_var; N]`
1024 Some(local) if body.local_decls[local].is_user_variable() => return false,
1025 None => return false,
1029 for block in body.basic_blocks.iter() {
1030 if let Some(Terminator { kind: TerminatorKind::Call { func, destination, .. }, .. }) =
1033 if let Operand::Constant(box Constant { literal, .. }) = func {
1034 if let ty::FnDef(def_id, _) = *literal.ty().kind() {
1035 if destination == place {
1036 if ccx.tcx.is_const_fn(def_id) {