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