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