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
, lhs
, rhs
) | Rvalue
::CheckedBinaryOp(op
, 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
),
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
{
1001 literal
: tcx
.mk_const(ty
::Const
{
1003 val
: ty
::ConstKind
::Unevaluated(
1005 InternalSubsts
::for_item(tcx
, def
.did
, |param
, _
| {
1006 if let ty
::GenericParamDefKind
::Lifetime
= param
.kind
{
1007 tcx
.lifetimes
.re_erased
.into()
1009 tcx
.mk_param_from_def(param
)
1017 let (blocks
, local_decls
) = self.source
.basic_blocks_and_local_decls_mut();
1019 Candidate
::Ref(loc
) => {
1020 let statement
= &mut blocks
[loc
.block
].statements
[loc
.statement_index
];
1021 match statement
.kind
{
1022 StatementKind
::Assign(box (
1024 Rvalue
::Ref(ref mut region
, borrow_kind
, ref mut place
),
1026 // Use the underlying local for this (necessarily interior) borrow.
1027 let ty
= local_decls
.local_decls()[place
.local
].ty
;
1028 let span
= statement
.source_info
.span
;
1030 let ref_ty
= tcx
.mk_ref(
1031 tcx
.lifetimes
.re_erased
,
1032 ty
::TypeAndMut { ty, mutbl: borrow_kind.to_mutbl_lossy() }
,
1035 *region
= tcx
.lifetimes
.re_erased
;
1037 let mut projection
= vec
![PlaceElem
::Deref
];
1038 projection
.extend(place
.projection
);
1039 place
.projection
= tcx
.intern_place_elems(&projection
);
1041 // Create a temp to hold the promoted reference.
1042 // This is because `*r` requires `r` to be a local,
1043 // otherwise we would use the `promoted` directly.
1044 let mut promoted_ref
= LocalDecl
::new(ref_ty
, span
);
1045 promoted_ref
.source_info
= statement
.source_info
;
1046 let promoted_ref
= local_decls
.push(promoted_ref
);
1047 assert_eq
!(self.temps
.push(TempState
::Unpromotable
), promoted_ref
);
1049 let promoted_ref_statement
= Statement
{
1050 source_info
: statement
.source_info
,
1051 kind
: StatementKind
::Assign(Box
::new((
1052 Place
::from(promoted_ref
),
1053 Rvalue
::Use(promoted_operand(ref_ty
, span
)),
1056 self.extra_statements
.push((loc
, promoted_ref_statement
));
1059 tcx
.lifetimes
.re_erased
,
1062 local
: mem
::replace(&mut place
.local
, promoted_ref
),
1063 projection
: List
::empty(),
1070 Candidate
::Argument { bb, index }
=> {
1071 let terminator
= blocks
[bb
].terminator_mut();
1072 match terminator
.kind
{
1073 TerminatorKind
::Call { ref mut args, .. }
=> {
1074 let ty
= args
[index
].ty(local_decls
, self.tcx
);
1075 let span
= terminator
.source_info
.span
;
1077 Rvalue
::Use(mem
::replace(&mut args
[index
], promoted_operand(ty
, span
)))
1079 // We expected a `TerminatorKind::Call` for which we'd like to promote an
1080 // argument. `qualify_consts` saw a `TerminatorKind::Call` here, but
1081 // we are seeing a `Goto`. That means that the `promote_temps` method
1082 // already promoted this call away entirely. This case occurs when calling
1083 // a function requiring a constant argument and as that constant value
1084 // providing a value whose computation contains another call to a function
1085 // requiring a constant argument.
1086 TerminatorKind
::Goto { .. }
=> return None
,
1090 Candidate
::InlineAsm { bb, index }
=> {
1091 let terminator
= blocks
[bb
].terminator_mut();
1092 match terminator
.kind
{
1093 TerminatorKind
::InlineAsm { ref mut operands, .. }
=> {
1094 match &mut operands
[index
] {
1095 InlineAsmOperand
::Const { ref mut value }
=> {
1096 let ty
= value
.ty(local_decls
, self.tcx
);
1097 let span
= terminator
.source_info
.span
;
1099 Rvalue
::Use(mem
::replace(value
, promoted_operand(ty
, span
)))
1111 assert_eq
!(self.new_block(), START_BLOCK
);
1114 Location { block: BasicBlock::new(0), statement_index: usize::MAX }
,
1117 let span
= self.promoted
.span
;
1118 self.assign(RETURN_PLACE
, rvalue
, span
);
1123 /// Replaces all temporaries with their promoted counterparts.
1124 impl<'a
, 'tcx
> MutVisitor
<'tcx
> for Promoter
<'a
, 'tcx
> {
1125 fn tcx(&self) -> TyCtxt
<'tcx
> {
1129 fn visit_local(&mut self, local
: &mut Local
, _
: PlaceContext
, _
: Location
) {
1130 if self.is_temp_kind(*local
) {
1131 *local
= self.promote_temp(*local
);
1136 pub fn promote_candidates
<'tcx
>(
1137 body
: &mut Body
<'tcx
>,
1139 mut temps
: IndexVec
<Local
, TempState
>,
1140 candidates
: Vec
<Candidate
>,
1141 ) -> IndexVec
<Promoted
, Body
<'tcx
>> {
1142 // Visit candidates in reverse, in case they're nested.
1143 debug
!("promote_candidates({:?})", candidates
);
1145 let mut promotions
= IndexVec
::new();
1147 let mut extra_statements
= vec
![];
1148 for candidate
in candidates
.into_iter().rev() {
1150 Candidate
::Ref(Location { block, statement_index }
) => {
1151 if let StatementKind
::Assign(box (place
, _
)) =
1152 &body
[block
].statements
[statement_index
].kind
1154 if let Some(local
) = place
.as_local() {
1155 if temps
[local
] == TempState
::PromotedOut
{
1156 // Already promoted.
1162 Candidate
::Argument { .. }
| Candidate
::InlineAsm { .. }
=> {}
1165 // Declare return place local so that `mir::Body::new` doesn't complain.
1166 let initial_locals
= iter
::once(LocalDecl
::new(tcx
.types
.never
, body
.span
)).collect();
1168 let mut scope
= body
.source_scopes
[candidate
.source_info(body
).scope
].clone();
1169 scope
.parent_scope
= None
;
1171 let promoted
= Body
::new(
1172 body
.source
, // `promoted` gets filled in below
1174 IndexVec
::from_elem_n(scope
, 1),
1180 body
.generator_kind
,
1183 let promoter
= Promoter
{
1188 extra_statements
: &mut extra_statements
,
1189 keep_original
: false,
1192 //FIXME(oli-obk): having a `maybe_push()` method on `IndexVec` might be nice
1193 if let Some(mut promoted
) = promoter
.promote_candidate(candidate
, promotions
.len()) {
1194 promoted
.source
.promoted
= Some(promotions
.next_index());
1195 promotions
.push(promoted
);
1199 // Insert each of `extra_statements` before its indicated location, which
1200 // has to be done in reverse location order, to not invalidate the rest.
1201 extra_statements
.sort_by_key(|&(loc
, _
)| cmp
::Reverse(loc
));
1202 for (loc
, statement
) in extra_statements
{
1203 body
[loc
.block
].statements
.insert(loc
.statement_index
, statement
);
1206 // Eliminate assignments to, and drops of promoted temps.
1207 let promoted
= |index
: Local
| temps
[index
] == TempState
::PromotedOut
;
1208 for block
in body
.basic_blocks_mut() {
1209 block
.statements
.retain(|statement
| match &statement
.kind
{
1210 StatementKind
::Assign(box (place
, _
)) => {
1211 if let Some(index
) = place
.as_local() {
1217 StatementKind
::StorageLive(index
) | StatementKind
::StorageDead(index
) => {
1222 let terminator
= block
.terminator_mut();
1223 if let TerminatorKind
::Drop { place, target, .. }
= &terminator
.kind
{
1224 if let Some(index
) = place
.as_local() {
1225 if promoted(index
) {
1226 terminator
.kind
= TerminatorKind
::Goto { target: *target }
;