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