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