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