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.
15 use rustc_ast::LitKind;
17 use rustc_hir::def_id::DefId;
18 use rustc_middle::mir::traversal::ReversePostorder;
19 use rustc_middle::mir::visit::{MutVisitor, MutatingUseContext, PlaceContext, Visitor};
20 use rustc_middle::mir::*;
21 use rustc_middle::ty::cast::CastTy;
22 use rustc_middle::ty::subst::InternalSubsts;
23 use rustc_middle::ty::{self, List, TyCtxt, TypeFoldable};
24 use rustc_span::symbol::sym;
27 use rustc_index::vec::{Idx, IndexVec};
28 use rustc_target::spec::abi::Abi;
31 use std::{cmp, iter, mem};
33 use crate::const_eval::{is_const_fn, is_unstable_const_fn};
34 use crate::transform::check_consts::{is_lang_panic_fn, qualifs, ConstCx};
35 use crate::transform::MirPass;
37 /// A `MirPass` for promotion.
39 /// Promotion is the extraction of promotable temps into separate MIR bodies. This pass also emits
40 /// errors when promotion of `#[rustc_args_required_const]` arguments fails.
42 /// After this pass is run, `promoted_fragments` will hold the MIR body corresponding to each
43 /// newly created `Constant`.
45 pub struct PromoteTemps<'tcx> {
46 pub promoted_fragments: Cell<IndexVec<Promoted, Body<'tcx>>>,
49 impl<'tcx> MirPass<'tcx> for PromoteTemps<'tcx> {
50 fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
51 // There's not really any point in promoting errorful MIR.
53 // This does not include MIR that failed const-checking, which we still try to promote.
54 if body.return_ty().references_error() {
55 tcx.sess.delay_span_bug(body.span, "PromoteTemps: MIR had errors");
59 if body.source.promoted.is_some() {
63 let mut rpo = traversal::reverse_postorder(body);
64 let ccx = ConstCx::new(tcx, body);
65 let (temps, all_candidates) = collect_temps_and_candidates(&ccx, &mut rpo);
67 let promotable_candidates = validate_candidates(&ccx, &temps, &all_candidates);
69 let promoted = promote_candidates(body, tcx, temps, promotable_candidates);
70 self.promoted_fragments.set(promoted);
74 /// State of a temporary during collection and promotion.
75 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
77 /// No references to this temp.
79 /// One direct assignment and any number of direct uses.
80 /// A borrow of this temp is promotable if the assigned
81 /// value is qualified as constant.
82 Defined { location: Location, uses: usize },
83 /// Any other combination of assignments/uses.
85 /// This temp was part of an rvalue which got extracted
86 /// during promotion and needs cleanup.
91 pub fn is_promotable(&self) -> bool {
92 debug!("is_promotable: self={:?}", self);
93 matches!(self, TempState::Defined { .. })
97 /// A "root candidate" for promotion, which will become the
98 /// returned value in a promoted MIR, unless it's a subset
99 /// of a larger candidate.
100 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
102 /// Borrow of a constant temporary, candidate for lifetime extension.
105 /// Currently applied to function calls where the callee has the unstable
106 /// `#[rustc_args_required_const]` attribute as well as the SIMD shuffle
107 /// intrinsic. The intrinsic requires the arguments are indeed constant and
108 /// the attribute currently provides the semantic requirement that arguments
109 /// must be constant.
110 Argument { bb: BasicBlock, index: usize },
112 /// `const` operand in asm!.
113 InlineAsm { bb: BasicBlock, index: usize },
117 /// Returns `true` if we should use the "explicit" rules for promotability for this `Candidate`.
118 fn forces_explicit_promotion(&self) -> bool {
120 Candidate::Ref(_) => false,
121 Candidate::Argument { .. } | Candidate::InlineAsm { .. } => true,
125 fn source_info(&self, body: &Body<'_>) -> SourceInfo {
127 Candidate::Ref(location) => *body.source_info(*location),
128 Candidate::Argument { bb, .. } | Candidate::InlineAsm { bb, .. } => {
129 *body.source_info(body.terminator_loc(*bb))
135 fn args_required_const(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Vec<usize>> {
136 let attrs = tcx.get_attrs(def_id);
137 let attr = attrs.iter().find(|a| tcx.sess.check_name(a, sym::rustc_args_required_const))?;
138 let mut ret = vec![];
139 for meta in attr.meta_item_list()? {
140 match meta.literal()?.kind {
141 LitKind::Int(a, _) => {
142 ret.push(a as usize);
144 _ => bug!("invalid arg index"),
150 struct Collector<'a, 'tcx> {
151 ccx: &'a ConstCx<'a, 'tcx>,
152 temps: IndexVec<Local, TempState>,
153 candidates: Vec<Candidate>,
156 impl<'tcx> Visitor<'tcx> for Collector<'_, 'tcx> {
157 fn visit_local(&mut self, &index: &Local, context: PlaceContext, location: Location) {
158 debug!("visit_local: index={:?} context={:?} location={:?}", index, context, location);
159 // We're only interested in temporaries and the return place
160 match self.ccx.body.local_kind(index) {
161 LocalKind::Temp | LocalKind::ReturnPointer => {}
162 LocalKind::Arg | LocalKind::Var => return,
165 // Ignore drops, if the temp gets promoted,
166 // then it's constant and thus drop is noop.
167 // Non-uses are also irrelevant.
168 if context.is_drop() || !context.is_use() {
170 "visit_local: context.is_drop={:?} context.is_use={:?}",
177 let temp = &mut self.temps[index];
178 debug!("visit_local: temp={:?}", temp);
179 if *temp == TempState::Undefined {
181 PlaceContext::MutatingUse(MutatingUseContext::Store)
182 | PlaceContext::MutatingUse(MutatingUseContext::Call) => {
183 *temp = TempState::Defined { location, uses: 0 };
186 _ => { /* mark as unpromotable below */ }
188 } else if let TempState::Defined { ref mut uses, .. } = *temp {
189 // We always allow borrows, even mutable ones, as we need
190 // to promote mutable borrows of some ZSTs e.g., `&mut []`.
191 let allowed_use = match context {
192 PlaceContext::MutatingUse(MutatingUseContext::Borrow)
193 | PlaceContext::NonMutatingUse(_) => true,
194 PlaceContext::MutatingUse(_) | PlaceContext::NonUse(_) => false,
196 debug!("visit_local: allowed_use={:?}", allowed_use);
201 /* mark as unpromotable below */
203 *temp = TempState::Unpromotable;
206 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
207 self.super_rvalue(rvalue, location);
211 self.candidates.push(Candidate::Ref(location));
217 fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
218 self.super_terminator(terminator, location);
220 match terminator.kind {
221 TerminatorKind::Call { ref func, .. } => {
222 if let ty::FnDef(def_id, _) = *func.ty(self.ccx.body, self.ccx.tcx).kind() {
223 let fn_sig = self.ccx.tcx.fn_sig(def_id);
224 if let Abi::RustIntrinsic | Abi::PlatformIntrinsic = fn_sig.abi() {
225 let name = self.ccx.tcx.item_name(def_id);
226 // FIXME(eddyb) use `#[rustc_args_required_const(2)]` for shuffles.
227 if name.as_str().starts_with("simd_shuffle") {
229 .push(Candidate::Argument { bb: location.block, index: 2 });
231 return; // Don't double count `simd_shuffle` candidates
235 if let Some(constant_args) = args_required_const(self.ccx.tcx, def_id) {
236 for index in constant_args {
237 self.candidates.push(Candidate::Argument { bb: location.block, index });
242 TerminatorKind::InlineAsm { ref operands, .. } => {
243 for (index, op) in operands.iter().enumerate() {
244 if let InlineAsmOperand::Const { .. } = op {
245 self.candidates.push(Candidate::InlineAsm { bb: location.block, index })
254 pub fn collect_temps_and_candidates(
255 ccx: &ConstCx<'mir, 'tcx>,
256 rpo: &mut ReversePostorder<'_, 'tcx>,
257 ) -> (IndexVec<Local, TempState>, Vec<Candidate>) {
258 let mut collector = Collector {
259 temps: IndexVec::from_elem(TempState::Undefined, &ccx.body.local_decls),
263 for (bb, data) in rpo {
264 collector.visit_basic_block_data(bb, data);
266 (collector.temps, collector.candidates)
269 /// Checks whether locals that appear in a promotion context (`Candidate`) are actually promotable.
271 /// This wraps an `Item`, and has access to all fields of that `Item` via `Deref` coercion.
272 struct Validator<'a, 'tcx> {
273 ccx: &'a ConstCx<'a, 'tcx>,
274 temps: &'a IndexVec<Local, TempState>,
276 /// Explicit promotion happens e.g. for constant arguments declared via
277 /// `rustc_args_required_const`.
278 /// Implicit promotion has almost the same rules, except that disallows `const fn`
279 /// except for those marked `#[rustc_promotable]`. This is to avoid changing
280 /// a legitimate run-time operation into a failing compile-time operation
281 /// e.g. due to addresses being compared inside the function.
285 impl std::ops::Deref for Validator<'a, 'tcx> {
286 type Target = ConstCx<'a, 'tcx>;
288 fn deref(&self) -> &Self::Target {
295 impl<'tcx> Validator<'_, 'tcx> {
296 fn validate_candidate(&self, candidate: Candidate) -> Result<(), Unpromotable> {
298 Candidate::Ref(loc) => {
299 assert!(!self.explicit);
301 let statement = &self.body[loc.block].statements[loc.statement_index];
302 match &statement.kind {
303 StatementKind::Assign(box (_, Rvalue::Ref(_, kind, place))) => {
304 // We can only promote interior borrows of promotable temps (non-temps
305 // don't get promoted anyway).
306 self.validate_local(place.local)?;
308 // The reference operation itself must be promotable.
309 // (Needs to come after `validate_local` to avoid ICEs.)
310 self.validate_ref(*kind, place)?;
312 // We do not check all the projections (they do not get promoted anyway),
313 // but we do stay away from promoting anything involving a dereference.
314 if place.projection.contains(&ProjectionElem::Deref) {
315 return Err(Unpromotable);
318 // We cannot promote things that need dropping, since the promoted value
319 // would not get dropped.
320 if self.qualif_local::<qualifs::NeedsDrop>(place.local) {
321 return Err(Unpromotable);
329 Candidate::Argument { bb, index } => {
330 assert!(self.explicit);
332 let terminator = self.body[bb].terminator();
333 match &terminator.kind {
334 TerminatorKind::Call { args, .. } => self.validate_operand(&args[index]),
338 Candidate::InlineAsm { bb, index } => {
339 assert!(self.explicit);
341 let terminator = self.body[bb].terminator();
342 match &terminator.kind {
343 TerminatorKind::InlineAsm { operands, .. } => match &operands[index] {
344 InlineAsmOperand::Const { value } => self.validate_operand(value),
353 // FIXME(eddyb) maybe cache this?
354 fn qualif_local<Q: qualifs::Qualif>(&self, local: Local) -> bool {
355 if let TempState::Defined { location: loc, .. } = self.temps[local] {
356 let num_stmts = self.body[loc.block].statements.len();
358 if loc.statement_index < num_stmts {
359 let statement = &self.body[loc.block].statements[loc.statement_index];
360 match &statement.kind {
361 StatementKind::Assign(box (_, rhs)) => qualifs::in_rvalue::<Q, _>(
363 &mut |l| self.qualif_local::<Q>(l),
368 statement.source_info.span,
369 "{:?} is not an assignment",
375 let terminator = self.body[loc.block].terminator();
376 match &terminator.kind {
377 TerminatorKind::Call { .. } => {
378 let return_ty = self.body.local_decls[local].ty;
379 Q::in_any_value_of_ty(&self.ccx, return_ty)
382 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
387 let span = self.body.local_decls[local].source_info.span;
388 span_bug!(span, "{:?} not promotable, qualif_local shouldn't have been called", local);
392 // FIXME(eddyb) maybe cache this?
393 fn validate_local(&self, local: Local) -> Result<(), Unpromotable> {
394 if let TempState::Defined { location: loc, .. } = self.temps[local] {
395 let block = &self.body[loc.block];
396 let num_stmts = block.statements.len();
398 if loc.statement_index < num_stmts {
399 let statement = &block.statements[loc.statement_index];
400 match &statement.kind {
401 StatementKind::Assign(box (_, rhs)) => self.validate_rvalue(rhs),
404 statement.source_info.span,
405 "{:?} is not an assignment",
411 let terminator = block.terminator();
412 match &terminator.kind {
413 TerminatorKind::Call { func, args, .. } => self.validate_call(func, args),
414 TerminatorKind::Yield { .. } => Err(Unpromotable),
416 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
425 fn validate_place(&self, place: PlaceRef<'tcx>) -> Result<(), Unpromotable> {
426 match place.last_projection() {
427 None => self.validate_local(place.local),
428 Some((place_base, elem)) => {
429 // Validate topmost projection, then recurse.
431 ProjectionElem::Deref => {
432 let mut promotable = false;
433 // We need to make sure this is a `Deref` of a local with no further projections.
434 // Discussion can be found at
435 // https://github.com/rust-lang/rust/pull/74945#discussion_r463063247
436 if let Some(local) = place_base.as_local() {
437 // This is a special treatment for cases like *&STATIC where STATIC is a
438 // global static variable.
439 // This pattern is generated only when global static variables are directly
440 // accessed and is qualified for promotion safely.
441 if let TempState::Defined { location, .. } = self.temps[local] {
442 let def_stmt = self.body[location.block]
444 .get(location.statement_index);
445 if let Some(Statement {
447 StatementKind::Assign(box (
449 Rvalue::Use(Operand::Constant(c)),
454 if let Some(did) = c.check_static_ptr(self.tcx) {
455 // Evaluating a promoted may not read statics except if it got
456 // promoted from a static (this is a CTFE check). So we
457 // can only promote static accesses inside statics.
458 if let Some(hir::ConstContext::Static(..)) = self.const_kind
460 if !self.tcx.is_thread_local_static(did) {
469 return Err(Unpromotable);
472 ProjectionElem::Downcast(..) => {
473 return Err(Unpromotable);
476 ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } => {}
478 ProjectionElem::Index(local) => {
480 let mut promotable = false;
481 // Only accept if we can predict the index and are indexing an array.
482 let val = if let TempState::Defined { location: loc, .. } =
485 let block = &self.body[loc.block];
486 if loc.statement_index < block.statements.len() {
487 let statement = &block.statements[loc.statement_index];
488 match &statement.kind {
489 StatementKind::Assign(box (
491 Rvalue::Use(Operand::Constant(c)),
492 )) => c.literal.try_eval_usize(self.tcx, self.param_env),
501 if let Some(idx) = val {
502 // Determine the type of the thing we are indexing.
503 let ty = place_base.ty(self.body, self.tcx).ty;
505 ty::Array(_, len) => {
506 // It's an array; determine its length.
508 len.try_eval_usize(self.tcx, self.param_env)
510 // If the index is in-bounds, go ahead.
520 return Err(Unpromotable);
523 self.validate_local(local)?;
526 ProjectionElem::Field(..) => {
527 let base_ty = place_base.ty(self.body, self.tcx).ty;
528 if let Some(def) = base_ty.ty_adt_def() {
529 // No promotion of union field accesses.
531 return Err(Unpromotable);
537 self.validate_place(place_base)
542 fn validate_operand(&self, operand: &Operand<'tcx>) -> Result<(), Unpromotable> {
544 Operand::Copy(place) | Operand::Move(place) => self.validate_place(place.as_ref()),
546 // The qualifs for a constant (e.g. `HasMutInterior`) are checked in
547 // `validate_rvalue` upon access.
548 Operand::Constant(c) => {
549 if let Some(def_id) = c.check_static_ptr(self.tcx) {
550 // Only allow statics (not consts) to refer to other statics.
551 // FIXME(eddyb) does this matter at all for promotion?
552 // FIXME(RalfJung) it makes little sense to not promote this in `fn`/`const fn`,
553 // and in `const` this cannot occur anyway. The only concern is that we might
554 // promote even `let x = &STATIC` which would be useless, but this applies to
555 // promotion inside statics as well.
556 let is_static = matches!(self.const_kind, Some(hir::ConstContext::Static(_)));
558 return Err(Unpromotable);
561 let is_thread_local = self.tcx.is_thread_local_static(def_id);
563 return Err(Unpromotable);
572 fn validate_ref(&self, kind: BorrowKind, place: &Place<'tcx>) -> Result<(), Unpromotable> {
574 // Reject these borrow types just to be safe.
575 // FIXME(RalfJung): could we allow them? Should we? No point in it until we have a usecase.
576 BorrowKind::Shallow | BorrowKind::Unique => return Err(Unpromotable),
578 BorrowKind::Shared => {
579 let has_mut_interior = self.qualif_local::<qualifs::HasMutInterior>(place.local);
580 if has_mut_interior {
581 return Err(Unpromotable);
585 BorrowKind::Mut { .. } => {
586 let ty = place.ty(self.body, self.tcx).ty;
588 // In theory, any zero-sized value could be borrowed
589 // mutably without consequences. However, only &mut []
590 // is allowed right now.
591 if let ty::Array(_, len) = ty.kind() {
592 match len.try_eval_usize(self.tcx, self.param_env) {
594 _ => return Err(Unpromotable),
597 return Err(Unpromotable);
605 fn validate_rvalue(&self, rvalue: &Rvalue<'tcx>) -> Result<(), Unpromotable> {
607 Rvalue::Use(operand) | Rvalue::Repeat(operand, _) => {
608 self.validate_operand(operand)?;
611 Rvalue::Discriminant(place) | Rvalue::Len(place) => {
612 self.validate_place(place.as_ref())?
615 Rvalue::ThreadLocalRef(_) => return Err(Unpromotable),
617 Rvalue::Cast(kind, operand, cast_ty) => {
618 if matches!(kind, CastKind::Misc) {
619 let operand_ty = operand.ty(self.body, self.tcx);
620 let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast");
621 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
622 if let (CastTy::Ptr(_) | CastTy::FnPtr, CastTy::Int(_)) = (cast_in, cast_out) {
623 // ptr-to-int casts are not possible in consts and thus not promotable
624 return Err(Unpromotable);
626 // int-to-ptr casts are fine, they just use the integer value at pointer type.
629 self.validate_operand(operand)?;
632 Rvalue::NullaryOp(op, _) => match op {
633 NullOp::Box => return Err(Unpromotable),
637 Rvalue::UnaryOp(op, operand) => {
639 // These operations can never fail.
640 UnOp::Neg | UnOp::Not => {}
643 self.validate_operand(operand)?;
646 Rvalue::BinaryOp(op, box (lhs, rhs)) | Rvalue::CheckedBinaryOp(op, box (lhs, rhs)) => {
648 let lhs_ty = lhs.ty(self.body, self.tcx);
650 if let ty::RawPtr(_) | ty::FnPtr(..) = lhs_ty.kind() {
651 // Raw and fn pointer operations are not allowed inside consts and thus not promotable.
662 return Err(Unpromotable);
666 BinOp::Div | BinOp::Rem => {
667 if !self.explicit && lhs_ty.is_integral() {
668 // Integer division: the RHS must be a non-zero const.
669 let const_val = match rhs {
670 Operand::Constant(c) => {
671 c.literal.try_eval_bits(self.tcx, self.param_env, lhs_ty)
676 Some(x) if x != 0 => {} // okay
677 _ => return Err(Unpromotable), // value not known or 0 -- not okay
681 // The remaining operations can never fail.
699 self.validate_operand(lhs)?;
700 self.validate_operand(rhs)?;
703 Rvalue::AddressOf(_, place) => {
704 // We accept `&raw *`, i.e., raw reborrows -- creating a raw pointer is
705 // no problem, only using it is.
706 if let Some((place_base, ProjectionElem::Deref)) = place.as_ref().last_projection()
708 let base_ty = place_base.ty(self.body, self.tcx).ty;
709 if let ty::Ref(..) = base_ty.kind() {
710 return self.validate_place(place_base);
713 return Err(Unpromotable);
716 Rvalue::Ref(_, kind, place) => {
717 // Special-case reborrows to be more like a copy of the reference.
718 let mut place_simplified = place.as_ref();
719 if let Some((place_base, ProjectionElem::Deref)) =
720 place_simplified.last_projection()
722 let base_ty = place_base.ty(self.body, self.tcx).ty;
723 if let ty::Ref(..) = base_ty.kind() {
724 place_simplified = place_base;
728 self.validate_place(place_simplified)?;
730 // Check that the reference is fine (using the original place!).
731 // (Needs to come after `validate_place` to avoid ICEs.)
732 self.validate_ref(*kind, place)?;
735 Rvalue::Aggregate(_, operands) => {
737 self.validate_operand(o)?;
747 callee: &Operand<'tcx>,
748 args: &[Operand<'tcx>],
749 ) -> Result<(), Unpromotable> {
750 let fn_ty = callee.ty(self.body, self.tcx);
752 // When doing explicit promotion and inside const/static items, we promote all (eligible) function calls.
753 // Everywhere else, we require `#[rustc_promotable]` on the callee.
754 let promote_all_const_fn = self.explicit
757 Some(hir::ConstContext::Static(_) | hir::ConstContext::Const)
759 if !promote_all_const_fn {
760 if let ty::FnDef(def_id, _) = *fn_ty.kind() {
761 // Never promote runtime `const fn` calls of
762 // functions without `#[rustc_promotable]`.
763 if !self.tcx.is_promotable_const_fn(def_id) {
764 return Err(Unpromotable);
769 let is_const_fn = match *fn_ty.kind() {
770 ty::FnDef(def_id, _) => {
771 is_const_fn(self.tcx, def_id)
772 || is_unstable_const_fn(self.tcx, def_id).is_some()
773 || is_lang_panic_fn(self.tcx, def_id)
778 return Err(Unpromotable);
781 self.validate_operand(callee)?;
783 self.validate_operand(arg)?;
790 // FIXME(eddyb) remove the differences for promotability in `static`, `const`, `const fn`.
791 pub fn validate_candidates(
792 ccx: &ConstCx<'_, '_>,
793 temps: &IndexVec<Local, TempState>,
794 candidates: &[Candidate],
795 ) -> Vec<Candidate> {
796 let mut validator = Validator { ccx, temps, explicit: false };
801 .filter(|&candidate| {
802 validator.explicit = candidate.forces_explicit_promotion();
804 // FIXME(eddyb) also emit the errors for shuffle indices
805 // and `#[rustc_args_required_const]` arguments here.
807 let is_promotable = validator.validate_candidate(candidate).is_ok();
809 // If we use explicit validation, we carry the risk of turning a legitimate run-time
810 // operation into a failing compile-time operation. Make sure that does not happen
811 // by asserting that there is no possible run-time behavior here in case promotion
813 if validator.explicit && !is_promotable {
814 ccx.tcx.sess.delay_span_bug(
816 "Explicit promotion requested, but failed to promote",
821 Candidate::Argument { bb, index } | Candidate::InlineAsm { bb, index }
824 let span = ccx.body[bb].terminator().source_info.span;
825 let msg = format!("argument {} is required to be a constant", index + 1);
826 ccx.tcx.sess.span_err(span, &msg);
836 struct Promoter<'a, 'tcx> {
838 source: &'a mut Body<'tcx>,
839 promoted: Body<'tcx>,
840 temps: &'a mut IndexVec<Local, TempState>,
841 extra_statements: &'a mut Vec<(Location, Statement<'tcx>)>,
843 /// If true, all nested temps are also kept in the
844 /// source MIR, not moved to the promoted MIR.
848 impl<'a, 'tcx> Promoter<'a, 'tcx> {
849 fn new_block(&mut self) -> BasicBlock {
850 let span = self.promoted.span;
851 self.promoted.basic_blocks_mut().push(BasicBlockData {
853 terminator: Some(Terminator {
854 source_info: SourceInfo::outermost(span),
855 kind: TerminatorKind::Return,
861 fn assign(&mut self, dest: Local, rvalue: Rvalue<'tcx>, span: Span) {
862 let last = self.promoted.basic_blocks().last().unwrap();
863 let data = &mut self.promoted[last];
864 data.statements.push(Statement {
865 source_info: SourceInfo::outermost(span),
866 kind: StatementKind::Assign(box (Place::from(dest), rvalue)),
870 fn is_temp_kind(&self, local: Local) -> bool {
871 self.source.local_kind(local) == LocalKind::Temp
874 /// Copies the initialization of this temp to the
875 /// promoted MIR, recursing through temps.
876 fn promote_temp(&mut self, temp: Local) -> Local {
877 let old_keep_original = self.keep_original;
878 let loc = match self.temps[temp] {
879 TempState::Defined { location, uses } if uses > 0 => {
881 self.keep_original = true;
886 span_bug!(self.promoted.span, "{:?} not promotable: {:?}", temp, state);
889 if !self.keep_original {
890 self.temps[temp] = TempState::PromotedOut;
893 let num_stmts = self.source[loc.block].statements.len();
894 let new_temp = self.promoted.local_decls.push(LocalDecl::new(
895 self.source.local_decls[temp].ty,
896 self.source.local_decls[temp].source_info.span,
899 debug!("promote({:?} @ {:?}/{:?}, {:?})", temp, loc, num_stmts, self.keep_original);
901 // First, take the Rvalue or Call out of the source MIR,
902 // or duplicate it, depending on keep_original.
903 if loc.statement_index < num_stmts {
904 let (mut rvalue, source_info) = {
905 let statement = &mut self.source[loc.block].statements[loc.statement_index];
906 let rhs = match statement.kind {
907 StatementKind::Assign(box (_, ref mut rhs)) => rhs,
910 statement.source_info.span,
911 "{:?} is not an assignment",
918 if self.keep_original {
921 let unit = Rvalue::Use(Operand::Constant(box Constant {
922 span: statement.source_info.span,
924 literal: ty::Const::zero_sized(self.tcx, self.tcx.types.unit).into(),
926 mem::replace(rhs, unit)
928 statement.source_info,
932 self.visit_rvalue(&mut rvalue, loc);
933 self.assign(new_temp, rvalue, source_info.span);
935 let terminator = if self.keep_original {
936 self.source[loc.block].terminator().clone()
938 let terminator = self.source[loc.block].terminator_mut();
939 let target = match terminator.kind {
940 TerminatorKind::Call { destination: Some((_, target)), .. } => target,
942 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
946 source_info: terminator.source_info,
947 kind: mem::replace(&mut terminator.kind, TerminatorKind::Goto { target }),
951 match terminator.kind {
952 TerminatorKind::Call { mut func, mut args, from_hir_call, fn_span, .. } => {
953 self.visit_operand(&mut func, loc);
954 for arg in &mut args {
955 self.visit_operand(arg, loc);
958 let last = self.promoted.basic_blocks().last().unwrap();
959 let new_target = self.new_block();
961 *self.promoted[last].terminator_mut() = Terminator {
962 kind: TerminatorKind::Call {
966 destination: Some((Place::from(new_temp), new_target)),
970 source_info: SourceInfo::outermost(terminator.source_info.span),
975 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
980 self.keep_original = old_keep_original;
984 fn promote_candidate(
986 candidate: Candidate,
987 next_promoted_id: usize,
988 ) -> Option<Body<'tcx>> {
989 let def = self.source.source.with_opt_param();
991 let promoted = &mut self.promoted;
992 let promoted_id = Promoted::new(next_promoted_id);
994 let mut promoted_operand = |ty, span| {
995 promoted.span = span;
996 promoted.local_decls[RETURN_PLACE] = LocalDecl::new(ty, span);
998 Operand::Constant(Box::new(Constant {
1002 .mk_const(ty::Const {
1004 val: ty::ConstKind::Unevaluated(ty::Unevaluated {
1006 substs: InternalSubsts::for_item(tcx, def.did, |param, _| {
1007 if let ty::GenericParamDefKind::Lifetime = param.kind {
1008 tcx.lifetimes.re_erased.into()
1010 tcx.mk_param_from_def(param)
1013 promoted: Some(promoted_id),
1019 let (blocks, local_decls) = self.source.basic_blocks_and_local_decls_mut();
1021 Candidate::Ref(loc) => {
1022 let statement = &mut blocks[loc.block].statements[loc.statement_index];
1023 match statement.kind {
1024 StatementKind::Assign(box (
1026 Rvalue::Ref(ref mut region, borrow_kind, ref mut place),
1028 // Use the underlying local for this (necessarily interior) borrow.
1029 let ty = local_decls.local_decls()[place.local].ty;
1030 let span = statement.source_info.span;
1032 let ref_ty = tcx.mk_ref(
1033 tcx.lifetimes.re_erased,
1034 ty::TypeAndMut { ty, mutbl: borrow_kind.to_mutbl_lossy() },
1037 *region = tcx.lifetimes.re_erased;
1039 let mut projection = vec![PlaceElem::Deref];
1040 projection.extend(place.projection);
1041 place.projection = tcx.intern_place_elems(&projection);
1043 // Create a temp to hold the promoted reference.
1044 // This is because `*r` requires `r` to be a local,
1045 // otherwise we would use the `promoted` directly.
1046 let mut promoted_ref = LocalDecl::new(ref_ty, span);
1047 promoted_ref.source_info = statement.source_info;
1048 let promoted_ref = local_decls.push(promoted_ref);
1049 assert_eq!(self.temps.push(TempState::Unpromotable), promoted_ref);
1051 let promoted_ref_statement = Statement {
1052 source_info: statement.source_info,
1053 kind: StatementKind::Assign(Box::new((
1054 Place::from(promoted_ref),
1055 Rvalue::Use(promoted_operand(ref_ty, span)),
1058 self.extra_statements.push((loc, promoted_ref_statement));
1061 tcx.lifetimes.re_erased,
1064 local: mem::replace(&mut place.local, promoted_ref),
1065 projection: List::empty(),
1072 Candidate::Argument { bb, index } => {
1073 let terminator = blocks[bb].terminator_mut();
1074 match terminator.kind {
1075 TerminatorKind::Call { ref mut args, .. } => {
1076 let ty = args[index].ty(local_decls, self.tcx);
1077 let span = terminator.source_info.span;
1079 Rvalue::Use(mem::replace(&mut args[index], promoted_operand(ty, span)))
1081 // We expected a `TerminatorKind::Call` for which we'd like to promote an
1082 // argument. `qualify_consts` saw a `TerminatorKind::Call` here, but
1083 // we are seeing a `Goto`. That means that the `promote_temps` method
1084 // already promoted this call away entirely. This case occurs when calling
1085 // a function requiring a constant argument and as that constant value
1086 // providing a value whose computation contains another call to a function
1087 // requiring a constant argument.
1088 TerminatorKind::Goto { .. } => return None,
1092 Candidate::InlineAsm { bb, index } => {
1093 let terminator = blocks[bb].terminator_mut();
1094 match terminator.kind {
1095 TerminatorKind::InlineAsm { ref mut operands, .. } => {
1096 match &mut operands[index] {
1097 InlineAsmOperand::Const { ref mut value } => {
1098 let ty = value.ty(local_decls, self.tcx);
1099 let span = terminator.source_info.span;
1101 Rvalue::Use(mem::replace(value, promoted_operand(ty, span)))
1113 assert_eq!(self.new_block(), START_BLOCK);
1116 Location { block: BasicBlock::new(0), statement_index: usize::MAX },
1119 let span = self.promoted.span;
1120 self.assign(RETURN_PLACE, rvalue, span);
1125 /// Replaces all temporaries with their promoted counterparts.
1126 impl<'a, 'tcx> MutVisitor<'tcx> for Promoter<'a, 'tcx> {
1127 fn tcx(&self) -> TyCtxt<'tcx> {
1131 fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
1132 if self.is_temp_kind(*local) {
1133 *local = self.promote_temp(*local);
1138 pub fn promote_candidates<'tcx>(
1139 body: &mut Body<'tcx>,
1141 mut temps: IndexVec<Local, TempState>,
1142 candidates: Vec<Candidate>,
1143 ) -> IndexVec<Promoted, Body<'tcx>> {
1144 // Visit candidates in reverse, in case they're nested.
1145 debug!("promote_candidates({:?})", candidates);
1147 let mut promotions = IndexVec::new();
1149 let mut extra_statements = vec![];
1150 for candidate in candidates.into_iter().rev() {
1152 Candidate::Ref(Location { block, statement_index }) => {
1153 if let StatementKind::Assign(box (place, _)) =
1154 &body[block].statements[statement_index].kind
1156 if let Some(local) = place.as_local() {
1157 if temps[local] == TempState::PromotedOut {
1158 // Already promoted.
1164 Candidate::Argument { .. } | Candidate::InlineAsm { .. } => {}
1167 // Declare return place local so that `mir::Body::new` doesn't complain.
1168 let initial_locals = iter::once(LocalDecl::new(tcx.types.never, body.span)).collect();
1170 let mut scope = body.source_scopes[candidate.source_info(body).scope].clone();
1171 scope.parent_scope = None;
1173 let promoted = Body::new(
1174 body.source, // `promoted` gets filled in below
1176 IndexVec::from_elem_n(scope, 1),
1182 body.generator_kind(),
1185 let promoter = Promoter {
1190 extra_statements: &mut extra_statements,
1191 keep_original: false,
1194 //FIXME(oli-obk): having a `maybe_push()` method on `IndexVec` might be nice
1195 if let Some(mut promoted) = promoter.promote_candidate(candidate, promotions.len()) {
1196 promoted.source.promoted = Some(promotions.next_index());
1197 promotions.push(promoted);
1201 // Insert each of `extra_statements` before its indicated location, which
1202 // has to be done in reverse location order, to not invalidate the rest.
1203 extra_statements.sort_by_key(|&(loc, _)| cmp::Reverse(loc));
1204 for (loc, statement) in extra_statements {
1205 body[loc.block].statements.insert(loc.statement_index, statement);
1208 // Eliminate assignments to, and drops of promoted temps.
1209 let promoted = |index: Local| temps[index] == TempState::PromotedOut;
1210 for block in body.basic_blocks_mut() {
1211 block.statements.retain(|statement| match &statement.kind {
1212 StatementKind::Assign(box (place, _)) => {
1213 if let Some(index) = place.as_local() {
1219 StatementKind::StorageLive(index) | StatementKind::StorageDead(index) => {
1224 let terminator = block.terminator_mut();
1225 if let TerminatorKind::Drop { place, target, .. } = &terminator.kind {
1226 if let Some(index) = place.as_local() {
1227 if promoted(index) {
1228 terminator.kind = TerminatorKind::Goto { target: *target };
1237 /// This function returns `true` if the function being called in the array
1238 /// repeat expression is a `const` function.
1239 crate fn is_const_fn_in_array_repeat_expression<'tcx>(
1240 ccx: &ConstCx<'_, 'tcx>,
1241 place: &Place<'tcx>,
1244 match place.as_local() {
1245 // rule out cases such as: `let my_var = some_fn(); [my_var; N]`
1246 Some(local) if body.local_decls[local].is_user_variable() => return false,
1247 None => return false,
1251 for block in body.basic_blocks() {
1252 if let Some(Terminator { kind: TerminatorKind::Call { func, destination, .. }, .. }) =
1255 if let Operand::Constant(box Constant { literal, .. }) = func {
1256 if let ty::FnDef(def_id, _) = *literal.ty().kind() {
1257 if let Some((destination_place, _)) = destination {
1258 if destination_place == place {
1259 if is_const_fn(ccx.tcx, def_id) {