]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/promote_consts.rs
Remove Static from PlaceBase
[rust.git] / src / librustc_mir / 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::mir::traversal::ReversePostorder;
16 use rustc::mir::visit::{MutVisitor, MutatingUseContext, PlaceContext, Visitor};
17 use rustc::mir::*;
18 use rustc::ty::cast::CastTy;
19 use rustc::ty::subst::InternalSubsts;
20 use rustc::ty::{self, List, TyCtxt, TypeFoldable};
21 use rustc_hir::def_id::DefId;
22 use rustc_span::symbol::sym;
23 use rustc_span::{Span, DUMMY_SP};
24 use syntax::ast::LitKind;
25
26 use rustc_index::vec::{Idx, IndexVec};
27 use rustc_target::spec::abi::Abi;
28
29 use std::cell::Cell;
30 use std::{cmp, iter, mem, usize};
31
32 use crate::const_eval::{is_const_fn, is_unstable_const_fn};
33 use crate::transform::check_consts::{is_lang_panic_fn, qualifs, ConstKind, Item};
34 use crate::transform::{MirPass, MirSource};
35
36 /// A `MirPass` for promotion.
37 ///
38 /// Promotion is the extraction of promotable temps into separate MIR bodies. This pass also emits
39 /// errors when promotion of `#[rustc_args_required_const]` arguments fails.
40 ///
41 /// After this pass is run, `promoted_fragments` will hold the MIR body corresponding to each
42 /// newly created `Constant`.
43 #[derive(Default)]
44 pub struct PromoteTemps<'tcx> {
45     pub promoted_fragments: Cell<IndexVec<Promoted, BodyAndCache<'tcx>>>,
46 }
47
48 impl<'tcx> MirPass<'tcx> for PromoteTemps<'tcx> {
49     fn run_pass(&self, tcx: TyCtxt<'tcx>, src: MirSource<'tcx>, body: &mut BodyAndCache<'tcx>) {
50         // There's not really any point in promoting errorful MIR.
51         //
52         // This does not include MIR that failed const-checking, which we still try to promote.
53         if body.return_ty().references_error() {
54             tcx.sess.delay_span_bug(body.span, "PromoteTemps: MIR had errors");
55             return;
56         }
57
58         if src.promoted.is_some() {
59             return;
60         }
61
62         let def_id = src.def_id();
63
64         let mut rpo = traversal::reverse_postorder(body);
65         let (temps, all_candidates) = collect_temps_and_candidates(tcx, body, &mut rpo);
66
67         let promotable_candidates =
68             validate_candidates(tcx, read_only!(body), def_id, &temps, &all_candidates);
69
70         let promoted = promote_candidates(def_id, body, tcx, temps, promotable_candidates);
71         self.promoted_fragments.set(promoted);
72     }
73 }
74
75 /// State of a temporary during collection and promotion.
76 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
77 pub enum TempState {
78     /// No references to this temp.
79     Undefined,
80     /// One direct assignment and any number of direct uses.
81     /// A borrow of this temp is promotable if the assigned
82     /// value is qualified as constant.
83     Defined { location: Location, uses: usize },
84     /// Any other combination of assignments/uses.
85     Unpromotable,
86     /// This temp was part of an rvalue which got extracted
87     /// during promotion and needs cleanup.
88     PromotedOut,
89 }
90
91 impl TempState {
92     pub fn is_promotable(&self) -> bool {
93         debug!("is_promotable: self={:?}", self);
94         if let TempState::Defined { .. } = *self { true } else { false }
95     }
96 }
97
98 /// A "root candidate" for promotion, which will become the
99 /// returned value in a promoted MIR, unless it's a subset
100 /// of a larger candidate.
101 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
102 pub enum Candidate {
103     /// Borrow of a constant temporary.
104     Ref(Location),
105
106     /// Promotion of the `x` in `[x; 32]`.
107     Repeat(Location),
108
109     /// Currently applied to function calls where the callee has the unstable
110     /// `#[rustc_args_required_const]` attribute as well as the SIMD shuffle
111     /// intrinsic. The intrinsic requires the arguments are indeed constant and
112     /// the attribute currently provides the semantic requirement that arguments
113     /// must be constant.
114     Argument { bb: BasicBlock, index: usize },
115 }
116
117 impl Candidate {
118     /// Returns `true` if we should use the "explicit" rules for promotability for this `Candidate`.
119     fn forces_explicit_promotion(&self) -> bool {
120         match self {
121             Candidate::Ref(_) | Candidate::Repeat(_) => false,
122             Candidate::Argument { .. } => true,
123         }
124     }
125 }
126
127 fn args_required_const(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Vec<usize>> {
128     let attrs = tcx.get_attrs(def_id);
129     let attr = attrs.iter().find(|a| a.check_name(sym::rustc_args_required_const))?;
130     let mut ret = vec![];
131     for meta in attr.meta_item_list()? {
132         match meta.literal()?.kind {
133             LitKind::Int(a, _) => {
134                 ret.push(a as usize);
135             }
136             _ => return None,
137         }
138     }
139     Some(ret)
140 }
141
142 struct Collector<'a, 'tcx> {
143     tcx: TyCtxt<'tcx>,
144     body: &'a Body<'tcx>,
145     temps: IndexVec<Local, TempState>,
146     candidates: Vec<Candidate>,
147     span: Span,
148 }
149
150 impl<'tcx> Visitor<'tcx> for Collector<'_, 'tcx> {
151     fn visit_local(&mut self, &index: &Local, context: PlaceContext, location: Location) {
152         debug!("visit_local: index={:?} context={:?} location={:?}", index, context, location);
153         // We're only interested in temporaries and the return place
154         match self.body.local_kind(index) {
155             LocalKind::Temp | LocalKind::ReturnPointer => {}
156             LocalKind::Arg | LocalKind::Var => return,
157         }
158
159         // Ignore drops, if the temp gets promoted,
160         // then it's constant and thus drop is noop.
161         // Non-uses are also irrelevant.
162         if context.is_drop() || !context.is_use() {
163             debug!(
164                 "visit_local: context.is_drop={:?} context.is_use={:?}",
165                 context.is_drop(),
166                 context.is_use(),
167             );
168             return;
169         }
170
171         let temp = &mut self.temps[index];
172         debug!("visit_local: temp={:?}", temp);
173         if *temp == TempState::Undefined {
174             match context {
175                 PlaceContext::MutatingUse(MutatingUseContext::Store)
176                 | PlaceContext::MutatingUse(MutatingUseContext::Call) => {
177                     *temp = TempState::Defined { location, uses: 0 };
178                     return;
179                 }
180                 _ => { /* mark as unpromotable below */ }
181             }
182         } else if let TempState::Defined { ref mut uses, .. } = *temp {
183             // We always allow borrows, even mutable ones, as we need
184             // to promote mutable borrows of some ZSTs e.g., `&mut []`.
185             let allowed_use = match context {
186                 PlaceContext::MutatingUse(MutatingUseContext::Borrow)
187                 | PlaceContext::NonMutatingUse(_) => true,
188                 PlaceContext::MutatingUse(_) | PlaceContext::NonUse(_) => false,
189             };
190             debug!("visit_local: allowed_use={:?}", allowed_use);
191             if allowed_use {
192                 *uses += 1;
193                 return;
194             }
195             /* mark as unpromotable below */
196         }
197         *temp = TempState::Unpromotable;
198     }
199
200     fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
201         self.super_rvalue(rvalue, location);
202
203         match *rvalue {
204             Rvalue::Ref(..) => {
205                 self.candidates.push(Candidate::Ref(location));
206             }
207             Rvalue::Repeat(..) if self.tcx.features().const_in_array_repeat_expressions => {
208                 // FIXME(#49147) only promote the element when it isn't `Copy`
209                 // (so that code that can copy it at runtime is unaffected).
210                 self.candidates.push(Candidate::Repeat(location));
211             }
212             _ => {}
213         }
214     }
215
216     fn visit_terminator_kind(&mut self, kind: &TerminatorKind<'tcx>, location: Location) {
217         self.super_terminator_kind(kind, location);
218
219         if let TerminatorKind::Call { ref func, .. } = *kind {
220             if let ty::FnDef(def_id, _) = func.ty(self.body, self.tcx).kind {
221                 let fn_sig = self.tcx.fn_sig(def_id);
222                 if let Abi::RustIntrinsic | Abi::PlatformIntrinsic = fn_sig.abi() {
223                     let name = self.tcx.item_name(def_id);
224                     // FIXME(eddyb) use `#[rustc_args_required_const(2)]` for shuffles.
225                     if name.as_str().starts_with("simd_shuffle") {
226                         self.candidates.push(Candidate::Argument { bb: location.block, index: 2 });
227
228                         return; // Don't double count `simd_shuffle` candidates
229                     }
230                 }
231
232                 if let Some(constant_args) = args_required_const(self.tcx, def_id) {
233                     for index in constant_args {
234                         self.candidates.push(Candidate::Argument { bb: location.block, index });
235                     }
236                 }
237             }
238         }
239     }
240
241     fn visit_source_info(&mut self, source_info: &SourceInfo) {
242         self.span = source_info.span;
243     }
244 }
245
246 pub fn collect_temps_and_candidates(
247     tcx: TyCtxt<'tcx>,
248     body: &Body<'tcx>,
249     rpo: &mut ReversePostorder<'_, 'tcx>,
250 ) -> (IndexVec<Local, TempState>, Vec<Candidate>) {
251     let mut collector = Collector {
252         tcx,
253         body,
254         temps: IndexVec::from_elem(TempState::Undefined, &body.local_decls),
255         candidates: vec![],
256         span: body.span,
257     };
258     for (bb, data) in rpo {
259         collector.visit_basic_block_data(bb, data);
260     }
261     (collector.temps, collector.candidates)
262 }
263
264 /// Checks whether locals that appear in a promotion context (`Candidate`) are actually promotable.
265 ///
266 /// This wraps an `Item`, and has access to all fields of that `Item` via `Deref` coercion.
267 struct Validator<'a, 'tcx> {
268     item: Item<'a, 'tcx>,
269     temps: &'a IndexVec<Local, TempState>,
270
271     /// Explicit promotion happens e.g. for constant arguments declared via
272     /// `rustc_args_required_const`.
273     /// Implicit promotion has almost the same rules, except that disallows `const fn`
274     /// except for those marked `#[rustc_promotable]`. This is to avoid changing
275     /// a legitimate run-time operation into a failing compile-time operation
276     /// e.g. due to addresses being compared inside the function.
277     explicit: bool,
278 }
279
280 impl std::ops::Deref for Validator<'a, 'tcx> {
281     type Target = Item<'a, 'tcx>;
282
283     fn deref(&self) -> &Self::Target {
284         &self.item
285     }
286 }
287
288 struct Unpromotable;
289
290 impl<'tcx> Validator<'_, 'tcx> {
291     fn validate_candidate(&self, candidate: Candidate) -> Result<(), Unpromotable> {
292         match candidate {
293             Candidate::Ref(loc) => {
294                 assert!(!self.explicit);
295
296                 let statement = &self.body[loc.block].statements[loc.statement_index];
297                 match &statement.kind {
298                     StatementKind::Assign(box (_, Rvalue::Ref(_, kind, place))) => {
299                         match kind {
300                             BorrowKind::Shared | BorrowKind::Mut { .. } => {}
301
302                             // FIXME(eddyb) these aren't promoted here but *could*
303                             // be promoted as part of a larger value because
304                             // `validate_rvalue`  doesn't check them, need to
305                             // figure out what is the intended behavior.
306                             BorrowKind::Shallow | BorrowKind::Unique => return Err(Unpromotable),
307                         }
308
309                         // We can only promote interior borrows of promotable temps (non-temps
310                         // don't get promoted anyway).
311                         let base = match place.base {
312                             PlaceBase::Local(local) => local,
313                         };
314                         self.validate_local(base)?;
315
316                         if place.projection.contains(&ProjectionElem::Deref) {
317                             return Err(Unpromotable);
318                         }
319
320                         let mut has_mut_interior =
321                             self.qualif_local::<qualifs::HasMutInterior>(base);
322                         // HACK(eddyb) this should compute the same thing as
323                         // `<HasMutInterior as Qualif>::in_projection` from
324                         // `check_consts::qualifs` but without recursion.
325                         if has_mut_interior {
326                             // This allows borrowing fields which don't have
327                             // `HasMutInterior`, from a type that does, e.g.:
328                             // `let _: &'static _ = &(Cell::new(1), 2).1;`
329                             let mut place_projection = &place.projection[..];
330                             // FIXME(eddyb) use a forward loop instead of a reverse one.
331                             while let [proj_base @ .., elem] = place_projection {
332                                 // FIXME(eddyb) this is probably excessive, with
333                                 // the exception of `union` member accesses.
334                                 let ty =
335                                     Place::ty_from(&place.base, proj_base, *self.body, self.tcx)
336                                         .projection_ty(self.tcx, elem)
337                                         .ty;
338                                 if ty.is_freeze(self.tcx, self.param_env, DUMMY_SP) {
339                                     has_mut_interior = false;
340                                     break;
341                                 }
342
343                                 place_projection = proj_base;
344                             }
345                         }
346
347                         // FIXME(eddyb) this duplicates part of `validate_rvalue`.
348                         if has_mut_interior {
349                             return Err(Unpromotable);
350                         }
351                         if self.qualif_local::<qualifs::NeedsDrop>(base) {
352                             return Err(Unpromotable);
353                         }
354
355                         if let BorrowKind::Mut { .. } = kind {
356                             let ty = place.ty(*self.body, self.tcx).ty;
357
358                             // In theory, any zero-sized value could be borrowed
359                             // mutably without consequences. However, only &mut []
360                             // is allowed right now, and only in functions.
361                             if self.const_kind == Some(ConstKind::StaticMut) {
362                                 // Inside a `static mut`, &mut [...] is also allowed.
363                                 match ty.kind {
364                                     ty::Array(..) | ty::Slice(_) => {}
365                                     _ => return Err(Unpromotable),
366                                 }
367                             } else if let ty::Array(_, len) = ty.kind {
368                                 // FIXME(eddyb) the `self.is_non_const_fn` condition
369                                 // seems unnecessary, given that this is merely a ZST.
370                                 match len.try_eval_usize(self.tcx, self.param_env) {
371                                     Some(0) if self.const_kind.is_none() => {}
372                                     _ => return Err(Unpromotable),
373                                 }
374                             } else {
375                                 return Err(Unpromotable);
376                             }
377                         }
378
379                         Ok(())
380                     }
381                     _ => bug!(),
382                 }
383             }
384             Candidate::Repeat(loc) => {
385                 assert!(!self.explicit);
386
387                 let statement = &self.body[loc.block].statements[loc.statement_index];
388                 match &statement.kind {
389                     StatementKind::Assign(box (_, Rvalue::Repeat(ref operand, _))) => {
390                         if !self.tcx.features().const_in_array_repeat_expressions {
391                             return Err(Unpromotable);
392                         }
393
394                         self.validate_operand(operand)
395                     }
396                     _ => bug!(),
397                 }
398             }
399             Candidate::Argument { bb, index } => {
400                 assert!(self.explicit);
401
402                 let terminator = self.body[bb].terminator();
403                 match &terminator.kind {
404                     TerminatorKind::Call { args, .. } => self.validate_operand(&args[index]),
405                     _ => bug!(),
406                 }
407             }
408         }
409     }
410
411     // FIXME(eddyb) maybe cache this?
412     fn qualif_local<Q: qualifs::Qualif>(&self, local: Local) -> bool {
413         let per_local = &|l| self.qualif_local::<Q>(l);
414
415         if let TempState::Defined { location: loc, .. } = self.temps[local] {
416             let num_stmts = self.body[loc.block].statements.len();
417
418             if loc.statement_index < num_stmts {
419                 let statement = &self.body[loc.block].statements[loc.statement_index];
420                 match &statement.kind {
421                     StatementKind::Assign(box (_, rhs)) => Q::in_rvalue(&self.item, per_local, rhs),
422                     _ => {
423                         span_bug!(
424                             statement.source_info.span,
425                             "{:?} is not an assignment",
426                             statement
427                         );
428                     }
429                 }
430             } else {
431                 let terminator = self.body[loc.block].terminator();
432                 match &terminator.kind {
433                     TerminatorKind::Call { func, args, .. } => {
434                         let return_ty = self.body.local_decls[local].ty;
435                         Q::in_call(&self.item, per_local, func, args, return_ty)
436                     }
437                     kind => {
438                         span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
439                     }
440                 }
441             }
442         } else {
443             let span = self.body.local_decls[local].source_info.span;
444             span_bug!(span, "{:?} not promotable, qualif_local shouldn't have been called", local);
445         }
446     }
447
448     // FIXME(eddyb) maybe cache this?
449     fn validate_local(&self, local: Local) -> Result<(), Unpromotable> {
450         if let TempState::Defined { location: loc, .. } = self.temps[local] {
451             let num_stmts = self.body[loc.block].statements.len();
452
453             if loc.statement_index < num_stmts {
454                 let statement = &self.body[loc.block].statements[loc.statement_index];
455                 match &statement.kind {
456                     StatementKind::Assign(box (_, rhs)) => self.validate_rvalue(rhs),
457                     _ => {
458                         span_bug!(
459                             statement.source_info.span,
460                             "{:?} is not an assignment",
461                             statement
462                         );
463                     }
464                 }
465             } else {
466                 let terminator = self.body[loc.block].terminator();
467                 match &terminator.kind {
468                     TerminatorKind::Call { func, args, .. } => self.validate_call(func, args),
469                     kind => {
470                         span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
471                     }
472                 }
473             }
474         } else {
475             Err(Unpromotable)
476         }
477     }
478
479     fn validate_place(&self, place: PlaceRef<'_, 'tcx>) -> Result<(), Unpromotable> {
480         match place {
481             PlaceRef { base: PlaceBase::Local(local), projection: [] } => {
482                 self.validate_local(*local)
483             }
484             PlaceRef { base: _, projection: [proj_base @ .., elem] } => {
485                 match *elem {
486                     ProjectionElem::Deref | ProjectionElem::Downcast(..) => {
487                         return Err(Unpromotable);
488                     }
489
490                     ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } => {}
491
492                     ProjectionElem::Index(local) => {
493                         self.validate_local(local)?;
494                     }
495
496                     ProjectionElem::Field(..) => {
497                         if self.const_kind.is_none() {
498                             let base_ty =
499                                 Place::ty_from(place.base, proj_base, *self.body, self.tcx).ty;
500                             if let Some(def) = base_ty.ty_adt_def() {
501                                 // No promotion of union field accesses.
502                                 if def.is_union() {
503                                     return Err(Unpromotable);
504                                 }
505                             }
506                         }
507                     }
508                 }
509
510                 self.validate_place(PlaceRef { base: place.base, projection: proj_base })
511             }
512         }
513     }
514
515     fn validate_operand(&self, operand: &Operand<'tcx>) -> Result<(), Unpromotable> {
516         match operand {
517             Operand::Copy(place) | Operand::Move(place) => self.validate_place(place.as_ref()),
518
519             // The qualifs for a constant (e.g. `HasMutInterior`) are checked in
520             // `validate_rvalue` upon access.
521             Operand::Constant(c) => {
522                 if let Some(def_id) = c.check_static_ptr(self.tcx) {
523                     // Only allow statics (not consts) to refer to other statics.
524                     // FIXME(eddyb) does this matter at all for promotion?
525                     let is_static = self.const_kind.map_or(false, |k| k.is_static());
526                     if !is_static {
527                         return Err(Unpromotable);
528                     }
529
530                     let is_thread_local = self.tcx.has_attr(def_id, sym::thread_local);
531                     if is_thread_local {
532                         return Err(Unpromotable);
533                     }
534                 }
535
536                 Ok(())
537             }
538         }
539     }
540
541     fn validate_rvalue(&self, rvalue: &Rvalue<'tcx>) -> Result<(), Unpromotable> {
542         match *rvalue {
543             Rvalue::Cast(CastKind::Misc, ref operand, cast_ty) if self.const_kind.is_none() => {
544                 let operand_ty = operand.ty(*self.body, self.tcx);
545                 let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast");
546                 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
547                 match (cast_in, cast_out) {
548                     (CastTy::Ptr(_), CastTy::Int(_)) | (CastTy::FnPtr, CastTy::Int(_)) => {
549                         // in normal functions, mark such casts as not promotable
550                         return Err(Unpromotable);
551                     }
552                     _ => {}
553                 }
554             }
555
556             Rvalue::BinaryOp(op, ref lhs, _) if self.const_kind.is_none() => {
557                 if let ty::RawPtr(_) | ty::FnPtr(..) = lhs.ty(*self.body, self.tcx).kind {
558                     assert!(
559                         op == BinOp::Eq
560                             || op == BinOp::Ne
561                             || op == BinOp::Le
562                             || op == BinOp::Lt
563                             || op == BinOp::Ge
564                             || op == BinOp::Gt
565                             || op == BinOp::Offset
566                     );
567
568                     // raw pointer operations are not allowed inside promoteds
569                     return Err(Unpromotable);
570                 }
571             }
572
573             Rvalue::NullaryOp(NullOp::Box, _) => return Err(Unpromotable),
574
575             _ => {}
576         }
577
578         match rvalue {
579             Rvalue::NullaryOp(..) => Ok(()),
580
581             Rvalue::Discriminant(place) | Rvalue::Len(place) => self.validate_place(place.as_ref()),
582
583             Rvalue::Use(operand)
584             | Rvalue::Repeat(operand, _)
585             | Rvalue::UnaryOp(_, operand)
586             | Rvalue::Cast(_, operand, _) => self.validate_operand(operand),
587
588             Rvalue::BinaryOp(_, lhs, rhs) | Rvalue::CheckedBinaryOp(_, lhs, rhs) => {
589                 self.validate_operand(lhs)?;
590                 self.validate_operand(rhs)
591             }
592
593             Rvalue::AddressOf(_, place) => {
594                 // Raw reborrows can come from reference to pointer coercions,
595                 // so are allowed.
596                 if let [proj_base @ .., ProjectionElem::Deref] = place.projection.as_ref() {
597                     let base_ty = Place::ty_from(&place.base, proj_base, *self.body, self.tcx).ty;
598                     if let ty::Ref(..) = base_ty.kind {
599                         return self
600                             .validate_place(PlaceRef { base: &place.base, projection: proj_base });
601                     }
602                 }
603                 Err(Unpromotable)
604             }
605
606             Rvalue::Ref(_, kind, place) => {
607                 if let BorrowKind::Mut { .. } = kind {
608                     let ty = place.ty(*self.body, self.tcx).ty;
609
610                     // In theory, any zero-sized value could be borrowed
611                     // mutably without consequences. However, only &mut []
612                     // is allowed right now, and only in functions.
613                     if self.const_kind == Some(ConstKind::StaticMut) {
614                         // Inside a `static mut`, &mut [...] is also allowed.
615                         match ty.kind {
616                             ty::Array(..) | ty::Slice(_) => {}
617                             _ => return Err(Unpromotable),
618                         }
619                     } else if let ty::Array(_, len) = ty.kind {
620                         // FIXME(eddyb): We only return `Unpromotable` for `&mut []` inside a
621                         // const context which seems unnecessary given that this is merely a ZST.
622                         match len.try_eval_usize(self.tcx, self.param_env) {
623                             Some(0) if self.const_kind.is_none() => {}
624                             _ => return Err(Unpromotable),
625                         }
626                     } else {
627                         return Err(Unpromotable);
628                     }
629                 }
630
631                 // Special-case reborrows to be more like a copy of the reference.
632                 let mut place = place.as_ref();
633                 if let [proj_base @ .., ProjectionElem::Deref] = &place.projection {
634                     let base_ty = Place::ty_from(&place.base, proj_base, *self.body, self.tcx).ty;
635                     if let ty::Ref(..) = base_ty.kind {
636                         place = PlaceRef { base: &place.base, projection: proj_base };
637                     }
638                 }
639
640                 self.validate_place(place)?;
641
642                 // HACK(eddyb) this should compute the same thing as
643                 // `<HasMutInterior as Qualif>::in_projection` from
644                 // `check_consts::qualifs` but without recursion.
645                 let mut has_mut_interior = match place.base {
646                     PlaceBase::Local(local) => self.qualif_local::<qualifs::HasMutInterior>(*local),
647                 };
648                 if has_mut_interior {
649                     let mut place_projection = place.projection;
650                     // FIXME(eddyb) use a forward loop instead of a reverse one.
651                     while let [proj_base @ .., elem] = place_projection {
652                         // FIXME(eddyb) this is probably excessive, with
653                         // the exception of `union` member accesses.
654                         let ty = Place::ty_from(place.base, proj_base, *self.body, self.tcx)
655                             .projection_ty(self.tcx, elem)
656                             .ty;
657                         if ty.is_freeze(self.tcx, self.param_env, DUMMY_SP) {
658                             has_mut_interior = false;
659                             break;
660                         }
661
662                         place_projection = proj_base;
663                     }
664                 }
665                 if has_mut_interior {
666                     return Err(Unpromotable);
667                 }
668
669                 Ok(())
670             }
671
672             Rvalue::Aggregate(_, ref operands) => {
673                 for o in operands {
674                     self.validate_operand(o)?;
675                 }
676
677                 Ok(())
678             }
679         }
680     }
681
682     fn validate_call(
683         &self,
684         callee: &Operand<'tcx>,
685         args: &[Operand<'tcx>],
686     ) -> Result<(), Unpromotable> {
687         let fn_ty = callee.ty(*self.body, self.tcx);
688
689         if !self.explicit && self.const_kind.is_none() {
690             if let ty::FnDef(def_id, _) = fn_ty.kind {
691                 // Never promote runtime `const fn` calls of
692                 // functions without `#[rustc_promotable]`.
693                 if !self.tcx.is_promotable_const_fn(def_id) {
694                     return Err(Unpromotable);
695                 }
696             }
697         }
698
699         let is_const_fn = match fn_ty.kind {
700             ty::FnDef(def_id, _) => {
701                 is_const_fn(self.tcx, def_id)
702                     || is_unstable_const_fn(self.tcx, def_id).is_some()
703                     || is_lang_panic_fn(self.tcx, self.def_id)
704             }
705             _ => false,
706         };
707         if !is_const_fn {
708             return Err(Unpromotable);
709         }
710
711         self.validate_operand(callee)?;
712         for arg in args {
713             self.validate_operand(arg)?;
714         }
715
716         Ok(())
717     }
718 }
719
720 // FIXME(eddyb) remove the differences for promotability in `static`, `const`, `const fn`.
721 pub fn validate_candidates(
722     tcx: TyCtxt<'tcx>,
723     body: ReadOnlyBodyAndCache<'_, 'tcx>,
724     def_id: DefId,
725     temps: &IndexVec<Local, TempState>,
726     candidates: &[Candidate],
727 ) -> Vec<Candidate> {
728     let mut validator = Validator { item: Item::new(tcx, def_id, body), temps, explicit: false };
729
730     candidates
731         .iter()
732         .copied()
733         .filter(|&candidate| {
734             validator.explicit = candidate.forces_explicit_promotion();
735
736             // FIXME(eddyb) also emit the errors for shuffle indices
737             // and `#[rustc_args_required_const]` arguments here.
738
739             let is_promotable = validator.validate_candidate(candidate).is_ok();
740             match candidate {
741                 Candidate::Argument { bb, index } if !is_promotable => {
742                     let span = body[bb].terminator().source_info.span;
743                     let msg = format!("argument {} is required to be a constant", index + 1);
744                     tcx.sess.span_err(span, &msg);
745                 }
746                 _ => (),
747             }
748
749             is_promotable
750         })
751         .collect()
752 }
753
754 struct Promoter<'a, 'tcx> {
755     tcx: TyCtxt<'tcx>,
756     source: &'a mut BodyAndCache<'tcx>,
757     promoted: BodyAndCache<'tcx>,
758     temps: &'a mut IndexVec<Local, TempState>,
759     extra_statements: &'a mut Vec<(Location, Statement<'tcx>)>,
760
761     /// If true, all nested temps are also kept in the
762     /// source MIR, not moved to the promoted MIR.
763     keep_original: bool,
764 }
765
766 impl<'a, 'tcx> Promoter<'a, 'tcx> {
767     fn new_block(&mut self) -> BasicBlock {
768         let span = self.promoted.span;
769         self.promoted.basic_blocks_mut().push(BasicBlockData {
770             statements: vec![],
771             terminator: Some(Terminator {
772                 source_info: SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE },
773                 kind: TerminatorKind::Return,
774             }),
775             is_cleanup: false,
776         })
777     }
778
779     fn assign(&mut self, dest: Local, rvalue: Rvalue<'tcx>, span: Span) {
780         let last = self.promoted.basic_blocks().last().unwrap();
781         let data = &mut self.promoted[last];
782         data.statements.push(Statement {
783             source_info: SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE },
784             kind: StatementKind::Assign(box (Place::from(dest), rvalue)),
785         });
786     }
787
788     fn is_temp_kind(&self, local: Local) -> bool {
789         self.source.local_kind(local) == LocalKind::Temp
790     }
791
792     /// Copies the initialization of this temp to the
793     /// promoted MIR, recursing through temps.
794     fn promote_temp(&mut self, temp: Local) -> Local {
795         let old_keep_original = self.keep_original;
796         let loc = match self.temps[temp] {
797             TempState::Defined { location, uses } if uses > 0 => {
798                 if uses > 1 {
799                     self.keep_original = true;
800                 }
801                 location
802             }
803             state => {
804                 span_bug!(self.promoted.span, "{:?} not promotable: {:?}", temp, state);
805             }
806         };
807         if !self.keep_original {
808             self.temps[temp] = TempState::PromotedOut;
809         }
810
811         let num_stmts = self.source[loc.block].statements.len();
812         let new_temp = self.promoted.local_decls.push(LocalDecl::new_temp(
813             self.source.local_decls[temp].ty,
814             self.source.local_decls[temp].source_info.span,
815         ));
816
817         debug!("promote({:?} @ {:?}/{:?}, {:?})", temp, loc, num_stmts, self.keep_original);
818
819         // First, take the Rvalue or Call out of the source MIR,
820         // or duplicate it, depending on keep_original.
821         if loc.statement_index < num_stmts {
822             let (mut rvalue, source_info) = {
823                 let statement = &mut self.source[loc.block].statements[loc.statement_index];
824                 let rhs = match statement.kind {
825                     StatementKind::Assign(box (_, ref mut rhs)) => rhs,
826                     _ => {
827                         span_bug!(
828                             statement.source_info.span,
829                             "{:?} is not an assignment",
830                             statement
831                         );
832                     }
833                 };
834
835                 (
836                     if self.keep_original {
837                         rhs.clone()
838                     } else {
839                         let unit = Rvalue::Aggregate(box AggregateKind::Tuple, vec![]);
840                         mem::replace(rhs, unit)
841                     },
842                     statement.source_info,
843                 )
844             };
845
846             self.visit_rvalue(&mut rvalue, loc);
847             self.assign(new_temp, rvalue, source_info.span);
848         } else {
849             let terminator = if self.keep_original {
850                 self.source[loc.block].terminator().clone()
851             } else {
852                 let terminator = self.source[loc.block].terminator_mut();
853                 let target = match terminator.kind {
854                     TerminatorKind::Call { destination: Some((_, target)), .. } => target,
855                     ref kind => {
856                         span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
857                     }
858                 };
859                 Terminator {
860                     source_info: terminator.source_info,
861                     kind: mem::replace(&mut terminator.kind, TerminatorKind::Goto { target }),
862                 }
863             };
864
865             match terminator.kind {
866                 TerminatorKind::Call { mut func, mut args, from_hir_call, .. } => {
867                     self.visit_operand(&mut func, loc);
868                     for arg in &mut args {
869                         self.visit_operand(arg, loc);
870                     }
871
872                     let last = self.promoted.basic_blocks().last().unwrap();
873                     let new_target = self.new_block();
874
875                     *self.promoted[last].terminator_mut() = Terminator {
876                         kind: TerminatorKind::Call {
877                             func,
878                             args,
879                             cleanup: None,
880                             destination: Some((Place::from(new_temp), new_target)),
881                             from_hir_call,
882                         },
883                         ..terminator
884                     };
885                 }
886                 ref kind => {
887                     span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
888                 }
889             };
890         };
891
892         self.keep_original = old_keep_original;
893         new_temp
894     }
895
896     fn promote_candidate(
897         mut self,
898         def_id: DefId,
899         candidate: Candidate,
900         next_promoted_id: usize,
901     ) -> Option<BodyAndCache<'tcx>> {
902         let mut rvalue = {
903             let promoted = &mut self.promoted;
904             let promoted_id = Promoted::new(next_promoted_id);
905             let tcx = self.tcx;
906             let mut promoted_operand = |ty, span| {
907                 promoted.span = span;
908                 promoted.local_decls[RETURN_PLACE] = LocalDecl::new_return_place(ty, span);
909
910                 Operand::Constant(Box::new(Constant {
911                     span,
912                     user_ty: None,
913                     literal: tcx.mk_const(ty::Const {
914                         ty,
915                         val: ty::ConstKind::Unevaluated(
916                             def_id,
917                             InternalSubsts::identity_for_item(tcx, def_id),
918                             Some(promoted_id),
919                         ),
920                     }),
921                 }))
922             };
923             let (blocks, local_decls) = self.source.basic_blocks_and_local_decls_mut();
924             match candidate {
925                 Candidate::Ref(loc) => {
926                     let ref mut statement = blocks[loc.block].statements[loc.statement_index];
927                     match statement.kind {
928                         StatementKind::Assign(box (
929                             _,
930                             Rvalue::Ref(ref mut region, borrow_kind, ref mut place),
931                         )) => {
932                             // Use the underlying local for this (necessarily interior) borrow.
933                             let ty = place.base.ty(local_decls).ty;
934                             let span = statement.source_info.span;
935
936                             let ref_ty = tcx.mk_ref(
937                                 tcx.lifetimes.re_static,
938                                 ty::TypeAndMut { ty, mutbl: borrow_kind.to_mutbl_lossy() },
939                             );
940
941                             *region = tcx.lifetimes.re_static;
942
943                             let mut projection = vec![PlaceElem::Deref];
944                             projection.extend(place.projection);
945                             place.projection = tcx.intern_place_elems(&projection);
946
947                             // Create a temp to hold the promoted reference.
948                             // This is because `*r` requires `r` to be a local,
949                             // otherwise we would use the `promoted` directly.
950                             let mut promoted_ref = LocalDecl::new_temp(ref_ty, span);
951                             promoted_ref.source_info = statement.source_info;
952                             let promoted_ref = local_decls.push(promoted_ref);
953                             assert_eq!(self.temps.push(TempState::Unpromotable), promoted_ref);
954
955                             let promoted_ref_statement = Statement {
956                                 source_info: statement.source_info,
957                                 kind: StatementKind::Assign(Box::new((
958                                     Place::from(promoted_ref),
959                                     Rvalue::Use(promoted_operand(ref_ty, span)),
960                                 ))),
961                             };
962                             self.extra_statements.push((loc, promoted_ref_statement));
963
964                             Rvalue::Ref(
965                                 tcx.lifetimes.re_static,
966                                 borrow_kind,
967                                 Place {
968                                     base: mem::replace(
969                                         &mut place.base,
970                                         PlaceBase::Local(promoted_ref),
971                                     ),
972                                     projection: List::empty(),
973                                 },
974                             )
975                         }
976                         _ => bug!(),
977                     }
978                 }
979                 Candidate::Repeat(loc) => {
980                     let ref mut statement = blocks[loc.block].statements[loc.statement_index];
981                     match statement.kind {
982                         StatementKind::Assign(box (_, Rvalue::Repeat(ref mut operand, _))) => {
983                             let ty = operand.ty(local_decls, self.tcx);
984                             let span = statement.source_info.span;
985
986                             Rvalue::Use(mem::replace(operand, promoted_operand(ty, span)))
987                         }
988                         _ => bug!(),
989                     }
990                 }
991                 Candidate::Argument { bb, index } => {
992                     let terminator = blocks[bb].terminator_mut();
993                     match terminator.kind {
994                         TerminatorKind::Call { ref mut args, .. } => {
995                             let ty = args[index].ty(local_decls, self.tcx);
996                             let span = terminator.source_info.span;
997
998                             Rvalue::Use(mem::replace(&mut args[index], promoted_operand(ty, span)))
999                         }
1000                         // We expected a `TerminatorKind::Call` for which we'd like to promote an
1001                         // argument. `qualify_consts` saw a `TerminatorKind::Call` here, but
1002                         // we are seeing a `Goto`. That means that the `promote_temps` method
1003                         // already promoted this call away entirely. This case occurs when calling
1004                         // a function requiring a constant argument and as that constant value
1005                         // providing a value whose computation contains another call to a function
1006                         // requiring a constant argument.
1007                         TerminatorKind::Goto { .. } => return None,
1008                         _ => bug!(),
1009                     }
1010                 }
1011             }
1012         };
1013
1014         assert_eq!(self.new_block(), START_BLOCK);
1015         self.visit_rvalue(
1016             &mut rvalue,
1017             Location { block: BasicBlock::new(0), statement_index: usize::MAX },
1018         );
1019
1020         let span = self.promoted.span;
1021         self.assign(RETURN_PLACE, rvalue, span);
1022         Some(self.promoted)
1023     }
1024 }
1025
1026 /// Replaces all temporaries with their promoted counterparts.
1027 impl<'a, 'tcx> MutVisitor<'tcx> for Promoter<'a, 'tcx> {
1028     fn tcx(&self) -> TyCtxt<'tcx> {
1029         self.tcx
1030     }
1031
1032     fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
1033         if self.is_temp_kind(*local) {
1034             *local = self.promote_temp(*local);
1035         }
1036     }
1037
1038     fn process_projection_elem(&mut self, elem: &PlaceElem<'tcx>) -> Option<PlaceElem<'tcx>> {
1039         match elem {
1040             PlaceElem::Index(local) if self.is_temp_kind(*local) => {
1041                 Some(PlaceElem::Index(self.promote_temp(*local)))
1042             }
1043             _ => None,
1044         }
1045     }
1046 }
1047
1048 pub fn promote_candidates<'tcx>(
1049     def_id: DefId,
1050     body: &mut BodyAndCache<'tcx>,
1051     tcx: TyCtxt<'tcx>,
1052     mut temps: IndexVec<Local, TempState>,
1053     candidates: Vec<Candidate>,
1054 ) -> IndexVec<Promoted, BodyAndCache<'tcx>> {
1055     // Visit candidates in reverse, in case they're nested.
1056     debug!("promote_candidates({:?})", candidates);
1057
1058     let mut promotions = IndexVec::new();
1059
1060     let mut extra_statements = vec![];
1061     for candidate in candidates.into_iter().rev() {
1062         match candidate {
1063             Candidate::Repeat(Location { block, statement_index })
1064             | Candidate::Ref(Location { block, statement_index }) => {
1065                 match &body[block].statements[statement_index].kind {
1066                     StatementKind::Assign(box (place, _)) => {
1067                         if let Some(local) = place.as_local() {
1068                             if temps[local] == TempState::PromotedOut {
1069                                 // Already promoted.
1070                                 continue;
1071                             }
1072                         }
1073                     }
1074                     _ => {}
1075                 }
1076             }
1077             Candidate::Argument { .. } => {}
1078         }
1079
1080         // Declare return place local so that `mir::Body::new` doesn't complain.
1081         let initial_locals =
1082             iter::once(LocalDecl::new_return_place(tcx.types.never, body.span)).collect();
1083
1084         let mut promoted = Body::new(
1085             IndexVec::new(),
1086             // FIXME: maybe try to filter this to avoid blowing up
1087             // memory usage?
1088             body.source_scopes.clone(),
1089             initial_locals,
1090             IndexVec::new(),
1091             0,
1092             vec![],
1093             body.span,
1094             vec![],
1095             body.generator_kind,
1096         );
1097         promoted.ignore_interior_mut_in_const_validation = true;
1098
1099         let promoter = Promoter {
1100             promoted: BodyAndCache::new(promoted),
1101             tcx,
1102             source: body,
1103             temps: &mut temps,
1104             extra_statements: &mut extra_statements,
1105             keep_original: false,
1106         };
1107
1108         //FIXME(oli-obk): having a `maybe_push()` method on `IndexVec` might be nice
1109         if let Some(promoted) = promoter.promote_candidate(def_id, candidate, promotions.len()) {
1110             promotions.push(promoted);
1111         }
1112     }
1113
1114     // Insert each of `extra_statements` before its indicated location, which
1115     // has to be done in reverse location order, to not invalidate the rest.
1116     extra_statements.sort_by_key(|&(loc, _)| cmp::Reverse(loc));
1117     for (loc, statement) in extra_statements {
1118         body[loc.block].statements.insert(loc.statement_index, statement);
1119     }
1120
1121     // Eliminate assignments to, and drops of promoted temps.
1122     let promoted = |index: Local| temps[index] == TempState::PromotedOut;
1123     for block in body.basic_blocks_mut() {
1124         block.statements.retain(|statement| match &statement.kind {
1125             StatementKind::Assign(box (place, _)) => {
1126                 if let Some(index) = place.as_local() {
1127                     !promoted(index)
1128                 } else {
1129                     true
1130                 }
1131             }
1132             StatementKind::StorageLive(index) | StatementKind::StorageDead(index) => {
1133                 !promoted(*index)
1134             }
1135             _ => true,
1136         });
1137         let terminator = block.terminator_mut();
1138         match &terminator.kind {
1139             TerminatorKind::Drop { location: place, target, .. } => {
1140                 if let Some(index) = place.as_local() {
1141                     if promoted(index) {
1142                         terminator.kind = TerminatorKind::Goto { target: *target };
1143                     }
1144                 }
1145             }
1146             _ => {}
1147         }
1148     }
1149
1150     promotions
1151 }
1152
1153 /// This function returns `true` if the `const_in_array_repeat_expressions` feature attribute should
1154 /// be suggested. This function is probably quite expensive, it shouldn't be run in the happy path.
1155 /// Feature attribute should be suggested if `operand` can be promoted and the feature is not
1156 /// enabled.
1157 crate fn should_suggest_const_in_array_repeat_expressions_attribute<'tcx>(
1158     tcx: TyCtxt<'tcx>,
1159     mir_def_id: DefId,
1160     body: ReadOnlyBodyAndCache<'_, 'tcx>,
1161     operand: &Operand<'tcx>,
1162 ) -> bool {
1163     let mut rpo = traversal::reverse_postorder(&body);
1164     let (temps, _) = collect_temps_and_candidates(tcx, &body, &mut rpo);
1165     let validator =
1166         Validator { item: Item::new(tcx, mir_def_id, body), temps: &temps, explicit: false };
1167
1168     let should_promote = validator.validate_operand(operand).is_ok();
1169     let feature_flag = tcx.features().const_in_array_repeat_expressions;
1170     debug!(
1171         "should_suggest_const_in_array_repeat_expressions_flag: mir_def_id={:?} \
1172             should_promote={:?} feature_flag={:?}",
1173         mir_def_id, should_promote, feature_flag
1174     );
1175     should_promote && !feature_flag
1176 }