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::mir::traversal::ReversePostorder;
16 use rustc::mir::visit::{MutVisitor, MutatingUseContext, PlaceContext, Visitor};
18 use rustc::ty::cast::CastTy;
19 use rustc::ty::subst::InternalSubsts;
20 use rustc::ty::{self, List, TyCtxt, TypeFoldable};
21 use rustc_hir::def_id::DefId;
22 use rustc_span::symbol::sym;
23 use rustc_span::{Span, DUMMY_SP};
24 use syntax::ast::LitKind;
26 use rustc_index::vec::{Idx, IndexVec};
27 use rustc_target::spec::abi::Abi;
30 use std::{cmp, iter, mem, usize};
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, BodyAndCache<'tcx>>>,
48 impl<'tcx> MirPass<'tcx> for PromoteTemps<'tcx> {
49 fn run_pass(&self, tcx: TyCtxt<'tcx>, src: MirSource<'tcx>, body: &mut BodyAndCache<'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 =
68 validate_candidates(tcx, read_only!(body), def_id, &temps, &all_candidates);
70 let promoted = promote_candidates(def_id, body, tcx, temps, promotable_candidates);
71 self.promoted_fragments.set(promoted);
75 /// State of a temporary during collection and promotion.
76 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
78 /// No references to this temp.
80 /// One direct assignment and any number of direct uses.
81 /// A borrow of this temp is promotable if the assigned
82 /// value is qualified as constant.
83 Defined { location: Location, uses: usize },
84 /// Any other combination of assignments/uses.
86 /// This temp was part of an rvalue which got extracted
87 /// during promotion and needs cleanup.
92 pub fn is_promotable(&self) -> bool {
93 debug!("is_promotable: self={:?}", self);
94 if let TempState::Defined { .. } = *self { true } else { false }
98 /// A "root candidate" for promotion, which will become the
99 /// returned value in a promoted MIR, unless it's a subset
100 /// of a larger candidate.
101 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
103 /// Borrow of a constant temporary.
106 /// Promotion of the `x` in `[x; 32]`.
109 /// Currently applied to function calls where the callee has the unstable
110 /// `#[rustc_args_required_const]` attribute as well as the SIMD shuffle
111 /// intrinsic. The intrinsic requires the arguments are indeed constant and
112 /// the attribute currently provides the semantic requirement that arguments
113 /// must be constant.
114 Argument { bb: BasicBlock, index: usize },
118 /// Returns `true` if we should use the "explicit" rules for promotability for this `Candidate`.
119 fn forces_explicit_promotion(&self) -> bool {
121 Candidate::Ref(_) | Candidate::Repeat(_) => false,
122 Candidate::Argument { .. } => true,
127 fn args_required_const(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Vec<usize>> {
128 let attrs = tcx.get_attrs(def_id);
129 let attr = attrs.iter().find(|a| a.check_name(sym::rustc_args_required_const))?;
130 let mut ret = vec![];
131 for meta in attr.meta_item_list()? {
132 match meta.literal()?.kind {
133 LitKind::Int(a, _) => {
134 ret.push(a as usize);
142 struct Collector<'a, 'tcx> {
144 body: &'a Body<'tcx>,
145 temps: IndexVec<Local, TempState>,
146 candidates: Vec<Candidate>,
150 impl<'tcx> Visitor<'tcx> for Collector<'_, 'tcx> {
151 fn visit_local(&mut self, &index: &Local, context: PlaceContext, location: Location) {
152 debug!("visit_local: index={:?} context={:?} location={:?}", index, context, location);
153 // We're only interested in temporaries and the return place
154 match self.body.local_kind(index) {
155 LocalKind::Temp | LocalKind::ReturnPointer => {}
156 LocalKind::Arg | LocalKind::Var => return,
159 // Ignore drops, if the temp gets promoted,
160 // then it's constant and thus drop is noop.
161 // Non-uses are also irrelevant.
162 if context.is_drop() || !context.is_use() {
164 "visit_local: context.is_drop={:?} context.is_use={:?}",
171 let temp = &mut self.temps[index];
172 debug!("visit_local: temp={:?}", temp);
173 if *temp == TempState::Undefined {
175 PlaceContext::MutatingUse(MutatingUseContext::Store)
176 | PlaceContext::MutatingUse(MutatingUseContext::Call) => {
177 *temp = TempState::Defined { location, uses: 0 };
180 _ => { /* mark as unpromotable below */ }
182 } else if let TempState::Defined { ref mut uses, .. } = *temp {
183 // We always allow borrows, even mutable ones, as we need
184 // to promote mutable borrows of some ZSTs e.g., `&mut []`.
185 let allowed_use = match context {
186 PlaceContext::MutatingUse(MutatingUseContext::Borrow)
187 | PlaceContext::NonMutatingUse(_) => true,
188 PlaceContext::MutatingUse(_) | PlaceContext::NonUse(_) => false,
190 debug!("visit_local: allowed_use={:?}", allowed_use);
195 /* mark as unpromotable below */
197 *temp = TempState::Unpromotable;
200 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
201 self.super_rvalue(rvalue, location);
205 self.candidates.push(Candidate::Ref(location));
207 Rvalue::Repeat(..) if self.tcx.features().const_in_array_repeat_expressions => {
208 // FIXME(#49147) only promote the element when it isn't `Copy`
209 // (so that code that can copy it at runtime is unaffected).
210 self.candidates.push(Candidate::Repeat(location));
216 fn visit_terminator_kind(&mut self, kind: &TerminatorKind<'tcx>, location: Location) {
217 self.super_terminator_kind(kind, location);
219 if let TerminatorKind::Call { ref func, .. } = *kind {
220 if let ty::FnDef(def_id, _) = func.ty(self.body, self.tcx).kind {
221 let fn_sig = self.tcx.fn_sig(def_id);
222 if let Abi::RustIntrinsic | Abi::PlatformIntrinsic = fn_sig.abi() {
223 let name = self.tcx.item_name(def_id);
224 // FIXME(eddyb) use `#[rustc_args_required_const(2)]` for shuffles.
225 if name.as_str().starts_with("simd_shuffle") {
226 self.candidates.push(Candidate::Argument { bb: location.block, index: 2 });
228 return; // Don't double count `simd_shuffle` candidates
232 if let Some(constant_args) = args_required_const(self.tcx, def_id) {
233 for index in constant_args {
234 self.candidates.push(Candidate::Argument { bb: location.block, index });
241 fn visit_source_info(&mut self, source_info: &SourceInfo) {
242 self.span = source_info.span;
246 pub fn collect_temps_and_candidates(
249 rpo: &mut ReversePostorder<'_, 'tcx>,
250 ) -> (IndexVec<Local, TempState>, Vec<Candidate>) {
251 let mut collector = Collector {
254 temps: IndexVec::from_elem(TempState::Undefined, &body.local_decls),
258 for (bb, data) in rpo {
259 collector.visit_basic_block_data(bb, data);
261 (collector.temps, collector.candidates)
264 /// Checks whether locals that appear in a promotion context (`Candidate`) are actually promotable.
266 /// This wraps an `Item`, and has access to all fields of that `Item` via `Deref` coercion.
267 struct Validator<'a, 'tcx> {
268 item: Item<'a, 'tcx>,
269 temps: &'a IndexVec<Local, TempState>,
271 /// Explicit promotion happens e.g. for constant arguments declared via
272 /// `rustc_args_required_const`.
273 /// Implicit promotion has almost the same rules, except that disallows `const fn`
274 /// except for those marked `#[rustc_promotable]`. This is to avoid changing
275 /// a legitimate run-time operation into a failing compile-time operation
276 /// e.g. due to addresses being compared inside the function.
280 impl std::ops::Deref for Validator<'a, 'tcx> {
281 type Target = Item<'a, 'tcx>;
283 fn deref(&self) -> &Self::Target {
290 impl<'tcx> Validator<'_, 'tcx> {
291 fn validate_candidate(&self, candidate: Candidate) -> Result<(), Unpromotable> {
293 Candidate::Ref(loc) => {
294 assert!(!self.explicit);
296 let statement = &self.body[loc.block].statements[loc.statement_index];
297 match &statement.kind {
298 StatementKind::Assign(box (_, Rvalue::Ref(_, kind, place))) => {
300 BorrowKind::Shared | BorrowKind::Mut { .. } => {}
302 // FIXME(eddyb) these aren't promoted here but *could*
303 // be promoted as part of a larger value because
304 // `validate_rvalue` doesn't check them, need to
305 // figure out what is the intended behavior.
306 BorrowKind::Shallow | BorrowKind::Unique => return Err(Unpromotable),
309 // We can only promote interior borrows of promotable temps (non-temps
310 // don't get promoted anyway).
311 let base = match place.base {
312 PlaceBase::Local(local) => local,
313 _ => return Err(Unpromotable),
315 self.validate_local(base)?;
317 if place.projection.contains(&ProjectionElem::Deref) {
318 return Err(Unpromotable);
321 let mut has_mut_interior =
322 self.qualif_local::<qualifs::HasMutInterior>(base);
323 // HACK(eddyb) this should compute the same thing as
324 // `<HasMutInterior as Qualif>::in_projection` from
325 // `check_consts::qualifs` but without recursion.
326 if has_mut_interior {
327 // This allows borrowing fields which don't have
328 // `HasMutInterior`, from a type that does, e.g.:
329 // `let _: &'static _ = &(Cell::new(1), 2).1;`
330 let mut place_projection = &place.projection[..];
331 // FIXME(eddyb) use a forward loop instead of a reverse one.
332 while let [proj_base @ .., elem] = place_projection {
333 // FIXME(eddyb) this is probably excessive, with
334 // the exception of `union` member accesses.
336 Place::ty_from(&place.base, proj_base, *self.body, self.tcx)
337 .projection_ty(self.tcx, elem)
339 if ty.is_freeze(self.tcx, self.param_env, DUMMY_SP) {
340 has_mut_interior = false;
344 place_projection = proj_base;
348 // FIXME(eddyb) this duplicates part of `validate_rvalue`.
349 if has_mut_interior {
350 return Err(Unpromotable);
352 if self.qualif_local::<qualifs::NeedsDrop>(base) {
353 return Err(Unpromotable);
356 if let BorrowKind::Mut { .. } = kind {
357 let ty = place.ty(*self.body, self.tcx).ty;
359 // In theory, any zero-sized value could be borrowed
360 // mutably without consequences. However, only &mut []
361 // is allowed right now, and only in functions.
362 if self.const_kind == Some(ConstKind::StaticMut) {
363 // Inside a `static mut`, &mut [...] is also allowed.
365 ty::Array(..) | ty::Slice(_) => {}
366 _ => return Err(Unpromotable),
368 } else if let ty::Array(_, len) = ty.kind {
369 // FIXME(eddyb) the `self.is_non_const_fn` condition
370 // seems unnecessary, given that this is merely a ZST.
371 match len.try_eval_usize(self.tcx, self.param_env) {
372 Some(0) if self.const_kind.is_none() => {}
373 _ => return Err(Unpromotable),
376 return Err(Unpromotable);
385 Candidate::Repeat(loc) => {
386 assert!(!self.explicit);
388 let statement = &self.body[loc.block].statements[loc.statement_index];
389 match &statement.kind {
390 StatementKind::Assign(box (_, Rvalue::Repeat(ref operand, _))) => {
391 if !self.tcx.features().const_in_array_repeat_expressions {
392 return Err(Unpromotable);
395 self.validate_operand(operand)
400 Candidate::Argument { bb, index } => {
401 assert!(self.explicit);
403 let terminator = self.body[bb].terminator();
404 match &terminator.kind {
405 TerminatorKind::Call { args, .. } => self.validate_operand(&args[index]),
412 // FIXME(eddyb) maybe cache this?
413 fn qualif_local<Q: qualifs::Qualif>(&self, local: Local) -> bool {
414 let per_local = &|l| self.qualif_local::<Q>(l);
416 if let TempState::Defined { location: loc, .. } = self.temps[local] {
417 let num_stmts = self.body[loc.block].statements.len();
419 if loc.statement_index < num_stmts {
420 let statement = &self.body[loc.block].statements[loc.statement_index];
421 match &statement.kind {
422 StatementKind::Assign(box (_, rhs)) => Q::in_rvalue(&self.item, per_local, rhs),
425 statement.source_info.span,
426 "{:?} is not an assignment",
432 let terminator = self.body[loc.block].terminator();
433 match &terminator.kind {
434 TerminatorKind::Call { func, args, .. } => {
435 let return_ty = self.body.local_decls[local].ty;
436 Q::in_call(&self.item, per_local, func, args, return_ty)
439 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
444 let span = self.body.local_decls[local].source_info.span;
445 span_bug!(span, "{:?} not promotable, qualif_local shouldn't have been called", local);
449 // FIXME(eddyb) maybe cache this?
450 fn validate_local(&self, local: Local) -> Result<(), Unpromotable> {
451 if let TempState::Defined { location: loc, .. } = self.temps[local] {
452 let num_stmts = self.body[loc.block].statements.len();
454 if loc.statement_index < num_stmts {
455 let statement = &self.body[loc.block].statements[loc.statement_index];
456 match &statement.kind {
457 StatementKind::Assign(box (_, rhs)) => self.validate_rvalue(rhs),
460 statement.source_info.span,
461 "{:?} is not an assignment",
467 let terminator = self.body[loc.block].terminator();
468 match &terminator.kind {
469 TerminatorKind::Call { func, args, .. } => self.validate_call(func, args),
471 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
480 fn validate_place(&self, place: PlaceRef<'_, 'tcx>) -> Result<(), Unpromotable> {
482 PlaceRef { base: PlaceBase::Local(local), projection: [] } => {
483 self.validate_local(*local)
485 PlaceRef { base: PlaceBase::Static(_), projection: [] } => {
486 bug!("qualifying already promoted MIR")
488 PlaceRef { base: _, projection: [proj_base @ .., elem] } => {
490 ProjectionElem::Deref | ProjectionElem::Downcast(..) => {
491 return Err(Unpromotable);
494 ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } => {}
496 ProjectionElem::Index(local) => {
497 self.validate_local(local)?;
500 ProjectionElem::Field(..) => {
501 if self.const_kind.is_none() {
503 Place::ty_from(place.base, proj_base, *self.body, self.tcx).ty;
504 if let Some(def) = base_ty.ty_adt_def() {
505 // No promotion of union field accesses.
507 return Err(Unpromotable);
514 self.validate_place(PlaceRef { base: place.base, projection: proj_base })
519 fn validate_operand(&self, operand: &Operand<'tcx>) -> Result<(), Unpromotable> {
521 Operand::Copy(place) | Operand::Move(place) => self.validate_place(place.as_ref()),
523 // The qualifs for a constant (e.g. `HasMutInterior`) are checked in
524 // `validate_rvalue` upon access.
525 Operand::Constant(c) => {
526 if let Some(def_id) = c.check_static_ptr(self.tcx) {
527 // Only allow statics (not consts) to refer to other statics.
528 // FIXME(eddyb) does this matter at all for promotion?
529 let is_static = self.const_kind.map_or(false, |k| k.is_static());
531 return Err(Unpromotable);
534 let is_thread_local = self.tcx.has_attr(def_id, sym::thread_local);
536 return Err(Unpromotable);
545 fn validate_rvalue(&self, rvalue: &Rvalue<'tcx>) -> Result<(), Unpromotable> {
547 Rvalue::Cast(CastKind::Misc, ref operand, cast_ty) if self.const_kind.is_none() => {
548 let operand_ty = operand.ty(*self.body, self.tcx);
549 let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast");
550 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
551 match (cast_in, cast_out) {
552 (CastTy::Ptr(_), CastTy::Int(_)) | (CastTy::FnPtr, CastTy::Int(_)) => {
553 // in normal functions, mark such casts as not promotable
554 return Err(Unpromotable);
560 Rvalue::BinaryOp(op, ref lhs, _) if self.const_kind.is_none() => {
561 if let ty::RawPtr(_) | ty::FnPtr(..) = lhs.ty(*self.body, self.tcx).kind {
569 || op == BinOp::Offset
572 // raw pointer operations are not allowed inside promoteds
573 return Err(Unpromotable);
577 Rvalue::NullaryOp(NullOp::Box, _) => return Err(Unpromotable),
583 Rvalue::NullaryOp(..) => Ok(()),
585 Rvalue::Discriminant(place) | Rvalue::Len(place) => self.validate_place(place.as_ref()),
588 | Rvalue::Repeat(operand, _)
589 | Rvalue::UnaryOp(_, operand)
590 | Rvalue::Cast(_, operand, _) => self.validate_operand(operand),
592 Rvalue::BinaryOp(_, lhs, rhs) | Rvalue::CheckedBinaryOp(_, lhs, rhs) => {
593 self.validate_operand(lhs)?;
594 self.validate_operand(rhs)
597 Rvalue::AddressOf(_, place) => {
598 // Raw reborrows can come from reference to pointer coercions,
600 if let [proj_base @ .., ProjectionElem::Deref] = place.projection.as_ref() {
601 let base_ty = Place::ty_from(&place.base, proj_base, *self.body, self.tcx).ty;
602 if let ty::Ref(..) = base_ty.kind {
604 .validate_place(PlaceRef { base: &place.base, projection: proj_base });
610 Rvalue::Ref(_, kind, place) => {
611 if let BorrowKind::Mut { .. } = kind {
612 let ty = place.ty(*self.body, self.tcx).ty;
614 // In theory, any zero-sized value could be borrowed
615 // mutably without consequences. However, only &mut []
616 // is allowed right now, and only in functions.
617 if self.const_kind == Some(ConstKind::StaticMut) {
618 // Inside a `static mut`, &mut [...] is also allowed.
620 ty::Array(..) | ty::Slice(_) => {}
621 _ => return Err(Unpromotable),
623 } else if let ty::Array(_, len) = ty.kind {
624 // FIXME(eddyb): We only return `Unpromotable` for `&mut []` inside a
625 // const context which seems unnecessary given that this is merely a ZST.
626 match len.try_eval_usize(self.tcx, self.param_env) {
627 Some(0) if self.const_kind.is_none() => {}
628 _ => return Err(Unpromotable),
631 return Err(Unpromotable);
635 // Special-case reborrows to be more like a copy of the reference.
636 let mut place = place.as_ref();
637 if let [proj_base @ .., ProjectionElem::Deref] = &place.projection {
638 let base_ty = Place::ty_from(&place.base, proj_base, *self.body, self.tcx).ty;
639 if let ty::Ref(..) = base_ty.kind {
640 place = PlaceRef { base: &place.base, projection: proj_base };
644 self.validate_place(place)?;
646 // HACK(eddyb) this should compute the same thing as
647 // `<HasMutInterior as Qualif>::in_projection` from
648 // `check_consts::qualifs` but without recursion.
649 let mut has_mut_interior = match place.base {
650 PlaceBase::Local(local) => self.qualif_local::<qualifs::HasMutInterior>(*local),
651 PlaceBase::Static(_) => false,
653 if has_mut_interior {
654 let mut place_projection = place.projection;
655 // FIXME(eddyb) use a forward loop instead of a reverse one.
656 while let [proj_base @ .., elem] = place_projection {
657 // FIXME(eddyb) this is probably excessive, with
658 // the exception of `union` member accesses.
659 let ty = Place::ty_from(place.base, proj_base, *self.body, self.tcx)
660 .projection_ty(self.tcx, elem)
662 if ty.is_freeze(self.tcx, self.param_env, DUMMY_SP) {
663 has_mut_interior = false;
667 place_projection = proj_base;
670 if has_mut_interior {
671 return Err(Unpromotable);
677 Rvalue::Aggregate(_, ref operands) => {
679 self.validate_operand(o)?;
689 callee: &Operand<'tcx>,
690 args: &[Operand<'tcx>],
691 ) -> Result<(), Unpromotable> {
692 let fn_ty = callee.ty(*self.body, self.tcx);
694 if !self.explicit && self.const_kind.is_none() {
695 if let ty::FnDef(def_id, _) = fn_ty.kind {
696 // Never promote runtime `const fn` calls of
697 // functions without `#[rustc_promotable]`.
698 if !self.tcx.is_promotable_const_fn(def_id) {
699 return Err(Unpromotable);
704 let is_const_fn = match fn_ty.kind {
705 ty::FnDef(def_id, _) => {
706 is_const_fn(self.tcx, def_id)
707 || is_unstable_const_fn(self.tcx, def_id).is_some()
708 || is_lang_panic_fn(self.tcx, self.def_id)
713 return Err(Unpromotable);
716 self.validate_operand(callee)?;
718 self.validate_operand(arg)?;
725 // FIXME(eddyb) remove the differences for promotability in `static`, `const`, `const fn`.
726 pub fn validate_candidates(
728 body: ReadOnlyBodyAndCache<'_, 'tcx>,
730 temps: &IndexVec<Local, TempState>,
731 candidates: &[Candidate],
732 ) -> Vec<Candidate> {
733 let mut validator = Validator { item: Item::new(tcx, def_id, body), temps, explicit: false };
738 .filter(|&candidate| {
739 validator.explicit = candidate.forces_explicit_promotion();
741 // FIXME(eddyb) also emit the errors for shuffle indices
742 // and `#[rustc_args_required_const]` arguments here.
744 let is_promotable = validator.validate_candidate(candidate).is_ok();
746 Candidate::Argument { bb, index } if !is_promotable => {
747 let span = body[bb].terminator().source_info.span;
748 let msg = format!("argument {} is required to be a constant", index + 1);
749 tcx.sess.span_err(span, &msg);
759 struct Promoter<'a, 'tcx> {
761 source: &'a mut BodyAndCache<'tcx>,
762 promoted: BodyAndCache<'tcx>,
763 temps: &'a mut IndexVec<Local, TempState>,
764 extra_statements: &'a mut Vec<(Location, Statement<'tcx>)>,
766 /// If true, all nested temps are also kept in the
767 /// source MIR, not moved to the promoted MIR.
771 impl<'a, 'tcx> Promoter<'a, 'tcx> {
772 fn new_block(&mut self) -> BasicBlock {
773 let span = self.promoted.span;
774 self.promoted.basic_blocks_mut().push(BasicBlockData {
776 terminator: Some(Terminator {
777 source_info: SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE },
778 kind: TerminatorKind::Return,
784 fn assign(&mut self, dest: Local, rvalue: Rvalue<'tcx>, span: Span) {
785 let last = self.promoted.basic_blocks().last().unwrap();
786 let data = &mut self.promoted[last];
787 data.statements.push(Statement {
788 source_info: SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE },
789 kind: StatementKind::Assign(box (Place::from(dest), rvalue)),
793 fn is_temp_kind(&self, local: Local) -> bool {
794 self.source.local_kind(local) == LocalKind::Temp
797 /// Copies the initialization of this temp to the
798 /// promoted MIR, recursing through temps.
799 fn promote_temp(&mut self, temp: Local) -> Local {
800 let old_keep_original = self.keep_original;
801 let loc = match self.temps[temp] {
802 TempState::Defined { location, uses } if uses > 0 => {
804 self.keep_original = true;
809 span_bug!(self.promoted.span, "{:?} not promotable: {:?}", temp, state);
812 if !self.keep_original {
813 self.temps[temp] = TempState::PromotedOut;
816 let num_stmts = self.source[loc.block].statements.len();
817 let new_temp = self.promoted.local_decls.push(LocalDecl::new_temp(
818 self.source.local_decls[temp].ty,
819 self.source.local_decls[temp].source_info.span,
822 debug!("promote({:?} @ {:?}/{:?}, {:?})", temp, loc, num_stmts, self.keep_original);
824 // First, take the Rvalue or Call out of the source MIR,
825 // or duplicate it, depending on keep_original.
826 if loc.statement_index < num_stmts {
827 let (mut rvalue, source_info) = {
828 let statement = &mut self.source[loc.block].statements[loc.statement_index];
829 let rhs = match statement.kind {
830 StatementKind::Assign(box (_, ref mut rhs)) => rhs,
833 statement.source_info.span,
834 "{:?} is not an assignment",
841 if self.keep_original {
844 let unit = Rvalue::Aggregate(box AggregateKind::Tuple, vec![]);
845 mem::replace(rhs, unit)
847 statement.source_info,
851 self.visit_rvalue(&mut rvalue, loc);
852 self.assign(new_temp, rvalue, source_info.span);
854 let terminator = if self.keep_original {
855 self.source[loc.block].terminator().clone()
857 let terminator = self.source[loc.block].terminator_mut();
858 let target = match terminator.kind {
859 TerminatorKind::Call { destination: Some((_, target)), .. } => target,
861 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
865 source_info: terminator.source_info,
866 kind: mem::replace(&mut terminator.kind, TerminatorKind::Goto { target }),
870 match terminator.kind {
871 TerminatorKind::Call { mut func, mut args, from_hir_call, .. } => {
872 self.visit_operand(&mut func, loc);
873 for arg in &mut args {
874 self.visit_operand(arg, loc);
877 let last = self.promoted.basic_blocks().last().unwrap();
878 let new_target = self.new_block();
880 *self.promoted[last].terminator_mut() = Terminator {
881 kind: TerminatorKind::Call {
885 destination: Some((Place::from(new_temp), new_target)),
892 span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
897 self.keep_original = old_keep_original;
901 fn promote_candidate(
904 candidate: Candidate,
905 next_promoted_id: usize,
906 ) -> Option<BodyAndCache<'tcx>> {
908 let promoted = &mut self.promoted;
909 let promoted_id = Promoted::new(next_promoted_id);
911 let mut promoted_operand = |ty, span| {
912 promoted.span = span;
913 promoted.local_decls[RETURN_PLACE] = LocalDecl::new_return_place(ty, span);
915 Operand::Constant(Box::new(Constant {
918 literal: tcx.mk_const(ty::Const {
920 val: ty::ConstKind::Unevaluated(
922 InternalSubsts::identity_for_item(tcx, def_id),
928 let (blocks, local_decls) = self.source.basic_blocks_and_local_decls_mut();
930 Candidate::Ref(loc) => {
931 let ref mut statement = blocks[loc.block].statements[loc.statement_index];
932 match statement.kind {
933 StatementKind::Assign(box (
935 Rvalue::Ref(ref mut region, borrow_kind, ref mut place),
937 // Use the underlying local for this (necessarily interior) borrow.
938 let ty = place.base.ty(local_decls).ty;
939 let span = statement.source_info.span;
941 let ref_ty = tcx.mk_ref(
942 tcx.lifetimes.re_static,
943 ty::TypeAndMut { ty, mutbl: borrow_kind.to_mutbl_lossy() },
946 *region = tcx.lifetimes.re_static;
948 let mut projection = vec![PlaceElem::Deref];
949 projection.extend(place.projection);
950 place.projection = tcx.intern_place_elems(&projection);
952 // Create a temp to hold the promoted reference.
953 // This is because `*r` requires `r` to be a local,
954 // otherwise we would use the `promoted` directly.
955 let mut promoted_ref = LocalDecl::new_temp(ref_ty, span);
956 promoted_ref.source_info = statement.source_info;
957 let promoted_ref = local_decls.push(promoted_ref);
958 assert_eq!(self.temps.push(TempState::Unpromotable), promoted_ref);
960 let promoted_ref_statement = Statement {
961 source_info: statement.source_info,
962 kind: StatementKind::Assign(Box::new((
963 Place::from(promoted_ref),
964 Rvalue::Use(promoted_operand(ref_ty, span)),
967 self.extra_statements.push((loc, promoted_ref_statement));
970 tcx.lifetimes.re_static,
975 PlaceBase::Local(promoted_ref),
977 projection: List::empty(),
984 Candidate::Repeat(loc) => {
985 let ref mut statement = 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);
1043 fn process_projection_elem(&mut self, elem: &PlaceElem<'tcx>) -> Option<PlaceElem<'tcx>> {
1045 PlaceElem::Index(local) if self.is_temp_kind(*local) => {
1046 Some(PlaceElem::Index(self.promote_temp(*local)))
1053 pub fn promote_candidates<'tcx>(
1055 body: &mut BodyAndCache<'tcx>,
1057 mut temps: IndexVec<Local, TempState>,
1058 candidates: Vec<Candidate>,
1059 ) -> IndexVec<Promoted, BodyAndCache<'tcx>> {
1060 // Visit candidates in reverse, in case they're nested.
1061 debug!("promote_candidates({:?})", candidates);
1063 let mut promotions = IndexVec::new();
1065 let mut extra_statements = vec![];
1066 for candidate in candidates.into_iter().rev() {
1068 Candidate::Repeat(Location { block, statement_index })
1069 | Candidate::Ref(Location { block, statement_index }) => {
1070 match &body[block].statements[statement_index].kind {
1071 StatementKind::Assign(box (place, _)) => {
1072 if let Some(local) = place.as_local() {
1073 if temps[local] == TempState::PromotedOut {
1074 // Already promoted.
1082 Candidate::Argument { .. } => {}
1085 // Declare return place local so that `mir::Body::new` doesn't complain.
1086 let initial_locals =
1087 iter::once(LocalDecl::new_return_place(tcx.types.never, body.span)).collect();
1089 let mut promoted = Body::new(
1091 // FIXME: maybe try to filter this to avoid blowing up
1093 body.source_scopes.clone(),
1100 body.generator_kind,
1102 promoted.ignore_interior_mut_in_const_validation = true;
1104 let promoter = Promoter {
1105 promoted: BodyAndCache::new(promoted),
1109 extra_statements: &mut extra_statements,
1110 keep_original: false,
1113 //FIXME(oli-obk): having a `maybe_push()` method on `IndexVec` might be nice
1114 if let Some(promoted) = promoter.promote_candidate(def_id, candidate, promotions.len()) {
1115 promotions.push(promoted);
1119 // Insert each of `extra_statements` before its indicated location, which
1120 // has to be done in reverse location order, to not invalidate the rest.
1121 extra_statements.sort_by_key(|&(loc, _)| cmp::Reverse(loc));
1122 for (loc, statement) in extra_statements {
1123 body[loc.block].statements.insert(loc.statement_index, statement);
1126 // Eliminate assignments to, and drops of promoted temps.
1127 let promoted = |index: Local| temps[index] == TempState::PromotedOut;
1128 for block in body.basic_blocks_mut() {
1129 block.statements.retain(|statement| match &statement.kind {
1130 StatementKind::Assign(box (place, _)) => {
1131 if let Some(index) = place.as_local() {
1137 StatementKind::StorageLive(index) | StatementKind::StorageDead(index) => {
1142 let terminator = block.terminator_mut();
1143 match &terminator.kind {
1144 TerminatorKind::Drop { location: place, target, .. } => {
1145 if let Some(index) = place.as_local() {
1146 if promoted(index) {
1147 terminator.kind = TerminatorKind::Goto { target: *target };
1158 /// This function returns `true` if the `const_in_array_repeat_expressions` feature attribute should
1159 /// be suggested. This function is probably quite expensive, it shouldn't be run in the happy path.
1160 /// Feature attribute should be suggested if `operand` can be promoted and the feature is not
1162 crate fn should_suggest_const_in_array_repeat_expressions_attribute<'tcx>(
1165 body: ReadOnlyBodyAndCache<'_, 'tcx>,
1166 operand: &Operand<'tcx>,
1168 let mut rpo = traversal::reverse_postorder(&body);
1169 let (temps, _) = collect_temps_and_candidates(tcx, &body, &mut rpo);
1171 Validator { item: Item::new(tcx, mir_def_id, body), temps: &temps, explicit: false };
1173 let should_promote = validator.validate_operand(operand).is_ok();
1174 let feature_flag = tcx.features().const_in_array_repeat_expressions;
1176 "should_suggest_const_in_array_repeat_expressions_flag: mir_def_id={:?} \
1177 should_promote={:?} feature_flag={:?}",
1178 mir_def_id, should_promote, feature_flag
1180 should_promote && !feature_flag