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