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, _ctx: &crate::PassCtx<'_>) -> 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::PhantomDeref
303            | ProjectionElem::OpaqueCast(..)
304            | ProjectionElem::Downcast(..) => {
305                return Err(Unpromotable);
306            }
307
308            ProjectionElem::Deref => {
309                // When a static is used by-value, that gets desugared to `*STATIC_ADDR`,
310                // and we need to be able to promote this. So check if this deref matches
311                // that specific pattern.
312
313                // We need to make sure this is a `Deref` of a local with no further projections.
314                // Discussion can be found at
315                // https://github.com/rust-lang/rust/pull/74945#discussion_r463063247
316                if let Some(local) = place_base.as_local()
317                    && let TempState::Defined { location, .. } = self.temps[local]
318                    && let Left(def_stmt) = self.body.stmt_at(location)
319                    && let Some((_, Rvalue::Use(Operand::Constant(c), _))) = def_stmt.kind.as_assign()
320                    && let Some(did) = c.check_static_ptr(self.tcx)
321                    // Evaluating a promoted may not read statics except if it got
322                    // promoted from a static (this is a CTFE check). So we
323                    // can only promote static accesses inside statics.
324                    && let Some(hir::ConstContext::Static(..)) = self.const_kind
325                    && !self.tcx.is_thread_local_static(did)
326                    // Extern statics can never be read by CTFE, even inside a static.
327                    && !self.tcx.is_foreign_item(did)
328                {
329                    // Recurse.
330                } else {
331                    return Err(Unpromotable);
332                }
333            }
334            ProjectionElem::Index(local) => {
335                // Only accept if we can predict the index and are indexing an array.
336                if let TempState::Defined { location: loc, .. } = self.temps[local]
337                    && let Left(statement) =  self.body.stmt_at(loc)
338                    && let Some((_, Rvalue::Use(Operand::Constant(c), _))) = statement.kind.as_assign()
339                    && self.should_evaluate_for_promotion_checks(c.const_)
340                    && let Some(idx) = c.const_.try_eval_target_usize(self.tcx, self.typing_env)
341                    // Determine the type of the thing we are indexing.
342                    && let ty::Array(_, len) = place_base.ty(self.body, self.tcx).ty.kind()
343                    // It's an array; determine its length.
344                    && let Some(len) = len.try_to_target_usize(self.tcx)
345                    // If the index is in-bounds, go ahead.
346                    && idx < len
347                {
348                    self.validate_local(local)?;
349                    // Recurse.
350                } else {
351                    return Err(Unpromotable);
352                }
353            }
354
355            ProjectionElem::Field(..) => {
356                let base_ty = place_base.ty(self.body, self.tcx).ty;
357                if base_ty.is_union() {
358                    // No promotion of union field accesses.
359                    return Err(Unpromotable);
360                }
361            }
362        }
363
364        self.validate_place(place_base)
365    }
366
367    fn validate_operand(&mut self, operand: &Operand<'tcx>) -> Result<(), Unpromotable> {
368        match operand {
369            Operand::Copy(place) | Operand::Move(place) => self.validate_place(place.as_ref()),
370
371            // `RuntimeChecks` behaves different in const-eval and runtime MIR,
372            // so we do not promote it.
373            Operand::RuntimeChecks(_) => Err(Unpromotable),
374
375            // The qualifs for a constant (e.g. `HasMutInterior`) are checked in
376            // `validate_rvalue` upon access.
377            Operand::Constant(c) => {
378                if let Some(def_id) = c.check_static_ptr(self.tcx) {
379                    // Only allow statics (not consts) to refer to other statics.
380                    // FIXME(eddyb) does this matter at all for promotion?
381                    // FIXME(RalfJung) it makes little sense to not promote this in `fn`/`const fn`,
382                    // and in `const` this cannot occur anyway. The only concern is that we might
383                    // promote even `let x = &STATIC` which would be useless, but this applies to
384                    // promotion inside statics as well.
385                    let is_static = matches!(self.const_kind, Some(hir::ConstContext::Static(_)));
386                    if !is_static {
387                        return Err(Unpromotable);
388                    }
389
390                    let is_thread_local = self.tcx.is_thread_local_static(def_id);
391                    if is_thread_local {
392                        return Err(Unpromotable);
393                    }
394                }
395
396                Ok(())
397            }
398        }
399    }
400
401    fn validate_ref(&mut self, kind: BorrowKind, place: &Place<'tcx>) -> Result<(), Unpromotable> {
402        match kind {
403            // Reject these borrow types just to be safe.
404            // FIXME(RalfJung): could we allow them? Should we? No point in it until we have a
405            // usecase.
406            BorrowKind::Fake(_) | BorrowKind::Mut { kind: MutBorrowKind::ClosureCapture } => {
407                return Err(Unpromotable);
408            }
409
410            BorrowKind::Shared => {
411                let has_mut_interior = self.qualif_local::<qualifs::HasMutInterior>(place.local);
412                if has_mut_interior {
413                    return Err(Unpromotable);
414                }
415            }
416
417            // FIXME: consider changing this to only promote &mut [] for default borrows,
418            // also forbidding two phase borrows
419            BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::TwoPhaseBorrow } => {
420                let ty = place.ty(self.body, self.tcx).ty;
421
422                // In theory, any zero-sized value could be borrowed
423                // mutably without consequences. However, only &mut []
424                // is allowed right now.
425                let ty::Array(_, len) = ty.kind() else { return Err(Unpromotable) };
426                let Some(0) = len.try_to_target_usize(self.tcx) else { return Err(Unpromotable) };
427            }
428        }
429
430        Ok(())
431    }
432
433    fn validate_rvalue(&mut self, rvalue: &Rvalue<'tcx>) -> Result<(), Unpromotable> {
434        match rvalue {
435            Rvalue::Use(_operand, WithRetag::No) => {
436                // This shouldn't actually happen, but just to be safe: we'll later add the promoted
437                // with retagging, so don't promote anything that didn't already have retagging.
438                return Err(Unpromotable);
439            }
440            Rvalue::Use(operand, _)
441            | Rvalue::Repeat(operand, _)
442            | Rvalue::WrapUnsafeBinder(operand, _) => {
443                self.validate_operand(operand)?;
444            }
445            Rvalue::CopyForDeref(place) => {
446                let op = &Operand::Copy(*place);
447                self.validate_operand(op)?
448            }
449
450            Rvalue::Discriminant(place) => self.validate_place(place.as_ref())?,
451
452            Rvalue::ThreadLocalRef(_) => return Err(Unpromotable),
453
454            // ptr-to-int casts are not possible in consts and thus not promotable
455            Rvalue::Cast(CastKind::PointerExposeProvenance, _, _) => return Err(Unpromotable),
456
457            // all other casts including int-to-ptr casts are fine, they just use the integer value
458            // at pointer type.
459            Rvalue::Cast(_, operand, _) => {
460                self.validate_operand(operand)?;
461            }
462
463            Rvalue::UnaryOp(op, operand) => {
464                match op {
465                    // These operations can never fail.
466                    UnOp::Neg | UnOp::Not | UnOp::PtrMetadata => {}
467                }
468
469                self.validate_operand(operand)?;
470            }
471
472            Rvalue::BinaryOp(op, (lhs, rhs)) => {
473                let op = *op;
474                let lhs_ty = lhs.ty(self.body, self.tcx);
475
476                if let ty::RawPtr(_, _) | ty::FnPtr(..) = lhs_ty.kind() {
477                    // Raw and fn pointer operations are not allowed inside consts and thus not
478                    // promotable.
479                    assert_matches!(
480                        op,
481                        BinOp::Eq
482                            | BinOp::Ne
483                            | BinOp::Le
484                            | BinOp::Lt
485                            | BinOp::Ge
486                            | BinOp::Gt
487                            | BinOp::Offset
488                    );
489                    return Err(Unpromotable);
490                }
491
492                match op {
493                    BinOp::Div | BinOp::Rem => {
494                        if lhs_ty.is_integral() {
495                            let sz = lhs_ty.primitive_size(self.tcx);
496                            // Integer division: the RHS must be a non-zero const.
497                            let rhs_val = if let Operand::Constant(rhs_c) = rhs
498                                && self.should_evaluate_for_promotion_checks(rhs_c.const_)
499                                && let Some(rhs_val) =
500                                    rhs_c.const_.try_eval_scalar_int(self.tcx, self.typing_env)
501                                // for the zero test, int vs uint does not matter
502                                && rhs_val.to_uint(sz) != 0
503                            {
504                                rhs_val
505                            } else {
506                                // value not known or 0 -- not okay
507                                return Err(Unpromotable);
508                            };
509                            // Furthermore, for signed division, we also have to exclude `int::MIN /
510                            // -1`.
511                            if lhs_ty.is_signed() && rhs_val.to_int(sz) == -1 {
512                                // The RHS is -1, so we have to be careful. But is the LHS int::MIN?
513                                if let Operand::Constant(lhs_c) = lhs
514                                    && self.should_evaluate_for_promotion_checks(lhs_c.const_)
515                                    && let Some(lhs_val) =
516                                        lhs_c.const_.try_eval_scalar_int(self.tcx, self.typing_env)
517                                    && let lhs_min = sz.signed_int_min()
518                                    && lhs_val.to_int(sz) != lhs_min
519                                {
520                                    // okay
521                                } else {
522                                    // value not known or int::MIN -- not okay
523                                    return Err(Unpromotable);
524                                }
525                            }
526                        }
527                    }
528                    // The remaining operations can never fail.
529                    BinOp::Eq
530                    | BinOp::Ne
531                    | BinOp::Le
532                    | BinOp::Lt
533                    | BinOp::Ge
534                    | BinOp::Gt
535                    | BinOp::Cmp
536                    | BinOp::Offset
537                    | BinOp::Add
538                    | BinOp::AddUnchecked
539                    | BinOp::AddWithOverflow
540                    | BinOp::Sub
541                    | BinOp::SubUnchecked
542                    | BinOp::SubWithOverflow
543                    | BinOp::Mul
544                    | BinOp::MulUnchecked
545                    | BinOp::MulWithOverflow
546                    | BinOp::BitXor
547                    | BinOp::BitAnd
548                    | BinOp::BitOr
549                    | BinOp::Shl
550                    | BinOp::ShlUnchecked
551                    | BinOp::Shr
552                    | BinOp::ShrUnchecked => {}
553                }
554
555                self.validate_operand(lhs)?;
556                self.validate_operand(rhs)?;
557            }
558
559            Rvalue::RawPtr(_, place) => {
560                // We accept `&raw *`, i.e., raw reborrows -- creating a raw pointer is
561                // no problem, only using it is.
562                if let Some((place_base, ProjectionElem::Deref)) = place.as_ref().last_projection()
563                {
564                    let base_ty = place_base.ty(self.body, self.tcx).ty;
565                    if let ty::Ref(..) = base_ty.kind() {
566                        return self.validate_place(place_base);
567                    }
568                }
569                return Err(Unpromotable);
570            }
571
572            Rvalue::Ref(_, kind, place) => {
573                // Special-case reborrows to be more like a copy of the reference.
574                let mut place_simplified = place.as_ref();
575                if let Some((place_base, ProjectionElem::Deref)) =
576                    place_simplified.last_projection()
577                {
578                    let base_ty = place_base.ty(self.body, self.tcx).ty;
579                    if let ty::Ref(..) = base_ty.kind() {
580                        place_simplified = place_base;
581                    }
582                }
583
584                self.validate_place(place_simplified)?;
585
586                // Check that the reference is fine (using the original place!).
587                // (Needs to come after `validate_place` to avoid ICEs.)
588                self.validate_ref(*kind, place)?;
589            }
590
591            Rvalue::Reborrow(..) => return Err(Unpromotable),
592
593            Rvalue::Aggregate(_, operands) => {
594                for o in operands {
595                    self.validate_operand(o)?;
596                }
597            }
598        }
599
600        Ok(())
601    }
602
603    /// Computes the sets of blocks of this MIR that are definitely going to be executed
604    /// if the function returns successfully. That makes it safe to promote calls in them
605    /// that might fail.
606    fn promotion_safe_blocks(body: &mir::Body<'tcx>) -> FxHashSet<BasicBlock> {
607        let mut safe_blocks = FxHashSet::default();
608        let mut safe_block = START_BLOCK;
609        loop {
610            safe_blocks.insert(safe_block);
611            // Let's see if we can find another safe block.
612            safe_block = match body.basic_blocks[safe_block].terminator().kind {
613                TerminatorKind::Goto { target } => target,
614                TerminatorKind::Call { target: Some(target), .. }
615                | TerminatorKind::Drop { target, .. } => {
616                    // This calls a function or the destructor. `target` does not get executed if
617                    // the callee loops or panics. But in both cases the const already fails to
618                    // evaluate, so we are fine considering `target` a safe block for promotion.
619                    target
620                }
621                TerminatorKind::Assert { target, .. } => {
622                    // Similar to above, we only consider successful execution.
623                    target
624                }
625                _ => {
626                    // No next safe block.
627                    break;
628                }
629            };
630        }
631        safe_blocks
632    }
633
634    /// Returns whether the block is "safe" for promotion, which means it cannot be dead code.
635    /// We use this to avoid promoting operations that can fail in dead code.
636    fn is_promotion_safe_block(&mut self, block: BasicBlock) -> bool {
637        let body = self.body;
638        let safe_blocks =
639            self.promotion_safe_blocks.get_or_insert_with(|| Self::promotion_safe_blocks(body));
640        safe_blocks.contains(&block)
641    }
642
643    fn validate_call(
644        &mut self,
645        callee: &Operand<'tcx>,
646        args: &[Spanned<Operand<'tcx>>],
647        block: BasicBlock,
648    ) -> Result<(), Unpromotable> {
649        // Validate the operands. If they fail, there's no question -- we cannot promote.
650        self.validate_operand(callee)?;
651        for arg in args {
652            self.validate_operand(&arg.node)?;
653        }
654
655        // Functions marked `#[rustc_promotable]` are explicitly allowed to be promoted, so we can
656        // accept them at this point.
657        let fn_ty = callee.ty(self.body, self.tcx);
658        if let ty::FnDef(def_id, _) = *fn_ty.kind() {
659            if self.tcx.is_promotable_const_fn(def_id) {
660                return Ok(());
661            }
662        }
663
664        // Ideally, we'd stop here and reject the rest.
665        // But for backward compatibility, we have to accept some promotion in const/static
666        // initializers. Inline consts are explicitly excluded, they are more recent so we have no
667        // backwards compatibility reason to allow more promotion inside of them.
668        let promote_all_fn = matches!(
669            self.const_kind,
670            Some(
671                hir::ConstContext::Static(_)
672                    | hir::ConstContext::Const { allow_const_fn_promotion: true }
673            )
674        );
675        if !promote_all_fn {
676            return Err(Unpromotable);
677        }
678        // Make sure the callee is a `const fn`.
679        let is_const_fn = match *fn_ty.kind() {
680            ty::FnDef(def_id, _) => self.tcx.is_const_fn(def_id),
681            _ => false,
682        };
683        if !is_const_fn {
684            return Err(Unpromotable);
685        }
686        // The problem is, this may promote calls to functions that panic.
687        // We don't want to introduce compilation errors if there's a panic in a call in dead code.
688        // So we ensure that this is not dead code.
689        if !self.is_promotion_safe_block(block) {
690            return Err(Unpromotable);
691        }
692        // This passed all checks, so let's accept.
693        Ok(())
694    }
695
696    /// Can we try to evaluate a given constant at this point in compilation? Attempting to evaluate
697    /// a const block before borrow-checking will result in a query cycle (#150464).
698    fn should_evaluate_for_promotion_checks(&self, constant: Const<'tcx>) -> bool {
699        match constant {
700            // `Const::Ty` is always a `ConstKind::Param` right now and that can never be turned
701            // into a mir value for promotion
702            // FIXME(mgca): do we want uses of type_const to be normalized during promotion?
703            Const::Ty(..) => false,
704            Const::Val(..) => true,
705            // Evaluating a MIR constant requires borrow-checking it. For inline consts, as of
706            // #138499, this means borrow-checking its typeck root. Since borrow-checking the
707            // typeck root requires promoting its constants, trying to evaluate an inline const here
708            // will result in a query cycle. To avoid the cycle, we can't evaluate const blocks yet.
709            // Other kinds of unevaluated's can cause query cycles too when they arise from
710            // self-reference in user code; e.g. evaluating a constant can require evaluating a
711            // const function that uses that constant, again requiring evaluation of the constant.
712            // However, this form of cycle renders both the constant and function unusable in
713            // general, so we don't need to special-case it here.
714            Const::Unevaluated(uc, _) => {
715                self.tcx.def_kind(uc.def) != DefKind::AnonConst
716                    || self.tcx.anon_const_kind(uc.def) != ty::AnonConstKind::NonTypeSystemInline
717            }
718        }
719    }
720}
721
722fn validate_candidates(
723    ccx: &ConstCx<'_, '_>,
724    temps: &mut IndexSlice<Local, TempState>,
725    mut candidates: Vec<Candidate>,
726) -> Vec<Candidate> {
727    let mut validator = Validator { ccx, temps, promotion_safe_blocks: None };
728
729    candidates.retain(|&candidate| validator.validate_candidate(candidate).is_ok());
730    candidates
731}
732
733struct Promoter<'a, 'tcx> {
734    tcx: TyCtxt<'tcx>,
735    source: &'a mut Body<'tcx>,
736    promoted: Body<'tcx>,
737    temps: &'a mut IndexVec<Local, TempState>,
738    extra_statements: &'a mut Vec<(Location, Statement<'tcx>)>,
739
740    /// Used to assemble the required_consts list while building the promoted.
741    required_consts: Vec<ConstOperand<'tcx>>,
742
743    /// If true, all nested temps are also kept in the
744    /// source MIR, not moved to the promoted MIR.
745    keep_original: bool,
746
747    /// If true, add the new const (the promoted) to the required_consts of the parent MIR.
748    /// This is initially false and then set by the visitor when it encounters a `Call` terminator.
749    add_to_required: bool,
750}
751
752impl<'a, 'tcx> Promoter<'a, 'tcx> {
753    fn new_block(&mut self) -> BasicBlock {
754        let span = self.promoted.span;
755        self.promoted.basic_blocks_mut().push(BasicBlockData::new(
756            Some(Terminator {
757                source_info: SourceInfo::outermost(span),
758                kind: TerminatorKind::Return,
759                attributes: ThinVec::new(),
760            }),
761            false,
762        ))
763    }
764
765    fn assign(&mut self, dest: Local, rvalue: Rvalue<'tcx>, span: Span) {
766        let last = self.promoted.basic_blocks.last_index().unwrap();
767        let data = &mut self.promoted[last];
768        data.statements.push(Statement::new(
769            SourceInfo::outermost(span),
770            StatementKind::Assign(Box::new((Place::from(dest), rvalue))),
771        ));
772    }
773
774    fn is_temp_kind(&self, local: Local) -> bool {
775        self.source.local_kind(local) == LocalKind::Temp
776    }
777
778    /// Copies the initialization of this temp to the
779    /// promoted MIR, recursing through temps.
780    fn promote_temp(&mut self, temp: Local) -> Local {
781        let old_keep_original = self.keep_original;
782        let loc = match self.temps[temp] {
783            TempState::Defined { location, uses, .. } if uses > 0 => {
784                if uses > 1 {
785                    self.keep_original = true;
786                }
787                location
788            }
789            state => {
790                span_bug!(self.promoted.span, "{:?} not promotable: {:?}", temp, state);
791            }
792        };
793        if !self.keep_original {
794            self.temps[temp] = TempState::PromotedOut;
795        }
796
797        let num_stmts = self.source[loc.block].statements.len();
798        let new_temp = self.promoted.local_decls.push(LocalDecl::new(
799            self.source.local_decls[temp].ty,
800            self.source.local_decls[temp].source_info.span,
801        ));
802
803        debug!("promote({:?} @ {:?}/{:?}, {:?})", temp, loc, num_stmts, self.keep_original);
804
805        // First, take the Rvalue or Call out of the source MIR,
806        // or duplicate it, depending on keep_original.
807        if loc.statement_index < num_stmts {
808            let (mut rvalue, source_info) = {
809                let statement = &mut self.source[loc.block].statements[loc.statement_index];
810                let StatementKind::Assign((_, rhs)) = &mut statement.kind else {
811                    span_bug!(statement.source_info.span, "{:?} is not an assignment", statement);
812                };
813
814                (
815                    if self.keep_original {
816                        rhs.clone()
817                    } else {
818                        let unit = Rvalue::Use(
819                            Operand::Constant(Box::new(ConstOperand {
820                                span: statement.source_info.span,
821                                user_ty: None,
822                                const_: Const::zero_sized(self.tcx.types.unit),
823                            })),
824                            WithRetag::Yes,
825                        );
826                        mem::replace(rhs, unit)
827                    },
828                    statement.source_info,
829                )
830            };
831
832            self.visit_rvalue(&mut rvalue, loc);
833            self.assign(new_temp, rvalue, source_info.span);
834        } else {
835            let terminator = if self.keep_original {
836                self.source[loc.block].terminator().clone()
837            } else {
838                let terminator = self.source[loc.block].terminator_mut();
839                let target = match &terminator.kind {
840                    TerminatorKind::Call { target: Some(target), .. } => *target,
841                    kind => {
842                        span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
843                    }
844                };
845                Terminator {
846                    source_info: terminator.source_info,
847                    kind: mem::replace(&mut terminator.kind, TerminatorKind::Goto { target }),
848                    attributes: ThinVec::new(),
849                }
850            };
851
852            match terminator.kind {
853                TerminatorKind::Call {
854                    mut func, mut args, call_source: desugar, fn_span, ..
855                } => {
856                    // This promoted involves a function call, so it may fail to evaluate. Let's
857                    // make sure it is added to `required_consts` so that failure cannot get lost.
858                    self.add_to_required = true;
859
860                    self.visit_operand(&mut func, loc);
861                    for arg in &mut args {
862                        self.visit_operand(&mut arg.node, loc);
863                    }
864
865                    let last = self.promoted.basic_blocks.last_index().unwrap();
866                    let new_target = self.new_block();
867
868                    *self.promoted[last].terminator_mut() = Terminator {
869                        kind: TerminatorKind::Call {
870                            func,
871                            args,
872                            unwind: UnwindAction::Continue,
873                            destination: Place::from(new_temp),
874                            target: Some(new_target),
875                            call_source: desugar,
876                            fn_span,
877                        },
878                        source_info: SourceInfo::outermost(terminator.source_info.span),
879                        ..terminator
880                    };
881                }
882                kind => {
883                    span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
884                }
885            };
886        };
887
888        self.keep_original = old_keep_original;
889        new_temp
890    }
891
892    fn promote_candidate(
893        mut self,
894        candidate: Candidate,
895        next_promoted_index: Promoted,
896    ) -> Body<'tcx> {
897        let def = self.source.source.def_id();
898        let (mut rvalue, promoted_op) = {
899            let promoted = &mut self.promoted;
900            let tcx = self.tcx;
901            let mut promoted_operand = |ty, span| {
902                promoted.span = span;
903                promoted.local_decls[RETURN_PLACE] = LocalDecl::new(ty, span);
904                let args =
905                    tcx.erase_and_anonymize_regions(GenericArgs::identity_for_item(tcx, def));
906                let uneval =
907                    mir::UnevaluatedConst { def, args, promoted: Some(next_promoted_index) };
908
909                ConstOperand { span, user_ty: None, const_: Const::Unevaluated(uneval, ty) }
910            };
911
912            let blocks = self.source.basic_blocks.as_mut();
913            let local_decls = &mut self.source.local_decls;
914            let loc = candidate.location;
915            let statement = &mut blocks[loc.block].statements[loc.statement_index];
916            let StatementKind::Assign((_, Rvalue::Ref(region, borrow_kind, place))) =
917                &mut statement.kind
918            else {
919                bug!()
920            };
921
922            // Use the underlying local for this (necessarily interior) borrow.
923            debug_assert!(region.is_erased());
924            let ty = local_decls[place.local].ty;
925            let span = statement.source_info.span;
926
927            let ref_ty =
928                Ty::new_ref(tcx, tcx.lifetimes.re_erased, ty, borrow_kind.to_mutbl_lossy());
929
930            let mut projection = vec![PlaceElem::Deref];
931            projection.extend(place.projection);
932            place.projection = tcx.mk_place_elems(&projection);
933
934            // Create a temp to hold the promoted reference.
935            // This is because `*r` requires `r` to be a local,
936            // otherwise we would use the `promoted` directly.
937            let mut promoted_ref = LocalDecl::new(ref_ty, span);
938            promoted_ref.source_info = statement.source_info;
939            let promoted_ref = local_decls.push(promoted_ref);
940            assert_eq!(self.temps.push(TempState::Unpromotable), promoted_ref);
941
942            let promoted_operand = promoted_operand(ref_ty, span);
943            let promoted_ref_statement = Statement::new(
944                statement.source_info,
945                StatementKind::Assign(Box::new((
946                    Place::from(promoted_ref),
947                    // We can retag here because we wouldn't promote non-retagged values (they get
948                    // rejected in validate_rvalue).
949                    Rvalue::Use(Operand::Constant(Box::new(promoted_operand)), WithRetag::Yes),
950                ))),
951            );
952            self.extra_statements.push((loc, promoted_ref_statement));
953
954            (
955                Rvalue::Ref(
956                    tcx.lifetimes.re_erased,
957                    *borrow_kind,
958                    Place {
959                        local: mem::replace(&mut place.local, promoted_ref),
960                        projection: List::empty(),
961                    },
962                ),
963                promoted_operand,
964            )
965        };
966
967        assert_eq!(self.new_block(), START_BLOCK);
968        self.visit_rvalue(
969            &mut rvalue,
970            Location { block: START_BLOCK, statement_index: usize::MAX },
971        );
972
973        let span = self.promoted.span;
974        self.assign(RETURN_PLACE, rvalue, span);
975
976        // Now that we did promotion, we know whether we'll want to add this to `required_consts` of
977        // the surrounding MIR body.
978        if self.add_to_required {
979            self.source.required_consts.as_mut().unwrap().push(promoted_op);
980        }
981
982        self.promoted.set_required_consts(self.required_consts);
983
984        self.promoted
985    }
986}
987
988/// Replaces all temporaries with their promoted counterparts.
989impl<'a, 'tcx> MutVisitor<'tcx> for Promoter<'a, 'tcx> {
990    fn tcx(&self) -> TyCtxt<'tcx> {
991        self.tcx
992    }
993
994    fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
995        if self.is_temp_kind(*local) {
996            *local = self.promote_temp(*local);
997        }
998    }
999
1000    fn visit_const_operand(&mut self, constant: &mut ConstOperand<'tcx>, _location: Location) {
1001        if constant.const_.is_required_const() {
1002            self.required_consts.push(*constant);
1003        }
1004
1005        // Skipping `super_constant` as the visitor is otherwise only looking for locals.
1006    }
1007}
1008
1009fn promote_candidates<'tcx>(
1010    body: &mut Body<'tcx>,
1011    tcx: TyCtxt<'tcx>,
1012    mut temps: IndexVec<Local, TempState>,
1013    candidates: Vec<Candidate>,
1014) -> IndexVec<Promoted, Body<'tcx>> {
1015    // Visit candidates in reverse, in case they're nested.
1016    debug!(promote_candidates = ?candidates);
1017
1018    // eagerly fail fast
1019    if candidates.is_empty() {
1020        return IndexVec::new();
1021    }
1022
1023    let mut promotions = IndexVec::new();
1024
1025    let mut extra_statements = vec![];
1026    for candidate in candidates.into_iter().rev() {
1027        let Location { block, statement_index } = candidate.location;
1028        if let StatementKind::Assign((place, _)) = &body[block].statements[statement_index].kind
1029            && let Some(local) = place.as_local()
1030        {
1031            if temps[local] == TempState::PromotedOut {
1032                // Already promoted.
1033                continue;
1034            }
1035        }
1036
1037        // Declare return place local so that `mir::Body::new` doesn't complain.
1038        let initial_locals = iter::once(LocalDecl::new(tcx.types.never, body.span)).collect();
1039
1040        let mut scope = body.source_scopes[body.source_info(candidate.location).scope].clone();
1041        scope.parent_scope = None;
1042
1043        let mut promoted = Body::new(
1044            body.source, // `promoted` gets filled in below
1045            IndexVec::new(),
1046            IndexVec::from_elem_n(scope, 1),
1047            initial_locals,
1048            IndexVec::new(),
1049            0,
1050            vec![],
1051            body.span,
1052            None,
1053            body.tainted_by_errors,
1054        );
1055        promoted.phase = MirPhase::Analysis(AnalysisPhase::Initial);
1056
1057        let promoter = Promoter {
1058            promoted,
1059            tcx,
1060            source: body,
1061            temps: &mut temps,
1062            extra_statements: &mut extra_statements,
1063            keep_original: false,
1064            add_to_required: false,
1065            required_consts: Vec::new(),
1066        };
1067
1068        let mut promoted = promoter.promote_candidate(candidate, promotions.next_index());
1069        promoted.source.promoted = Some(promotions.next_index());
1070        promotions.push(promoted);
1071    }
1072
1073    // Insert each of `extra_statements` before its indicated location, which
1074    // has to be done in reverse location order, to not invalidate the rest.
1075    extra_statements.sort_by_key(|&(loc, _)| cmp::Reverse(loc));
1076    for (loc, statement) in extra_statements {
1077        body[loc.block].statements.insert(loc.statement_index, statement);
1078    }
1079
1080    // Eliminate assignments to, and drops of promoted temps.
1081    let promoted = |index: Local| temps[index] == TempState::PromotedOut;
1082    for block in body.basic_blocks_mut() {
1083        block.retain_statements(|statement| match &statement.kind {
1084            StatementKind::Assign((place, _)) => {
1085                if let Some(index) = place.as_local() {
1086                    !promoted(index)
1087                } else {
1088                    true
1089                }
1090            }
1091            StatementKind::StorageLive(index) | StatementKind::StorageDead(index) => {
1092                !promoted(*index)
1093            }
1094            _ => true,
1095        });
1096        let terminator = block.terminator_mut();
1097        if let TerminatorKind::Drop { place, target, .. } = &terminator.kind
1098            && let Some(index) = place.as_local()
1099        {
1100            if promoted(index) {
1101                terminator.kind = TerminatorKind::Goto { target: *target };
1102            }
1103        }
1104    }
1105
1106    promotions
1107}