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::ast::LitKind;
16 use rustc_hir::def_id::DefId;
17 use rustc_middle::mir::traversal::ReversePostorder;
18 use rustc_middle::mir::visit::{MutVisitor, MutatingUseContext, PlaceContext, Visitor};
19 use rustc_middle::mir::*;
20 use rustc_middle::ty::cast::CastTy;
21 use rustc_middle::ty::subst::InternalSubsts;
22 use rustc_middle::ty::{self, List, TyCtxt, TypeFoldable};
23 use rustc_span::symbol::sym;
24 use rustc_span::{Span, DUMMY_SP};
26 use rustc_index::vec::{Idx, IndexVec};
27 use rustc_target::spec::abi::Abi;
30 use std::{cmp, iter, mem};
32 use crate::const_eval::{is_const_fn, is_unstable_const_fn};
33 use crate::transform::check_consts::{is_lang_panic_fn, qualifs, ConstKind, Item};
34 use crate::transform::{MirPass, MirSource};
36 /// A `MirPass` for promotion.
38 /// Promotion is the extraction of promotable temps into separate MIR bodies. This pass also emits
39 /// errors when promotion of `#[rustc_args_required_const]` arguments fails.
41 /// After this pass is run, `promoted_fragments` will hold the MIR body corresponding to each
42 /// newly created `Constant`.
44 pub struct PromoteTemps<'tcx> {
45 pub promoted_fragments: Cell<IndexVec<Promoted, Body<'tcx>>>,
48 impl<'tcx> MirPass<'tcx> for PromoteTemps<'tcx> {
49 fn run_pass(&self, tcx: TyCtxt<'tcx>, src: MirSource<'tcx>, body: &mut Body<'tcx>) {
50 // There's not really any point in promoting errorful MIR.
52 // This does not include MIR that failed const-checking, which we still try to promote.
53 if body.return_ty().references_error() {
54 tcx.sess.delay_span_bug(body.span, "PromoteTemps: MIR had errors");
58 if src.promoted.is_some() {
62 let def_id = src.def_id();
64 let mut rpo = traversal::reverse_postorder(body);
65 let (temps, all_candidates) = collect_temps_and_candidates(tcx, body, &mut rpo);
67 let promotable_candidates = validate_candidates(tcx, body, def_id, &temps, &all_candidates);
69 let promoted = promote_candidates(def_id, 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 if let TempState::Defined { .. } = *self { true } else { false }
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.
105 /// Promotion of the `x` in `[x; 32]`.
108 /// Currently applied to function calls where the callee has the unstable
109 /// `#[rustc_args_required_const]` attribute as well as the SIMD shuffle
110 /// intrinsic. The intrinsic requires the arguments are indeed constant and
111 /// the attribute currently provides the semantic requirement that arguments
112 /// must be constant.
113 Argument { 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(_) | Candidate::Repeat(_) => false,
121 Candidate::Argument { .. } => true,
126 fn args_required_const(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Vec<usize>> {
127 let attrs = tcx.get_attrs(def_id);
128 let attr = attrs.iter().find(|a| a.check_name(sym::rustc_args_required_const))?;
129 let mut ret = vec![];
130 for meta in attr.meta_item_list()? {
131 match meta.literal()?.kind {
132 LitKind::Int(a, _) => {
133 ret.push(a as usize);
141 struct Collector<'a, 'tcx> {
143 body: &'a Body<'tcx>,
144 temps: IndexVec<Local, TempState>,
145 candidates: Vec<Candidate>,
149 impl<'tcx> Visitor<'tcx> for Collector<'_, 'tcx> {
150 fn visit_local(&mut self, &index: &Local, context: PlaceContext, location: Location) {
151 debug!("visit_local: index={:?} context={:?} location={:?}", index, context, location);
152 // We're only interested in temporaries and the return place
153 match self.body.local_kind(index) {
154 LocalKind::Temp | LocalKind::ReturnPointer => {}
155 LocalKind::Arg | LocalKind::Var => return,
158 // Ignore drops, if the temp gets promoted,
159 // then it's constant and thus drop is noop.
160 // Non-uses are also irrelevant.
161 if context.is_drop() || !context.is_use() {
163 "visit_local: context.is_drop={:?} context.is_use={:?}",
170 let temp = &mut self.temps[index];
171 debug!("visit_local: temp={:?}", temp);
172 if *temp == TempState::Undefined {
174 PlaceContext::MutatingUse(MutatingUseContext::Store)
175 | PlaceContext::MutatingUse(MutatingUseContext::Call) => {
176 *temp = TempState::Defined { location, uses: 0 };
179 _ => { /* mark as unpromotable below */ }
181 } else if let TempState::Defined { ref mut uses, .. } = *temp {
182 // We always allow borrows, even mutable ones, as we need
183 // to promote mutable borrows of some ZSTs e.g., `&mut []`.
184 let allowed_use = match context {
185 PlaceContext::MutatingUse(MutatingUseContext::Borrow)
186 | PlaceContext::NonMutatingUse(_) => true,
187 PlaceContext::MutatingUse(_) | PlaceContext::NonUse(_) => false,
189 debug!("visit_local: allowed_use={:?}", allowed_use);
194 /* mark as unpromotable below */
196 *temp = TempState::Unpromotable;
199 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
200 self.super_rvalue(rvalue, location);
204 self.candidates.push(Candidate::Ref(location));
206 Rvalue::Repeat(..) if self.tcx.features().const_in_array_repeat_expressions => {
207 // FIXME(#49147) only promote the element when it isn't `Copy`
208 // (so that code that can copy it at runtime is unaffected).
209 self.candidates.push(Candidate::Repeat(location));
215 fn visit_terminator_kind(&mut self, kind: &TerminatorKind<'tcx>, location: Location) {
216 self.super_terminator_kind(kind, location);
218 if let TerminatorKind::Call { ref func, .. } = *kind {
219 if let ty::FnDef(def_id, _) = func.ty(self.body, self.tcx).kind {
220 let fn_sig = self.tcx.fn_sig(def_id);
221 if let Abi::RustIntrinsic | Abi::PlatformIntrinsic = fn_sig.abi() {
222 let name = self.tcx.item_name(def_id);
223 // FIXME(eddyb) use `#[rustc_args_required_const(2)]` for shuffles.
224 if name.as_str().starts_with("simd_shuffle") {
225 self.candidates.push(Candidate::Argument { bb: location.block, index: 2 });
227 return; // Don't double count `simd_shuffle` candidates
231 if let Some(constant_args) = args_required_const(self.tcx, def_id) {
232 for index in constant_args {
233 self.candidates.push(Candidate::Argument { bb: location.block, index });
240 fn visit_source_info(&mut self, source_info: &SourceInfo) {
241 self.span = source_info.span;
245 pub fn collect_temps_and_candidates(
248 rpo: &mut ReversePostorder<'_, 'tcx>,
249 ) -> (IndexVec<Local, TempState>, Vec<Candidate>) {
250 let mut collector = Collector {
253 temps: IndexVec::from_elem(TempState::Undefined, &body.local_decls),
257 for (bb, data) in rpo {
258 collector.visit_basic_block_data(bb, data);
260 (collector.temps, collector.candidates)
263 /// Checks whether locals that appear in a promotion context (`Candidate`) are actually promotable.
265 /// This wraps an `Item`, and has access to all fields of that `Item` via `Deref` coercion.
266 struct Validator<'a, 'tcx> {
267 item: Item<'a, 'tcx>,
268 temps: &'a IndexVec<Local, TempState>,
270 /// Explicit promotion happens e.g. for constant arguments declared via
271 /// `rustc_args_required_const`.
272 /// Implicit promotion has almost the same rules, except that disallows `const fn`
273 /// except for those marked `#[rustc_promotable]`. This is to avoid changing
274 /// a legitimate run-time operation into a failing compile-time operation
275 /// e.g. due to addresses being compared inside the function.
279 impl std::ops::Deref for Validator<'a, 'tcx> {
280 type Target = Item<'a, 'tcx>;
282 fn deref(&self) -> &Self::Target {
289 impl<'tcx> Validator<'_, 'tcx> {
290 fn validate_candidate(&self, candidate: Candidate) -> Result<(), Unpromotable> {
292 Candidate::Ref(loc) => {
293 assert!(!self.explicit);
295 let statement = &self.body[loc.block].statements[loc.statement_index];
296 match &statement.kind {
297 StatementKind::Assign(box (_, Rvalue::Ref(_, kind, place))) => {
299 BorrowKind::Shared | BorrowKind::Mut { .. } => {}
301 // FIXME(eddyb) these aren't promoted here but *could*
302 // be promoted as part of a larger value because
303 // `validate_rvalue` doesn't check them, need to
304 // figure out what is the intended behavior.
305 BorrowKind::Shallow | BorrowKind::Unique => return Err(Unpromotable),
308 // We can only promote interior borrows of promotable temps (non-temps
309 // don't get promoted anyway).
310 self.validate_local(place.local)?;
312 if place.projection.contains(&ProjectionElem::Deref) {
313 return Err(Unpromotable);
316 let mut has_mut_interior =
317 self.qualif_local::<qualifs::HasMutInterior>(place.local);
318 // HACK(eddyb) this should compute the same thing as
319 // `<HasMutInterior as Qualif>::in_projection` from
320 // `check_consts::qualifs` but without recursion.
321 if has_mut_interior {
322 // This allows borrowing fields which don't have
323 // `HasMutInterior`, from a type that does, e.g.:
324 // `let _: &'static _ = &(Cell::new(1), 2).1;`
325 let mut place_projection = &place.projection[..];
326 // FIXME(eddyb) use a forward loop instead of a reverse one.
327 while let [proj_base @ .., elem] = place_projection {
328 // FIXME(eddyb) this is probably excessive, with
329 // the exception of `union` member accesses.
331 Place::ty_from(place.local, proj_base, self.body, self.tcx)
332 .projection_ty(self.tcx, elem)
334 if ty.is_freeze(self.tcx, self.param_env, DUMMY_SP) {
335 has_mut_interior = false;
339 place_projection = proj_base;
343 // FIXME(eddyb) this duplicates part of `validate_rvalue`.
344 if has_mut_interior {
345 return Err(Unpromotable);
347 if self.qualif_local::<qualifs::NeedsDrop>(place.local) {
348 return Err(Unpromotable);
351 if let BorrowKind::Mut { .. } = kind {
352 let ty = place.ty(self.body, self.tcx).ty;
354 // In theory, any zero-sized value could be borrowed
355 // mutably without consequences. However, only &mut []
356 // is allowed right now, and only in functions.
357 if self.const_kind == Some(ConstKind::StaticMut) {
358 // Inside a `static mut`, &mut [...] is also allowed.
360 ty::Array(..) | ty::Slice(_) => {}
361 _ => return Err(Unpromotable),
363 } else if let ty::Array(_, len) = ty.kind {
364 // FIXME(eddyb) the `self.is_non_const_fn` condition
365 // seems unnecessary, given that this is merely a ZST.
366 match len.try_eval_usize(self.tcx, self.param_env) {
367 Some(0) if self.const_kind.is_none() => {}
368 _ => return Err(Unpromotable),
371 return Err(Unpromotable);
380 Candidate::Repeat(loc) => {
381 assert!(!self.explicit);
383 let statement = &self.body[loc.block].statements[loc.statement_index];
384 match &statement.kind {
385 StatementKind::Assign(box (_, Rvalue::Repeat(ref operand, _))) => {
386 if !self.tcx.features().const_in_array_repeat_expressions {
387 return Err(Unpromotable);
390 self.validate_operand(operand)
395 Candidate::Argument { bb, index } => {
396 assert!(self.explicit);
398 let terminator = self.body[bb].terminator();
399 match &terminator.kind {
400 TerminatorKind::Call { args, .. } => self.validate_operand(&args[index]),
407 // FIXME(eddyb) maybe cache this?
408 fn qualif_local<Q: qualifs::Qualif>(&self, local: Local) -> bool {
409 if let TempState::Defined { location: loc, .. } = self.temps[local] {
410 let num_stmts = self.body[loc.block].statements.len();
412 if loc.statement_index < num_stmts {
413 let statement = &self.body[loc.block].statements[loc.statement_index];
414 match &statement.kind {
415 StatementKind::Assign(box (_, rhs)) => qualifs::in_rvalue::<Q, _>(
417 &mut |l| self.qualif_local::<Q>(l),
422 statement.source_info.span,
423 "{:?} is not an assignment",
429 let terminator = self.body[loc.block].terminator();
430 match &terminator.kind {
431 TerminatorKind::Call { .. } => {
432 let return_ty = self.body.local_decls[local].ty;
433 Q::in_any_value_of_ty(&self.item, return_ty)
436 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
441 let span = self.body.local_decls[local].source_info.span;
442 span_bug!(span, "{:?} not promotable, qualif_local shouldn't have been called", local);
446 // FIXME(eddyb) maybe cache this?
447 fn validate_local(&self, local: Local) -> Result<(), Unpromotable> {
448 if let TempState::Defined { location: loc, .. } = self.temps[local] {
449 let num_stmts = self.body[loc.block].statements.len();
451 if loc.statement_index < num_stmts {
452 let statement = &self.body[loc.block].statements[loc.statement_index];
453 match &statement.kind {
454 StatementKind::Assign(box (_, rhs)) => self.validate_rvalue(rhs),
457 statement.source_info.span,
458 "{:?} is not an assignment",
464 let terminator = self.body[loc.block].terminator();
465 match &terminator.kind {
466 TerminatorKind::Call { func, args, .. } => self.validate_call(func, args),
467 TerminatorKind::Yield { .. } => Err(Unpromotable),
469 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
478 fn validate_place(&self, place: PlaceRef<'tcx>) -> Result<(), Unpromotable> {
480 PlaceRef { local, projection: [] } => self.validate_local(local),
481 PlaceRef { local: _, projection: [proj_base @ .., elem] } => {
483 ProjectionElem::Deref | ProjectionElem::Downcast(..) => {
484 return Err(Unpromotable);
487 ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } => {}
489 ProjectionElem::Index(local) => {
490 self.validate_local(local)?;
493 ProjectionElem::Field(..) => {
494 if self.const_kind.is_none() {
496 Place::ty_from(place.local, proj_base, self.body, self.tcx).ty;
497 if let Some(def) = base_ty.ty_adt_def() {
498 // No promotion of union field accesses.
500 return Err(Unpromotable);
507 self.validate_place(PlaceRef { local: place.local, projection: proj_base })
512 fn validate_operand(&self, operand: &Operand<'tcx>) -> Result<(), Unpromotable> {
514 Operand::Copy(place) | Operand::Move(place) => self.validate_place(place.as_ref()),
516 // The qualifs for a constant (e.g. `HasMutInterior`) are checked in
517 // `validate_rvalue` upon access.
518 Operand::Constant(c) => {
519 if let Some(def_id) = c.check_static_ptr(self.tcx) {
520 // Only allow statics (not consts) to refer to other statics.
521 // FIXME(eddyb) does this matter at all for promotion?
522 let is_static = self.const_kind.map_or(false, |k| k.is_static());
524 return Err(Unpromotable);
527 let is_thread_local = self.tcx.has_attr(def_id, sym::thread_local);
529 return Err(Unpromotable);
538 fn validate_rvalue(&self, rvalue: &Rvalue<'tcx>) -> Result<(), Unpromotable> {
540 Rvalue::Cast(CastKind::Misc, ref operand, cast_ty) if self.const_kind.is_none() => {
541 let operand_ty = operand.ty(self.body, self.tcx);
542 let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast");
543 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
544 match (cast_in, cast_out) {
545 (CastTy::Ptr(_) | CastTy::FnPtr, CastTy::Int(_)) => {
546 // in normal functions, mark such casts as not promotable
547 return Err(Unpromotable);
553 Rvalue::BinaryOp(op, ref lhs, _) if self.const_kind.is_none() => {
554 if let ty::RawPtr(_) | ty::FnPtr(..) = lhs.ty(self.body, self.tcx).kind {
562 || op == BinOp::Offset
565 // raw pointer operations are not allowed inside promoteds
566 return Err(Unpromotable);
570 Rvalue::NullaryOp(NullOp::Box, _) => return Err(Unpromotable),
576 Rvalue::NullaryOp(..) => Ok(()),
578 Rvalue::Discriminant(place) | Rvalue::Len(place) => self.validate_place(place.as_ref()),
581 | Rvalue::Repeat(operand, _)
582 | Rvalue::UnaryOp(_, operand)
583 | Rvalue::Cast(_, operand, _) => self.validate_operand(operand),
585 Rvalue::BinaryOp(_, lhs, rhs) | Rvalue::CheckedBinaryOp(_, lhs, rhs) => {
586 self.validate_operand(lhs)?;
587 self.validate_operand(rhs)
590 Rvalue::AddressOf(_, place) => {
591 // Raw reborrows can come from reference to pointer coercions,
593 if let [proj_base @ .., ProjectionElem::Deref] = place.projection.as_ref() {
594 let base_ty = Place::ty_from(place.local, proj_base, self.body, self.tcx).ty;
595 if let ty::Ref(..) = base_ty.kind {
596 return self.validate_place(PlaceRef {
598 projection: proj_base,
605 Rvalue::Ref(_, kind, place) => {
606 if let BorrowKind::Mut { .. } = kind {
607 let ty = place.ty(self.body, self.tcx).ty;
609 // In theory, any zero-sized value could be borrowed
610 // mutably without consequences. However, only &mut []
611 // is allowed right now, and only in functions.
612 if self.const_kind == Some(ConstKind::StaticMut) {
613 // Inside a `static mut`, &mut [...] is also allowed.
615 ty::Array(..) | ty::Slice(_) => {}
616 _ => return Err(Unpromotable),
618 } else if let ty::Array(_, len) = ty.kind {
619 // FIXME(eddyb): We only return `Unpromotable` for `&mut []` inside a
620 // const context which seems unnecessary given that this is merely a ZST.
621 match len.try_eval_usize(self.tcx, self.param_env) {
622 Some(0) if self.const_kind.is_none() => {}
623 _ => return Err(Unpromotable),
626 return Err(Unpromotable);
630 // Special-case reborrows to be more like a copy of the reference.
631 let mut place = place.as_ref();
632 if let [proj_base @ .., ProjectionElem::Deref] = &place.projection {
633 let base_ty = Place::ty_from(place.local, proj_base, self.body, self.tcx).ty;
634 if let ty::Ref(..) = base_ty.kind {
635 place = PlaceRef { local: place.local, projection: proj_base };
639 self.validate_place(place)?;
641 // HACK(eddyb) this should compute the same thing as
642 // `<HasMutInterior as Qualif>::in_projection` from
643 // `check_consts::qualifs` but without recursion.
644 let mut has_mut_interior =
645 self.qualif_local::<qualifs::HasMutInterior>(place.local);
646 if has_mut_interior {
647 let mut place_projection = place.projection;
648 // FIXME(eddyb) use a forward loop instead of a reverse one.
649 while let [proj_base @ .., elem] = place_projection {
650 // FIXME(eddyb) this is probably excessive, with
651 // the exception of `union` member accesses.
652 let ty = Place::ty_from(place.local, proj_base, self.body, self.tcx)
653 .projection_ty(self.tcx, elem)
655 if ty.is_freeze(self.tcx, self.param_env, DUMMY_SP) {
656 has_mut_interior = false;
660 place_projection = proj_base;
663 if has_mut_interior {
664 return Err(Unpromotable);
670 Rvalue::Aggregate(_, ref operands) => {
672 self.validate_operand(o)?;
682 callee: &Operand<'tcx>,
683 args: &[Operand<'tcx>],
684 ) -> Result<(), Unpromotable> {
685 let fn_ty = callee.ty(self.body, self.tcx);
687 if !self.explicit && self.const_kind.is_none() {
688 if let ty::FnDef(def_id, _) = fn_ty.kind {
689 // Never promote runtime `const fn` calls of
690 // functions without `#[rustc_promotable]`.
691 if !self.tcx.is_promotable_const_fn(def_id) {
692 return Err(Unpromotable);
697 let is_const_fn = match fn_ty.kind {
698 ty::FnDef(def_id, _) => {
699 is_const_fn(self.tcx, def_id)
700 || is_unstable_const_fn(self.tcx, def_id).is_some()
701 || is_lang_panic_fn(self.tcx, self.def_id)
706 return Err(Unpromotable);
709 self.validate_operand(callee)?;
711 self.validate_operand(arg)?;
718 // FIXME(eddyb) remove the differences for promotability in `static`, `const`, `const fn`.
719 pub fn validate_candidates(
723 temps: &IndexVec<Local, TempState>,
724 candidates: &[Candidate],
725 ) -> Vec<Candidate> {
726 let mut validator = Validator { item: Item::new(tcx, def_id, body), temps, explicit: false };
731 .filter(|&candidate| {
732 validator.explicit = candidate.forces_explicit_promotion();
734 // FIXME(eddyb) also emit the errors for shuffle indices
735 // and `#[rustc_args_required_const]` arguments here.
737 let is_promotable = validator.validate_candidate(candidate).is_ok();
739 Candidate::Argument { bb, index } if !is_promotable => {
740 let span = body[bb].terminator().source_info.span;
741 let msg = format!("argument {} is required to be a constant", index + 1);
742 tcx.sess.span_err(span, &msg);
752 struct Promoter<'a, 'tcx> {
754 source: &'a mut Body<'tcx>,
755 promoted: Body<'tcx>,
756 temps: &'a mut IndexVec<Local, TempState>,
757 extra_statements: &'a mut Vec<(Location, Statement<'tcx>)>,
759 /// If true, all nested temps are also kept in the
760 /// source MIR, not moved to the promoted MIR.
764 impl<'a, 'tcx> Promoter<'a, 'tcx> {
765 fn new_block(&mut self) -> BasicBlock {
766 let span = self.promoted.span;
767 self.promoted.basic_blocks_mut().push(BasicBlockData {
769 terminator: Some(Terminator {
770 source_info: SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE },
771 kind: TerminatorKind::Return,
777 fn assign(&mut self, dest: Local, rvalue: Rvalue<'tcx>, span: Span) {
778 let last = self.promoted.basic_blocks().last().unwrap();
779 let data = &mut self.promoted[last];
780 data.statements.push(Statement {
781 source_info: SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE },
782 kind: StatementKind::Assign(box (Place::from(dest), rvalue)),
786 fn is_temp_kind(&self, local: Local) -> bool {
787 self.source.local_kind(local) == LocalKind::Temp
790 /// Copies the initialization of this temp to the
791 /// promoted MIR, recursing through temps.
792 fn promote_temp(&mut self, temp: Local) -> Local {
793 let old_keep_original = self.keep_original;
794 let loc = match self.temps[temp] {
795 TempState::Defined { location, uses } if uses > 0 => {
797 self.keep_original = true;
802 span_bug!(self.promoted.span, "{:?} not promotable: {:?}", temp, state);
805 if !self.keep_original {
806 self.temps[temp] = TempState::PromotedOut;
809 let num_stmts = self.source[loc.block].statements.len();
810 let new_temp = self.promoted.local_decls.push(LocalDecl::new_temp(
811 self.source.local_decls[temp].ty,
812 self.source.local_decls[temp].source_info.span,
815 debug!("promote({:?} @ {:?}/{:?}, {:?})", temp, loc, num_stmts, self.keep_original);
817 // First, take the Rvalue or Call out of the source MIR,
818 // or duplicate it, depending on keep_original.
819 if loc.statement_index < num_stmts {
820 let (mut rvalue, source_info) = {
821 let statement = &mut self.source[loc.block].statements[loc.statement_index];
822 let rhs = match statement.kind {
823 StatementKind::Assign(box (_, ref mut rhs)) => rhs,
826 statement.source_info.span,
827 "{:?} is not an assignment",
834 if self.keep_original {
837 let unit = Rvalue::Use(Operand::Constant(box Constant {
838 span: statement.source_info.span,
840 literal: ty::Const::zero_sized(self.tcx, self.tcx.types.unit),
842 mem::replace(rhs, unit)
844 statement.source_info,
848 self.visit_rvalue(&mut rvalue, loc);
849 self.assign(new_temp, rvalue, source_info.span);
851 let terminator = if self.keep_original {
852 self.source[loc.block].terminator().clone()
854 let terminator = self.source[loc.block].terminator_mut();
855 let target = match terminator.kind {
856 TerminatorKind::Call { destination: Some((_, target)), .. } => target,
858 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
862 source_info: terminator.source_info,
863 kind: mem::replace(&mut terminator.kind, TerminatorKind::Goto { target }),
867 match terminator.kind {
868 TerminatorKind::Call { mut func, mut args, from_hir_call, .. } => {
869 self.visit_operand(&mut func, loc);
870 for arg in &mut args {
871 self.visit_operand(arg, loc);
874 let last = self.promoted.basic_blocks().last().unwrap();
875 let new_target = self.new_block();
877 *self.promoted[last].terminator_mut() = Terminator {
878 kind: TerminatorKind::Call {
882 destination: Some((Place::from(new_temp), new_target)),
889 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
894 self.keep_original = old_keep_original;
898 fn promote_candidate(
901 candidate: Candidate,
902 next_promoted_id: usize,
903 ) -> Option<Body<'tcx>> {
905 let promoted = &mut self.promoted;
906 let promoted_id = Promoted::new(next_promoted_id);
908 let mut promoted_operand = |ty, span| {
909 promoted.span = span;
910 promoted.local_decls[RETURN_PLACE] = LocalDecl::new_return_place(ty, span);
912 Operand::Constant(Box::new(Constant {
915 literal: tcx.mk_const(ty::Const {
917 val: ty::ConstKind::Unevaluated(
919 InternalSubsts::for_item(tcx, def_id, |param, _| {
920 if let ty::GenericParamDefKind::Lifetime = param.kind {
921 tcx.lifetimes.re_erased.into()
923 tcx.mk_param_from_def(param)
931 let (blocks, local_decls) = self.source.basic_blocks_and_local_decls_mut();
933 Candidate::Ref(loc) => {
934 let statement = &mut blocks[loc.block].statements[loc.statement_index];
935 match statement.kind {
936 StatementKind::Assign(box (
938 Rvalue::Ref(ref mut region, borrow_kind, ref mut place),
940 // Use the underlying local for this (necessarily interior) borrow.
941 let ty = local_decls.local_decls()[place.local].ty;
942 let span = statement.source_info.span;
944 let ref_ty = tcx.mk_ref(
945 tcx.lifetimes.re_erased,
946 ty::TypeAndMut { ty, mutbl: borrow_kind.to_mutbl_lossy() },
949 *region = tcx.lifetimes.re_erased;
951 let mut projection = vec![PlaceElem::Deref];
952 projection.extend(place.projection);
953 place.projection = tcx.intern_place_elems(&projection);
955 // Create a temp to hold the promoted reference.
956 // This is because `*r` requires `r` to be a local,
957 // otherwise we would use the `promoted` directly.
958 let mut promoted_ref = LocalDecl::new_temp(ref_ty, span);
959 promoted_ref.source_info = statement.source_info;
960 let promoted_ref = local_decls.push(promoted_ref);
961 assert_eq!(self.temps.push(TempState::Unpromotable), promoted_ref);
963 let promoted_ref_statement = Statement {
964 source_info: statement.source_info,
965 kind: StatementKind::Assign(Box::new((
966 Place::from(promoted_ref),
967 Rvalue::Use(promoted_operand(ref_ty, span)),
970 self.extra_statements.push((loc, promoted_ref_statement));
973 tcx.lifetimes.re_erased,
976 local: mem::replace(&mut place.local, promoted_ref),
977 projection: List::empty(),
984 Candidate::Repeat(loc) => {
985 let statement = &mut blocks[loc.block].statements[loc.statement_index];
986 match statement.kind {
987 StatementKind::Assign(box (_, Rvalue::Repeat(ref mut operand, _))) => {
988 let ty = operand.ty(local_decls, self.tcx);
989 let span = statement.source_info.span;
991 Rvalue::Use(mem::replace(operand, promoted_operand(ty, span)))
996 Candidate::Argument { bb, index } => {
997 let terminator = blocks[bb].terminator_mut();
998 match terminator.kind {
999 TerminatorKind::Call { ref mut args, .. } => {
1000 let ty = args[index].ty(local_decls, self.tcx);
1001 let span = terminator.source_info.span;
1003 Rvalue::Use(mem::replace(&mut args[index], promoted_operand(ty, span)))
1005 // We expected a `TerminatorKind::Call` for which we'd like to promote an
1006 // argument. `qualify_consts` saw a `TerminatorKind::Call` here, but
1007 // we are seeing a `Goto`. That means that the `promote_temps` method
1008 // already promoted this call away entirely. This case occurs when calling
1009 // a function requiring a constant argument and as that constant value
1010 // providing a value whose computation contains another call to a function
1011 // requiring a constant argument.
1012 TerminatorKind::Goto { .. } => return None,
1019 assert_eq!(self.new_block(), START_BLOCK);
1022 Location { block: BasicBlock::new(0), statement_index: usize::MAX },
1025 let span = self.promoted.span;
1026 self.assign(RETURN_PLACE, rvalue, span);
1031 /// Replaces all temporaries with their promoted counterparts.
1032 impl<'a, 'tcx> MutVisitor<'tcx> for Promoter<'a, 'tcx> {
1033 fn tcx(&self) -> TyCtxt<'tcx> {
1037 fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
1038 if self.is_temp_kind(*local) {
1039 *local = self.promote_temp(*local);
1044 pub fn promote_candidates<'tcx>(
1046 body: &mut Body<'tcx>,
1048 mut temps: IndexVec<Local, TempState>,
1049 candidates: Vec<Candidate>,
1050 ) -> IndexVec<Promoted, Body<'tcx>> {
1051 // Visit candidates in reverse, in case they're nested.
1052 debug!("promote_candidates({:?})", candidates);
1054 let mut promotions = IndexVec::new();
1056 let mut extra_statements = vec![];
1057 for candidate in candidates.into_iter().rev() {
1059 Candidate::Repeat(Location { block, statement_index })
1060 | Candidate::Ref(Location { block, statement_index }) => {
1061 if let StatementKind::Assign(box (place, _)) =
1062 &body[block].statements[statement_index].kind
1064 if let Some(local) = place.as_local() {
1065 if temps[local] == TempState::PromotedOut {
1066 // Already promoted.
1072 Candidate::Argument { .. } => {}
1075 // Declare return place local so that `mir::Body::new` doesn't complain.
1076 let initial_locals =
1077 iter::once(LocalDecl::new_return_place(tcx.types.never, body.span)).collect();
1079 let mut promoted = Body::new(
1081 // FIXME: maybe try to filter this to avoid blowing up
1083 body.source_scopes.clone(),
1090 body.generator_kind,
1092 promoted.ignore_interior_mut_in_const_validation = true;
1094 let promoter = Promoter {
1099 extra_statements: &mut extra_statements,
1100 keep_original: false,
1103 //FIXME(oli-obk): having a `maybe_push()` method on `IndexVec` might be nice
1104 if let Some(promoted) = promoter.promote_candidate(def_id, candidate, promotions.len()) {
1105 promotions.push(promoted);
1109 // Insert each of `extra_statements` before its indicated location, which
1110 // has to be done in reverse location order, to not invalidate the rest.
1111 extra_statements.sort_by_key(|&(loc, _)| cmp::Reverse(loc));
1112 for (loc, statement) in extra_statements {
1113 body[loc.block].statements.insert(loc.statement_index, statement);
1116 // Eliminate assignments to, and drops of promoted temps.
1117 let promoted = |index: Local| temps[index] == TempState::PromotedOut;
1118 for block in body.basic_blocks_mut() {
1119 block.statements.retain(|statement| match &statement.kind {
1120 StatementKind::Assign(box (place, _)) => {
1121 if let Some(index) = place.as_local() {
1127 StatementKind::StorageLive(index) | StatementKind::StorageDead(index) => {
1132 let terminator = block.terminator_mut();
1133 if let TerminatorKind::Drop { location: place, target, .. } = &terminator.kind {
1134 if let Some(index) = place.as_local() {
1135 if promoted(index) {
1136 terminator.kind = TerminatorKind::Goto { target: *target };
1145 /// This function returns `true` if the `const_in_array_repeat_expressions` feature attribute should
1146 /// be suggested. This function is probably quite expensive, it shouldn't be run in the happy path.
1147 /// Feature attribute should be suggested if `operand` can be promoted and the feature is not
1149 crate fn should_suggest_const_in_array_repeat_expressions_attribute<'tcx>(
1153 operand: &Operand<'tcx>,
1155 let mut rpo = traversal::reverse_postorder(&body);
1156 let (temps, _) = collect_temps_and_candidates(tcx, &body, &mut rpo);
1158 Validator { item: Item::new(tcx, mir_def_id, body), temps: &temps, explicit: false };
1160 let should_promote = validator.validate_operand(operand).is_ok();
1161 let feature_flag = tcx.features().const_in_array_repeat_expressions;
1163 "should_suggest_const_in_array_repeat_expressions_flag: mir_def_id={:?} \
1164 should_promote={:?} feature_flag={:?}",
1165 mir_def_id, should_promote, feature_flag
1167 should_promote && !feature_flag