Skip to main content

rustc_mir_transform/
promote_consts.rs

1//! A pass that promotes borrows of constant rvalues.
2//!
3//! The rvalues considered constant are trees of temps, each with exactly one
4//! initialization, and holding a constant value with no interior mutability.
5//! They are placed into a new MIR constant body in `promoted` and the borrow
6//! rvalue is replaced with a `Literal::Promoted` using the index into
7//! `promoted` of that constant MIR.
8//!
9//! This pass assumes that every use is dominated by an initialization and can
10//! otherwise silence errors, if move analysis runs after promotion on broken
11//! MIR.
12
13use std::cell::Cell;
14use std::{assert_matches, cmp, iter, mem};
15
16use either::{Left, Right};
17use rustc_const_eval::check_consts::{ConstCx, qualifs};
18use rustc_data_structures::fx::FxHashSet;
19use rustc_data_structures::thin_vec::ThinVec;
20use rustc_hir as hir;
21use rustc_hir::def::DefKind;
22use rustc_index::{IndexSlice, IndexVec};
23use rustc_middle::mir::visit::{MutVisitor, MutatingUseContext, PlaceContext, Visitor};
24use rustc_middle::mir::*;
25use rustc_middle::ty::{self, GenericArgs, List, Ty, TyCtxt, TypeVisitableExt};
26use rustc_middle::{bug, mir, span_bug};
27use rustc_span::{Span, Spanned};
28use tracing::{debug, instrument};
29
30use crate::PassPolicy;
31
32/// A `MirPass` for promotion.
33///
34/// Promotion is the extraction of promotable temps into separate MIR bodies so they can have
35/// `'static` lifetime.
36///
37/// After this pass is run, `promoted_fragments` will hold the MIR body corresponding to each
38/// newly created `Constant`.
39#[derive(Default)]
40pub(super) struct PromoteTemps<'tcx> {
41    // Must use `Cell` because `run_pass` takes `&self`, not `&mut self`.
42    pub promoted_fragments: Cell<IndexVec<Promoted, Body<'tcx>>>,
43}
44
45impl<'tcx> crate::MirPass<'tcx> for PromoteTemps<'tcx> {
46    fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
47        // There's not really any point in promoting errorful MIR.
48        //
49        // This does not include MIR that failed const-checking, which we still try to promote.
50        if let Err(_) = body.return_ty().error_reported() {
51            debug!("PromoteTemps: MIR had errors");
52            return;
53        }
54        if body.source.promoted.is_some() {
55            return;
56        }
57
58        let ccx = ConstCx::new(tcx, body);
59        let (mut temps, all_candidates) = collect_temps_and_candidates(&ccx);
60
61        let promotable_candidates = validate_candidates(&ccx, &mut temps, all_candidates);
62
63        let promoted = promote_candidates(body, tcx, temps, promotable_candidates);
64        self.promoted_fragments.set(promoted);
65    }
66
67    fn policy(&self, _sess: &rustc_session::Session) -> PassPolicy {
68        // Implements promotion by extracting eligible values into separate constant MIR bodies.
69        PassPolicy::Required
70    }
71}
72
73/// State of a temporary during collection and promotion.
74#[derive(Copy, Clone, PartialEq, Eq, Debug)]
75enum TempState {
76    /// No references to this temp.
77    Undefined,
78    /// One direct assignment and any number of direct uses.
79    /// A borrow of this temp is promotable if the assigned
80    /// value is qualified as constant.
81    Defined { location: Location, uses: usize, valid: Result<(), ()> },
82    /// Any other combination of assignments/uses.
83    Unpromotable,
84    /// This temp was part of an rvalue which got extracted
85    /// during promotion and needs cleanup.
86    PromotedOut,
87}
88
89/// A "root candidate" for promotion, which will become the
90/// returned value in a promoted MIR, unless it's a subset
91/// of a larger candidate.
92#[derive(Copy, Clone, PartialEq, Eq, Debug)]
93struct Candidate {
94    location: Location,
95}
96
97struct Collector<'a, 'tcx> {
98    ccx: &'a ConstCx<'a, 'tcx>,
99    temps: IndexVec<Local, TempState>,
100    candidates: Vec<Candidate>,
101}
102
103impl<'tcx> Visitor<'tcx> for Collector<'_, 'tcx> {
104    #[instrument(level = "debug", skip(self))]
105    fn visit_local(&mut self, index: Local, context: PlaceContext, location: Location) {
106        // We're only interested in temporaries and the return place
107        match self.ccx.body.local_kind(index) {
108            LocalKind::Arg => return,
109            LocalKind::Temp if self.ccx.body.local_decls[index].is_user_variable() => return,
110            LocalKind::ReturnPointer | LocalKind::Temp => {}
111        }
112
113        // Ignore drops, if the temp gets promoted,
114        // then it's constant and thus drop is noop.
115        // Non-uses are also irrelevant.
116        if context.is_drop() || !context.is_use() {
117            debug!(is_drop = context.is_drop(), is_use = context.is_use());
118            return;
119        }
120
121        let temp = &mut self.temps[index];
122        debug!(?temp);
123        *temp = match *temp {
124            TempState::Undefined => match context {
125                PlaceContext::MutatingUse(MutatingUseContext::Store | MutatingUseContext::Call) => {
126                    TempState::Defined { location, uses: 0, valid: Err(()) }
127                }
128                _ => TempState::Unpromotable,
129            },
130            TempState::Defined { ref mut uses, .. } => {
131                // We always allow borrows, even mutable ones, as we need
132                // to promote mutable borrows of some ZSTs e.g., `&mut []`.
133                let allowed_use = match context {
134                    PlaceContext::MutatingUse(MutatingUseContext::Borrow)
135                    | PlaceContext::NonMutatingUse(_) => true,
136                    PlaceContext::MutatingUse(_) | PlaceContext::NonUse(_) => false,
137                };
138                debug!(?allowed_use);
139                if allowed_use {
140                    *uses += 1;
141                    return;
142                }
143                TempState::Unpromotable
144            }
145            TempState::Unpromotable | TempState::PromotedOut => TempState::Unpromotable,
146        };
147        debug!(?temp);
148    }
149
150    fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
151        self.super_rvalue(rvalue, location);
152
153        if let Rvalue::Ref(..) = *rvalue {
154            self.candidates.push(Candidate { location });
155        }
156    }
157}
158
159fn collect_temps_and_candidates<'tcx>(
160    ccx: &ConstCx<'_, 'tcx>,
161) -> (IndexVec<Local, TempState>, Vec<Candidate>) {
162    let mut collector = Collector {
163        temps: IndexVec::from_elem(TempState::Undefined, &ccx.body.local_decls),
164        candidates: vec![],
165        ccx,
166    };
167    for (bb, data) in traversal::reverse_postorder(ccx.body) {
168        collector.visit_basic_block_data(bb, data);
169    }
170    (collector.temps, collector.candidates)
171}
172
173/// Checks whether locals that appear in a promotion context (`Candidate`) are actually promotable.
174///
175/// This wraps an `Item`, and has access to all fields of that `Item` via `Deref` coercion.
176struct Validator<'a, 'tcx> {
177    ccx: &'a ConstCx<'a, 'tcx>,
178    temps: &'a mut IndexSlice<Local, TempState>,
179    /// For backwards compatibility, we are promoting function calls in `const`/`static`
180    /// initializers. But we want to avoid evaluating code that might panic and that otherwise would
181    /// not have been evaluated, so we only promote such calls in basic blocks that are guaranteed
182    /// to execute. In other words, we only promote such calls in basic blocks that are definitely
183    /// not dead code. Here we cache the result of computing that set of basic blocks.
184    promotion_safe_blocks: Option<FxHashSet<BasicBlock>>,
185}
186
187impl<'a, 'tcx> std::ops::Deref for Validator<'a, 'tcx> {
188    type Target = ConstCx<'a, 'tcx>;
189
190    fn deref(&self) -> &Self::Target {
191        self.ccx
192    }
193}
194
195struct Unpromotable;
196
197impl<'tcx> Validator<'_, 'tcx> {
198    fn validate_candidate(&mut self, candidate: Candidate) -> Result<(), Unpromotable> {
199        let Left(statement) = self.body.stmt_at(candidate.location) else { bug!() };
200        let Some((_, Rvalue::Ref(_, kind, place))) = statement.kind.as_assign() else { bug!() };
201
202        // We can only promote interior borrows of promotable temps (non-temps
203        // don't get promoted anyway).
204        self.validate_local(place.local)?;
205
206        // The reference operation itself must be promotable.
207        // (Needs to come after `validate_local` to avoid ICEs.)
208        self.validate_ref(*kind, place)?;
209
210        // We do not check all the projections (they do not get promoted anyway),
211        // but we do stay away from promoting anything involving a dereference.
212        if place.projection.contains(&ProjectionElem::Deref) {
213            return Err(Unpromotable);
214        }
215
216        Ok(())
217    }
218
219    // FIXME(eddyb) maybe cache this?
220    fn qualif_local<Q: qualifs::Qualif>(&mut self, local: Local) -> bool {
221        let TempState::Defined { location: loc, .. } = self.temps[local] else {
222            return false;
223        };
224
225        let stmt_or_term = self.body.stmt_at(loc);
226        match stmt_or_term {
227            Left(statement) => {
228                let Some((_, rhs)) = statement.kind.as_assign() else {
229                    span_bug!(statement.source_info.span, "{:?} is not an assignment", statement)
230                };
231                qualifs::in_rvalue::<Q, _>(self.ccx, &mut |l| self.qualif_local::<Q>(l), rhs)
232            }
233            Right(terminator) => {
234                assert_matches!(terminator.kind, TerminatorKind::Call { .. });
235                let return_ty = self.body.local_decls[local].ty;
236                Q::in_any_value_of_ty(self.ccx, return_ty)
237            }
238        }
239    }
240
241    fn validate_local(&mut self, local: Local) -> Result<(), Unpromotable> {
242        let TempState::Defined { location: loc, uses, valid } = self.temps[local] else {
243            return Err(Unpromotable);
244        };
245
246        // We cannot promote things that need dropping, since the promoted value would not get
247        // dropped.
248        if self.qualif_local::<qualifs::NeedsDrop>(local) {
249            return Err(Unpromotable);
250        }
251
252        if valid.is_ok() {
253            return Ok(());
254        }
255
256        let ok = {
257            let stmt_or_term = self.body.stmt_at(loc);
258            match stmt_or_term {
259                Left(statement) => {
260                    let Some((_, rhs)) = statement.kind.as_assign() else {
261                        span_bug!(
262                            statement.source_info.span,
263                            "{:?} is not an assignment",
264                            statement
265                        )
266                    };
267                    self.validate_rvalue(rhs)
268                }
269                Right(terminator) => match &terminator.kind {
270                    TerminatorKind::Call { func, args, .. } => {
271                        self.validate_call(func, args, loc.block)
272                    }
273                    TerminatorKind::Yield { .. } => Err(Unpromotable),
274                    kind => {
275                        span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
276                    }
277                },
278            }
279        };
280
281        self.temps[local] = match ok {
282            Ok(()) => TempState::Defined { location: loc, uses, valid: Ok(()) },
283            Err(_) => TempState::Unpromotable,
284        };
285
286        ok
287    }
288
289    fn validate_place(&mut self, place: PlaceRef<'tcx>) -> Result<(), Unpromotable> {
290        let Some((place_base, elem)) = place.last_projection() else {
291            return self.validate_local(place.local);
292        };
293
294        // Validate topmost projection, then recurse.
295        match elem {
296            // Recurse directly.
297            ProjectionElem::ConstantIndex { .. }
298            | ProjectionElem::Subslice { .. }
299            | ProjectionElem::UnwrapUnsafeBinder(_) => {}
300
301            // Never recurse.
302            ProjectionElem::OpaqueCast(..) | ProjectionElem::Downcast(..) => {
303                return Err(Unpromotable);
304            }
305
306            ProjectionElem::Deref => {
307                // When a static is used by-value, that gets desugared to `*STATIC_ADDR`,
308                // and we need to be able to promote this. So check if this deref matches
309                // that specific pattern.
310
311                // We need to make sure this is a `Deref` of a local with no further projections.
312                // Discussion can be found at
313                // https://github.com/rust-lang/rust/pull/74945#discussion_r463063247
314                if let Some(local) = place_base.as_local()
315                    && let TempState::Defined { location, .. } = self.temps[local]
316                    && let Left(def_stmt) = self.body.stmt_at(location)
317                    && let Some((_, Rvalue::Use(Operand::Constant(c), _))) = def_stmt.kind.as_assign()
318                    && let Some(did) = c.check_static_ptr(self.tcx)
319                    // Evaluating a promoted may not read statics except if it got
320                    // promoted from a static (this is a CTFE check). So we
321                    // can only promote static accesses inside statics.
322                    && let Some(hir::ConstContext::Static(..)) = self.const_kind
323                    && !self.tcx.is_thread_local_static(did)
324                {
325                    // Recurse.
326                } else {
327                    return Err(Unpromotable);
328                }
329            }
330            ProjectionElem::Index(local) => {
331                // Only accept if we can predict the index and are indexing an array.
332                if let TempState::Defined { location: loc, .. } = self.temps[local]
333                    && let Left(statement) =  self.body.stmt_at(loc)
334                    && let Some((_, Rvalue::Use(Operand::Constant(c), _))) = statement.kind.as_assign()
335                    && self.should_evaluate_for_promotion_checks(c.const_)
336                    && let Some(idx) = c.const_.try_eval_target_usize(self.tcx, self.typing_env)
337                    // Determine the type of the thing we are indexing.
338                    && let ty::Array(_, len) = place_base.ty(self.body, self.tcx).ty.kind()
339                    // It's an array; determine its length.
340                    && let Some(len) = len.try_to_target_usize(self.tcx)
341                    // If the index is in-bounds, go ahead.
342                    && idx < len
343                {
344                    self.validate_local(local)?;
345                    // Recurse.
346                } else {
347                    return Err(Unpromotable);
348                }
349            }
350
351            ProjectionElem::Field(..) => {
352                let base_ty = place_base.ty(self.body, self.tcx).ty;
353                if base_ty.is_union() {
354                    // No promotion of union field accesses.
355                    return Err(Unpromotable);
356                }
357            }
358        }
359
360        self.validate_place(place_base)
361    }
362
363    fn validate_operand(&mut self, operand: &Operand<'tcx>) -> Result<(), Unpromotable> {
364        match operand {
365            Operand::Copy(place) | Operand::Move(place) => self.validate_place(place.as_ref()),
366
367            // `RuntimeChecks` behaves different in const-eval and runtime MIR,
368            // so we do not promote it.
369            Operand::RuntimeChecks(_) => Err(Unpromotable),
370
371            // The qualifs for a constant (e.g. `HasMutInterior`) are checked in
372            // `validate_rvalue` upon access.
373            Operand::Constant(c) => {
374                if let Some(def_id) = c.check_static_ptr(self.tcx) {
375                    // Only allow statics (not consts) to refer to other statics.
376                    // FIXME(eddyb) does this matter at all for promotion?
377                    // FIXME(RalfJung) it makes little sense to not promote this in `fn`/`const fn`,
378                    // and in `const` this cannot occur anyway. The only concern is that we might
379                    // promote even `let x = &STATIC` which would be useless, but this applies to
380                    // promotion inside statics as well.
381                    let is_static = matches!(self.const_kind, Some(hir::ConstContext::Static(_)));
382                    if !is_static {
383                        return Err(Unpromotable);
384                    }
385
386                    let is_thread_local = self.tcx.is_thread_local_static(def_id);
387                    if is_thread_local {
388                        return Err(Unpromotable);
389                    }
390                }
391
392                Ok(())
393            }
394        }
395    }
396
397    fn validate_ref(&mut self, kind: BorrowKind, place: &Place<'tcx>) -> Result<(), Unpromotable> {
398        match kind {
399            // Reject these borrow types just to be safe.
400            // FIXME(RalfJung): could we allow them? Should we? No point in it until we have a
401            // usecase.
402            BorrowKind::Fake(_) | BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture } => {
403                return Err(Unpromotable);
404            }
405
406            BorrowKind::Shared => {
407                let has_mut_interior = self.qualif_local::<qualifs::HasMutInterior>(place.local);
408                if has_mut_interior {
409                    return Err(Unpromotable);
410                }
411            }
412
413            // FIXME: consider changing this to only promote &mut [] for default borrows,
414            // also forbidding two phase borrows
415            BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow } => {
416                let ty = place.ty(self.body, self.tcx).ty;
417
418                // In theory, any zero-sized value could be borrowed
419                // mutably without consequences. However, only &mut []
420                // is allowed right now.
421                let ty::Array(_, len) = ty.kind() else { return Err(Unpromotable) };
422                let Some(0) = len.try_to_target_usize(self.tcx) else { return Err(Unpromotable) };
423            }
424        }
425
426        Ok(())
427    }
428
429    fn validate_rvalue(&mut self, rvalue: &Rvalue<'tcx>) -> Result<(), Unpromotable> {
430        match rvalue {
431            Rvalue::Use(_operand, WithRetag::No) => {
432                // This shouldn't actually happen, but just to be safe: we'll later add the promoted
433                // with retagging, so don't promote anything that didn't already have retagging.
434                return Err(Unpromotable);
435            }
436            Rvalue::Use(operand, _)
437            | Rvalue::Repeat(operand, _)
438            | Rvalue::WrapUnsafeBinder(operand, _) => {
439                self.validate_operand(operand)?;
440            }
441            Rvalue::CopyForDeref(place) => {
442                let op = &Operand::Copy(*place);
443                self.validate_operand(op)?
444            }
445
446            Rvalue::Discriminant(place) => self.validate_place(place.as_ref())?,
447
448            Rvalue::ThreadLocalRef(_) => return Err(Unpromotable),
449
450            // ptr-to-int casts are not possible in consts and thus not promotable
451            Rvalue::Cast(CastKind::PointerExposeProvenance, _, _) => return Err(Unpromotable),
452
453            // all other casts including int-to-ptr casts are fine, they just use the integer value
454            // at pointer type.
455            Rvalue::Cast(_, operand, _) => {
456                self.validate_operand(operand)?;
457            }
458
459            Rvalue::UnaryOp(op, operand) => {
460                match op {
461                    // These operations can never fail.
462                    UnOp::Neg | UnOp::Not | UnOp::PtrMetadata => {}
463                }
464
465                self.validate_operand(operand)?;
466            }
467
468            Rvalue::BinaryOp(op, (lhs, rhs)) => {
469                let op = *op;
470                let lhs_ty = lhs.ty(self.body, self.tcx);
471
472                if let ty::RawPtr(_, _) | ty::FnPtr(..) = lhs_ty.kind() {
473                    // Raw and fn pointer operations are not allowed inside consts and thus not
474                    // promotable.
475                    assert_matches!(
476                        op,
477                        BinOp::Eq
478                            | BinOp::Ne
479                            | BinOp::Le
480                            | BinOp::Lt
481                            | BinOp::Ge
482                            | BinOp::Gt
483                            | BinOp::Offset
484                    );
485                    return Err(Unpromotable);
486                }
487
488                match op {
489                    BinOp::Div | BinOp::Rem => {
490                        if lhs_ty.is_integral() {
491                            let sz = lhs_ty.primitive_size(self.tcx);
492                            // Integer division: the RHS must be a non-zero const.
493                            let rhs_val = if let Operand::Constant(rhs_c) = rhs
494                                && self.should_evaluate_for_promotion_checks(rhs_c.const_)
495                                && let Some(rhs_val) =
496                                    rhs_c.const_.try_eval_scalar_int(self.tcx, self.typing_env)
497                                // for the zero test, int vs uint does not matter
498                                && rhs_val.to_uint(sz) != 0
499                            {
500                                rhs_val
501                            } else {
502                                // value not known or 0 -- not okay
503                                return Err(Unpromotable);
504                            };
505                            // Furthermore, for signed division, we also have to exclude `int::MIN /
506                            // -1`.
507                            if lhs_ty.is_signed() && rhs_val.to_int(sz) == -1 {
508                                // The RHS is -1, so we have to be careful. But is the LHS int::MIN?
509                                if let Operand::Constant(lhs_c) = lhs
510                                    && self.should_evaluate_for_promotion_checks(lhs_c.const_)
511                                    && let Some(lhs_val) =
512                                        lhs_c.const_.try_eval_scalar_int(self.tcx, self.typing_env)
513                                    && let lhs_min = sz.signed_int_min()
514                                    && lhs_val.to_int(sz) != lhs_min
515                                {
516                                    // okay
517                                } else {
518                                    // value not known or int::MIN -- not okay
519                                    return Err(Unpromotable);
520                                }
521                            }
522                        }
523                    }
524                    // The remaining operations can never fail.
525                    BinOp::Eq
526                    | BinOp::Ne
527                    | BinOp::Le
528                    | BinOp::Lt
529                    | BinOp::Ge
530                    | BinOp::Gt
531                    | BinOp::Cmp
532                    | BinOp::Offset
533                    | BinOp::Add
534                    | BinOp::AddUnchecked
535                    | BinOp::AddWithOverflow
536                    | BinOp::Sub
537                    | BinOp::SubUnchecked
538                    | BinOp::SubWithOverflow
539                    | BinOp::Mul
540                    | BinOp::MulUnchecked
541                    | BinOp::MulWithOverflow
542                    | BinOp::BitXor
543                    | BinOp::BitAnd
544                    | BinOp::BitOr
545                    | BinOp::Shl
546                    | BinOp::ShlUnchecked
547                    | BinOp::Shr
548                    | BinOp::ShrUnchecked => {}
549                }
550
551                self.validate_operand(lhs)?;
552                self.validate_operand(rhs)?;
553            }
554
555            Rvalue::RawPtr(_, place) => {
556                // We accept `&raw *`, i.e., raw reborrows -- creating a raw pointer is
557                // no problem, only using it is.
558                if let Some((place_base, ProjectionElem::Deref)) = place.as_ref().last_projection()
559                {
560                    let base_ty = place_base.ty(self.body, self.tcx).ty;
561                    if let ty::Ref(..) = base_ty.kind() {
562                        return self.validate_place(place_base);
563                    }
564                }
565                return Err(Unpromotable);
566            }
567
568            Rvalue::Ref(_, kind, place) => {
569                // Special-case reborrows to be more like a copy of the reference.
570                let mut place_simplified = place.as_ref();
571                if let Some((place_base, ProjectionElem::Deref)) =
572                    place_simplified.last_projection()
573                {
574                    let base_ty = place_base.ty(self.body, self.tcx).ty;
575                    if let ty::Ref(..) = base_ty.kind() {
576                        place_simplified = place_base;
577                    }
578                }
579
580                self.validate_place(place_simplified)?;
581
582                // Check that the reference is fine (using the original place!).
583                // (Needs to come after `validate_place` to avoid ICEs.)
584                self.validate_ref(*kind, place)?;
585            }
586
587            Rvalue::Reborrow(..) => return Err(Unpromotable),
588
589            Rvalue::Aggregate(_, operands) => {
590                for o in operands {
591                    self.validate_operand(o)?;
592                }
593            }
594        }
595
596        Ok(())
597    }
598
599    /// Computes the sets of blocks of this MIR that are definitely going to be executed
600    /// if the function returns successfully. That makes it safe to promote calls in them
601    /// that might fail.
602    fn promotion_safe_blocks(body: &mir::Body<'tcx>) -> FxHashSet<BasicBlock> {
603        let mut safe_blocks = FxHashSet::default();
604        let mut safe_block = START_BLOCK;
605        loop {
606            safe_blocks.insert(safe_block);
607            // Let's see if we can find another safe block.
608            safe_block = match body.basic_blocks[safe_block].terminator().kind {
609                TerminatorKind::Goto { target } => target,
610                TerminatorKind::Call { target: Some(target), .. }
611                | TerminatorKind::Drop { target, .. } => {
612                    // This calls a function or the destructor. `target` does not get executed if
613                    // the callee loops or panics. But in both cases the const already fails to
614                    // evaluate, so we are fine considering `target` a safe block for promotion.
615                    target
616                }
617                TerminatorKind::Assert { target, .. } => {
618                    // Similar to above, we only consider successful execution.
619                    target
620                }
621                _ => {
622                    // No next safe block.
623                    break;
624                }
625            };
626        }
627        safe_blocks
628    }
629
630    /// Returns whether the block is "safe" for promotion, which means it cannot be dead code.
631    /// We use this to avoid promoting operations that can fail in dead code.
632    fn is_promotion_safe_block(&mut self, block: BasicBlock) -> bool {
633        let body = self.body;
634        let safe_blocks =
635            self.promotion_safe_blocks.get_or_insert_with(|| Self::promotion_safe_blocks(body));
636        safe_blocks.contains(&block)
637    }
638
639    fn validate_call(
640        &mut self,
641        callee: &Operand<'tcx>,
642        args: &[Spanned<Operand<'tcx>>],
643        block: BasicBlock,
644    ) -> Result<(), Unpromotable> {
645        // Validate the operands. If they fail, there's no question -- we cannot promote.
646        self.validate_operand(callee)?;
647        for arg in args {
648            self.validate_operand(&arg.node)?;
649        }
650
651        // Functions marked `#[rustc_promotable]` are explicitly allowed to be promoted, so we can
652        // accept them at this point.
653        let fn_ty = callee.ty(self.body, self.tcx);
654        if let ty::FnDef(def_id, _) = *fn_ty.kind() {
655            if self.tcx.is_promotable_const_fn(def_id) {
656                return Ok(());
657            }
658        }
659
660        // Ideally, we'd stop here and reject the rest.
661        // But for backward compatibility, we have to accept some promotion in const/static
662        // initializers. Inline consts are explicitly excluded, they are more recent so we have no
663        // backwards compatibility reason to allow more promotion inside of them.
664        let promote_all_fn = matches!(
665            self.const_kind,
666            Some(
667                hir::ConstContext::Static(_)
668                    | hir::ConstContext::Const { allow_const_fn_promotion: true }
669            )
670        );
671        if !promote_all_fn {
672            return Err(Unpromotable);
673        }
674        // Make sure the callee is a `const fn`.
675        let is_const_fn = match *fn_ty.kind() {
676            ty::FnDef(def_id, _) => self.tcx.is_const_fn(def_id),
677            _ => false,
678        };
679        if !is_const_fn {
680            return Err(Unpromotable);
681        }
682        // The problem is, this may promote calls to functions that panic.
683        // We don't want to introduce compilation errors if there's a panic in a call in dead code.
684        // So we ensure that this is not dead code.
685        if !self.is_promotion_safe_block(block) {
686            return Err(Unpromotable);
687        }
688        // This passed all checks, so let's accept.
689        Ok(())
690    }
691
692    /// Can we try to evaluate a given constant at this point in compilation? Attempting to evaluate
693    /// a const block before borrow-checking will result in a query cycle (#150464).
694    fn should_evaluate_for_promotion_checks(&self, constant: Const<'tcx>) -> bool {
695        match constant {
696            // `Const::Ty` is always a `ConstKind::Param` right now and that can never be turned
697            // into a mir value for promotion
698            // FIXME(mgca): do we want uses of type_const to be normalized during promotion?
699            Const::Ty(..) => false,
700            Const::Val(..) => true,
701            // Evaluating a MIR constant requires borrow-checking it. For inline consts, as of
702            // #138499, this means borrow-checking its typeck root. Since borrow-checking the
703            // typeck root requires promoting its constants, trying to evaluate an inline const here
704            // will result in a query cycle. To avoid the cycle, we can't evaluate const blocks yet.
705            // Other kinds of unevaluated's can cause query cycles too when they arise from
706            // self-reference in user code; e.g. evaluating a constant can require evaluating a
707            // const function that uses that constant, again requiring evaluation of the constant.
708            // However, this form of cycle renders both the constant and function unusable in
709            // general, so we don't need to special-case it here.
710            Const::Unevaluated(uc, _) => {
711                self.tcx.def_kind(uc.def) != DefKind::AnonConst
712                    || self.tcx.anon_const_kind(uc.def) != ty::AnonConstKind::NonTypeSystemInline
713            }
714        }
715    }
716}
717
718fn validate_candidates(
719    ccx: &ConstCx<'_, '_>,
720    temps: &mut IndexSlice<Local, TempState>,
721    mut candidates: Vec<Candidate>,
722) -> Vec<Candidate> {
723    let mut validator = Validator { ccx, temps, promotion_safe_blocks: None };
724
725    candidates.retain(|&candidate| validator.validate_candidate(candidate).is_ok());
726    candidates
727}
728
729struct Promoter<'a, 'tcx> {
730    tcx: TyCtxt<'tcx>,
731    source: &'a mut Body<'tcx>,
732    promoted: Body<'tcx>,
733    temps: &'a mut IndexVec<Local, TempState>,
734    extra_statements: &'a mut Vec<(Location, Statement<'tcx>)>,
735
736    /// Used to assemble the required_consts list while building the promoted.
737    required_consts: Vec<ConstOperand<'tcx>>,
738
739    /// If true, all nested temps are also kept in the
740    /// source MIR, not moved to the promoted MIR.
741    keep_original: bool,
742
743    /// If true, add the new const (the promoted) to the required_consts of the parent MIR.
744    /// This is initially false and then set by the visitor when it encounters a `Call` terminator.
745    add_to_required: bool,
746}
747
748impl<'a, 'tcx> Promoter<'a, 'tcx> {
749    fn new_block(&mut self) -> BasicBlock {
750        let span = self.promoted.span;
751        self.promoted.basic_blocks_mut().push(BasicBlockData::new(
752            Some(Terminator {
753                source_info: SourceInfo::outermost(span),
754                kind: TerminatorKind::Return,
755                attributes: ThinVec::new(),
756            }),
757            false,
758        ))
759    }
760
761    fn assign(&mut self, dest: Local, rvalue: Rvalue<'tcx>, span: Span) {
762        let last = self.promoted.basic_blocks.last_index().unwrap();
763        let data = &mut self.promoted[last];
764        data.statements.push(Statement::new(
765            SourceInfo::outermost(span),
766            StatementKind::Assign(Box::new((Place::from(dest), rvalue))),
767        ));
768    }
769
770    fn is_temp_kind(&self, local: Local) -> bool {
771        self.source.local_kind(local) == LocalKind::Temp
772    }
773
774    /// Copies the initialization of this temp to the
775    /// promoted MIR, recursing through temps.
776    fn promote_temp(&mut self, temp: Local) -> Local {
777        let old_keep_original = self.keep_original;
778        let loc = match self.temps[temp] {
779            TempState::Defined { location, uses, .. } if uses > 0 => {
780                if uses > 1 {
781                    self.keep_original = true;
782                }
783                location
784            }
785            state => {
786                span_bug!(self.promoted.span, "{:?} not promotable: {:?}", temp, state);
787            }
788        };
789        if !self.keep_original {
790            self.temps[temp] = TempState::PromotedOut;
791        }
792
793        let num_stmts = self.source[loc.block].statements.len();
794        let new_temp = self.promoted.local_decls.push(LocalDecl::new(
795            self.source.local_decls[temp].ty,
796            self.source.local_decls[temp].source_info.span,
797        ));
798
799        debug!("promote({:?} @ {:?}/{:?}, {:?})", temp, loc, num_stmts, self.keep_original);
800
801        // First, take the Rvalue or Call out of the source MIR,
802        // or duplicate it, depending on keep_original.
803        if loc.statement_index < num_stmts {
804            let (mut rvalue, source_info) = {
805                let statement = &mut self.source[loc.block].statements[loc.statement_index];
806                let StatementKind::Assign((_, rhs)) = &mut statement.kind else {
807                    span_bug!(statement.source_info.span, "{:?} is not an assignment", statement);
808                };
809
810                (
811                    if self.keep_original {
812                        rhs.clone()
813                    } else {
814                        let unit = Rvalue::Use(
815                            Operand::Constant(Box::new(ConstOperand {
816                                span: statement.source_info.span,
817                                user_ty: None,
818                                const_: Const::zero_sized(self.tcx.types.unit),
819                            })),
820                            WithRetag::Yes,
821                        );
822                        mem::replace(rhs, unit)
823                    },
824                    statement.source_info,
825                )
826            };
827
828            self.visit_rvalue(&mut rvalue, loc);
829            self.assign(new_temp, rvalue, source_info.span);
830        } else {
831            let terminator = if self.keep_original {
832                self.source[loc.block].terminator().clone()
833            } else {
834                let terminator = self.source[loc.block].terminator_mut();
835                let target = match &terminator.kind {
836                    TerminatorKind::Call { target: Some(target), .. } => *target,
837                    kind => {
838                        span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
839                    }
840                };
841                Terminator {
842                    source_info: terminator.source_info,
843                    kind: mem::replace(&mut terminator.kind, TerminatorKind::Goto { target }),
844                    attributes: ThinVec::new(),
845                }
846            };
847
848            match terminator.kind {
849                TerminatorKind::Call {
850                    mut func, mut args, call_source: desugar, fn_span, ..
851                } => {
852                    // This promoted involves a function call, so it may fail to evaluate. Let's
853                    // make sure it is added to `required_consts` so that failure cannot get lost.
854                    self.add_to_required = true;
855
856                    self.visit_operand(&mut func, loc);
857                    for arg in &mut args {
858                        self.visit_operand(&mut arg.node, loc);
859                    }
860
861                    let last = self.promoted.basic_blocks.last_index().unwrap();
862                    let new_target = self.new_block();
863
864                    *self.promoted[last].terminator_mut() = Terminator {
865                        kind: TerminatorKind::Call {
866                            func,
867                            args,
868                            unwind: UnwindAction::Continue,
869                            destination: Place::from(new_temp),
870                            target: Some(new_target),
871                            call_source: desugar,
872                            fn_span,
873                        },
874                        source_info: SourceInfo::outermost(terminator.source_info.span),
875                        ..terminator
876                    };
877                }
878                kind => {
879                    span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
880                }
881            };
882        };
883
884        self.keep_original = old_keep_original;
885        new_temp
886    }
887
888    fn promote_candidate(
889        mut self,
890        candidate: Candidate,
891        next_promoted_index: Promoted,
892    ) -> Body<'tcx> {
893        let def = self.source.source.def_id();
894        let (mut rvalue, promoted_op) = {
895            let promoted = &mut self.promoted;
896            let tcx = self.tcx;
897            let mut promoted_operand = |ty, span| {
898                promoted.span = span;
899                promoted.local_decls[RETURN_PLACE] = LocalDecl::new(ty, span);
900                let args =
901                    tcx.erase_and_anonymize_regions(GenericArgs::identity_for_item(tcx, def));
902                let uneval =
903                    mir::UnevaluatedConst { def, args, promoted: Some(next_promoted_index) };
904
905                ConstOperand { span, user_ty: None, const_: Const::Unevaluated(uneval, ty) }
906            };
907
908            let blocks = self.source.basic_blocks.as_mut();
909            let local_decls = &mut self.source.local_decls;
910            let loc = candidate.location;
911            let statement = &mut blocks[loc.block].statements[loc.statement_index];
912            let StatementKind::Assign((_, Rvalue::Ref(region, borrow_kind, place))) =
913                &mut statement.kind
914            else {
915                bug!()
916            };
917
918            // Use the underlying local for this (necessarily interior) borrow.
919            debug_assert!(region.is_erased());
920            let ty = local_decls[place.local].ty;
921            let span = statement.source_info.span;
922
923            let ref_ty =
924                Ty::new_ref(tcx, tcx.lifetimes.re_erased, ty, borrow_kind.to_mutbl_lossy());
925
926            let mut projection = vec![PlaceElem::Deref];
927            projection.extend(place.projection);
928            place.projection = tcx.mk_place_elems(&projection);
929
930            // Create a temp to hold the promoted reference.
931            // This is because `*r` requires `r` to be a local,
932            // otherwise we would use the `promoted` directly.
933            let mut promoted_ref = LocalDecl::new(ref_ty, span);
934            promoted_ref.source_info = statement.source_info;
935            let promoted_ref = local_decls.push(promoted_ref);
936            assert_eq!(self.temps.push(TempState::Unpromotable), promoted_ref);
937
938            let promoted_operand = promoted_operand(ref_ty, span);
939            let promoted_ref_statement = Statement::new(
940                statement.source_info,
941                StatementKind::Assign(Box::new((
942                    Place::from(promoted_ref),
943                    // We can retag here because we wouldn't promote non-retagged values (they get
944                    // rejected in validate_rvalue).
945                    Rvalue::Use(Operand::Constant(Box::new(promoted_operand)), WithRetag::Yes),
946                ))),
947            );
948            self.extra_statements.push((loc, promoted_ref_statement));
949
950            (
951                Rvalue::Ref(
952                    tcx.lifetimes.re_erased,
953                    *borrow_kind,
954                    Place {
955                        local: mem::replace(&mut place.local, promoted_ref),
956                        projection: List::empty(),
957                    },
958                ),
959                promoted_operand,
960            )
961        };
962
963        assert_eq!(self.new_block(), START_BLOCK);
964        self.visit_rvalue(
965            &mut rvalue,
966            Location { block: START_BLOCK, statement_index: usize::MAX },
967        );
968
969        let span = self.promoted.span;
970        self.assign(RETURN_PLACE, rvalue, span);
971
972        // Now that we did promotion, we know whether we'll want to add this to `required_consts` of
973        // the surrounding MIR body.
974        if self.add_to_required {
975            self.source.required_consts.as_mut().unwrap().push(promoted_op);
976        }
977
978        self.promoted.set_required_consts(self.required_consts);
979
980        self.promoted
981    }
982}
983
984/// Replaces all temporaries with their promoted counterparts.
985impl<'a, 'tcx> MutVisitor<'tcx> for Promoter<'a, 'tcx> {
986    fn tcx(&self) -> TyCtxt<'tcx> {
987        self.tcx
988    }
989
990    fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
991        if self.is_temp_kind(*local) {
992            *local = self.promote_temp(*local);
993        }
994    }
995
996    fn visit_const_operand(&mut self, constant: &mut ConstOperand<'tcx>, _location: Location) {
997        if constant.const_.is_required_const() {
998            self.required_consts.push(*constant);
999        }
1000
1001        // Skipping `super_constant` as the visitor is otherwise only looking for locals.
1002    }
1003}
1004
1005fn promote_candidates<'tcx>(
1006    body: &mut Body<'tcx>,
1007    tcx: TyCtxt<'tcx>,
1008    mut temps: IndexVec<Local, TempState>,
1009    candidates: Vec<Candidate>,
1010) -> IndexVec<Promoted, Body<'tcx>> {
1011    // Visit candidates in reverse, in case they're nested.
1012    debug!(promote_candidates = ?candidates);
1013
1014    // eagerly fail fast
1015    if candidates.is_empty() {
1016        return IndexVec::new();
1017    }
1018
1019    let mut promotions = IndexVec::new();
1020
1021    let mut extra_statements = vec![];
1022    for candidate in candidates.into_iter().rev() {
1023        let Location { block, statement_index } = candidate.location;
1024        if let StatementKind::Assign((place, _)) = &body[block].statements[statement_index].kind
1025            && let Some(local) = place.as_local()
1026        {
1027            if temps[local] == TempState::PromotedOut {
1028                // Already promoted.
1029                continue;
1030            }
1031        }
1032
1033        // Declare return place local so that `mir::Body::new` doesn't complain.
1034        let initial_locals = iter::once(LocalDecl::new(tcx.types.never, body.span)).collect();
1035
1036        let mut scope = body.source_scopes[body.source_info(candidate.location).scope].clone();
1037        scope.parent_scope = None;
1038
1039        let mut promoted = Body::new(
1040            body.source, // `promoted` gets filled in below
1041            IndexVec::new(),
1042            IndexVec::from_elem_n(scope, 1),
1043            initial_locals,
1044            IndexVec::new(),
1045            0,
1046            vec![],
1047            body.span,
1048            None,
1049            body.tainted_by_errors,
1050        );
1051        promoted.phase = MirPhase::Analysis(AnalysisPhase::Initial);
1052
1053        let promoter = Promoter {
1054            promoted,
1055            tcx,
1056            source: body,
1057            temps: &mut temps,
1058            extra_statements: &mut extra_statements,
1059            keep_original: false,
1060            add_to_required: false,
1061            required_consts: Vec::new(),
1062        };
1063
1064        let mut promoted = promoter.promote_candidate(candidate, promotions.next_index());
1065        promoted.source.promoted = Some(promotions.next_index());
1066        promotions.push(promoted);
1067    }
1068
1069    // Insert each of `extra_statements` before its indicated location, which
1070    // has to be done in reverse location order, to not invalidate the rest.
1071    extra_statements.sort_by_key(|&(loc, _)| cmp::Reverse(loc));
1072    for (loc, statement) in extra_statements {
1073        body[loc.block].statements.insert(loc.statement_index, statement);
1074    }
1075
1076    // Eliminate assignments to, and drops of promoted temps.
1077    let promoted = |index: Local| temps[index] == TempState::PromotedOut;
1078    for block in body.basic_blocks_mut() {
1079        block.retain_statements(|statement| match &statement.kind {
1080            StatementKind::Assign((place, _)) => {
1081                if let Some(index) = place.as_local() {
1082                    !promoted(index)
1083                } else {
1084                    true
1085                }
1086            }
1087            StatementKind::StorageLive(index) | StatementKind::StorageDead(index) => {
1088                !promoted(*index)
1089            }
1090            _ => true,
1091        });
1092        let terminator = block.terminator_mut();
1093        if let TerminatorKind::Drop { place, target, .. } = &terminator.kind
1094            && let Some(index) = place.as_local()
1095        {
1096            if promoted(index) {
1097                terminator.kind = TerminatorKind::Goto { target: *target };
1098            }
1099        }
1100    }
1101
1102    promotions
1103}