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