]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/promote_consts.rs
Rollup merge of #67566 - Mark-Simulacrum:thread-id-u64, r=alexcrichton
[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::{iter, mem, usize};
31
32 use crate::transform::check_consts::{is_lang_panic_fn, qualifs, ConstKind, Item};
33 use crate::transform::{MirPass, MirSource};
34
35 /// A `MirPass` for promotion.
36 ///
37 /// Promotion is the extraction of promotable temps into separate MIR bodies. This pass also emits
38 /// errors when promotion of `#[rustc_args_required_const]` arguments fails.
39 ///
40 /// After this pass is run, `promoted_fragments` will hold the MIR body corresponding to each
41 /// newly created `StaticKind::Promoted`.
42 #[derive(Default)]
43 pub struct PromoteTemps<'tcx> {
44     pub promoted_fragments: Cell<IndexVec<Promoted, BodyAndCache<'tcx>>>,
45 }
46
47 impl<'tcx> MirPass<'tcx> for PromoteTemps<'tcx> {
48     fn run_pass(&self, tcx: TyCtxt<'tcx>, src: MirSource<'tcx>, body: &mut BodyAndCache<'tcx>) {
49         // There's not really any point in promoting errorful MIR.
50         //
51         // This does not include MIR that failed const-checking, which we still try to promote.
52         if body.return_ty().references_error() {
53             tcx.sess.delay_span_bug(body.span, "PromoteTemps: MIR had errors");
54             return;
55         }
56
57         if src.promoted.is_some() {
58             return;
59         }
60
61         let def_id = src.def_id();
62
63         let mut rpo = traversal::reverse_postorder(body);
64         let (temps, all_candidates) = collect_temps_and_candidates(tcx, body, &mut rpo);
65
66         let promotable_candidates =
67             validate_candidates(tcx, read_only!(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                         let base = match place.base {
311                             PlaceBase::Local(local) => local,
312                             _ => return Err(Unpromotable),
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: PlaceBase::Static(_), projection: [] } => {
485                 bug!("qualifying already promoted MIR")
486             }
487             PlaceRef { base: _, projection: [proj_base @ .., elem] } => {
488                 match *elem {
489                     ProjectionElem::Deref | ProjectionElem::Downcast(..) => {
490                         return Err(Unpromotable);
491                     }
492
493                     ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } => {}
494
495                     ProjectionElem::Index(local) => {
496                         self.validate_local(local)?;
497                     }
498
499                     ProjectionElem::Field(..) => {
500                         if self.const_kind.is_none() {
501                             let base_ty =
502                                 Place::ty_from(place.base, proj_base, *self.body, self.tcx).ty;
503                             if let Some(def) = base_ty.ty_adt_def() {
504                                 // No promotion of union field accesses.
505                                 if def.is_union() {
506                                     return Err(Unpromotable);
507                                 }
508                             }
509                         }
510                     }
511                 }
512
513                 self.validate_place(PlaceRef { base: place.base, projection: proj_base })
514             }
515         }
516     }
517
518     fn validate_operand(&self, operand: &Operand<'tcx>) -> Result<(), Unpromotable> {
519         match operand {
520             Operand::Copy(place) | Operand::Move(place) => self.validate_place(place.as_ref()),
521
522             // The qualifs for a constant (e.g. `HasMutInterior`) are checked in
523             // `validate_rvalue` upon access.
524             Operand::Constant(c) => {
525                 if let Some(def_id) = c.check_static_ptr(self.tcx) {
526                     // Only allow statics (not consts) to refer to other statics.
527                     // FIXME(eddyb) does this matter at all for promotion?
528                     let is_static = self.const_kind.map_or(false, |k| k.is_static());
529                     if !is_static {
530                         return Err(Unpromotable);
531                     }
532
533                     let is_thread_local = self.tcx.has_attr(def_id, sym::thread_local);
534                     if is_thread_local {
535                         return Err(Unpromotable);
536                     }
537                 }
538
539                 Ok(())
540             }
541         }
542     }
543
544     fn validate_rvalue(&self, rvalue: &Rvalue<'tcx>) -> Result<(), Unpromotable> {
545         match *rvalue {
546             Rvalue::Cast(CastKind::Misc, ref operand, cast_ty) if self.const_kind.is_none() => {
547                 let operand_ty = operand.ty(*self.body, self.tcx);
548                 let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast");
549                 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
550                 match (cast_in, cast_out) {
551                     (CastTy::Ptr(_), CastTy::Int(_)) | (CastTy::FnPtr, CastTy::Int(_)) => {
552                         // in normal functions, mark such casts as not promotable
553                         return Err(Unpromotable);
554                     }
555                     _ => {}
556                 }
557             }
558
559             Rvalue::BinaryOp(op, ref lhs, _) if self.const_kind.is_none() => {
560                 if let ty::RawPtr(_) | ty::FnPtr(..) = lhs.ty(*self.body, self.tcx).kind {
561                     assert!(
562                         op == BinOp::Eq
563                             || op == BinOp::Ne
564                             || op == BinOp::Le
565                             || op == BinOp::Lt
566                             || op == BinOp::Ge
567                             || op == BinOp::Gt
568                             || op == BinOp::Offset
569                     );
570
571                     // raw pointer operations are not allowed inside promoteds
572                     return Err(Unpromotable);
573                 }
574             }
575
576             Rvalue::NullaryOp(NullOp::Box, _) => return Err(Unpromotable),
577
578             _ => {}
579         }
580
581         match rvalue {
582             Rvalue::NullaryOp(..) => Ok(()),
583
584             Rvalue::Discriminant(place) | Rvalue::Len(place) => self.validate_place(place.as_ref()),
585
586             Rvalue::Use(operand)
587             | Rvalue::Repeat(operand, _)
588             | Rvalue::UnaryOp(_, operand)
589             | Rvalue::Cast(_, operand, _) => self.validate_operand(operand),
590
591             Rvalue::BinaryOp(_, lhs, rhs) | Rvalue::CheckedBinaryOp(_, lhs, rhs) => {
592                 self.validate_operand(lhs)?;
593                 self.validate_operand(rhs)
594             }
595
596             Rvalue::AddressOf(_, place) => {
597                 // Raw reborrows can come from reference to pointer coercions,
598                 // so are allowed.
599                 if let [proj_base @ .., ProjectionElem::Deref] = place.projection.as_ref() {
600                     let base_ty = Place::ty_from(&place.base, proj_base, *self.body, self.tcx).ty;
601                     if let ty::Ref(..) = base_ty.kind {
602                         return self
603                             .validate_place(PlaceRef { base: &place.base, projection: proj_base });
604                     }
605                 }
606                 Err(Unpromotable)
607             }
608
609             Rvalue::Ref(_, kind, place) => {
610                 if let BorrowKind::Mut { .. } = kind {
611                     let ty = place.ty(*self.body, self.tcx).ty;
612
613                     // In theory, any zero-sized value could be borrowed
614                     // mutably without consequences. However, only &mut []
615                     // is allowed right now, and only in functions.
616                     if self.const_kind == Some(ConstKind::StaticMut) {
617                         // Inside a `static mut`, &mut [...] is also allowed.
618                         match ty.kind {
619                             ty::Array(..) | ty::Slice(_) => {}
620                             _ => return Err(Unpromotable),
621                         }
622                     } else if let ty::Array(_, len) = ty.kind {
623                         // FIXME(eddyb): We only return `Unpromotable` for `&mut []` inside a
624                         // const context which seems unnecessary given that this is merely a ZST.
625                         match len.try_eval_usize(self.tcx, self.param_env) {
626                             Some(0) if self.const_kind.is_none() => {}
627                             _ => return Err(Unpromotable),
628                         }
629                     } else {
630                         return Err(Unpromotable);
631                     }
632                 }
633
634                 // Special-case reborrows to be more like a copy of the reference.
635                 let mut place = place.as_ref();
636                 if let [proj_base @ .., ProjectionElem::Deref] = &place.projection {
637                     let base_ty = Place::ty_from(&place.base, proj_base, *self.body, self.tcx).ty;
638                     if let ty::Ref(..) = base_ty.kind {
639                         place = PlaceRef { base: &place.base, projection: proj_base };
640                     }
641                 }
642
643                 self.validate_place(place)?;
644
645                 // HACK(eddyb) this should compute the same thing as
646                 // `<HasMutInterior as Qualif>::in_projection` from
647                 // `check_consts::qualifs` but without recursion.
648                 let mut has_mut_interior = match place.base {
649                     PlaceBase::Local(local) => self.qualif_local::<qualifs::HasMutInterior>(*local),
650                     PlaceBase::Static(_) => false,
651                 };
652                 if has_mut_interior {
653                     let mut place_projection = place.projection;
654                     // FIXME(eddyb) use a forward loop instead of a reverse one.
655                     while let [proj_base @ .., elem] = place_projection {
656                         // FIXME(eddyb) this is probably excessive, with
657                         // the exception of `union` member accesses.
658                         let ty = Place::ty_from(place.base, proj_base, *self.body, self.tcx)
659                             .projection_ty(self.tcx, elem)
660                             .ty;
661                         if ty.is_freeze(self.tcx, self.param_env, DUMMY_SP) {
662                             has_mut_interior = false;
663                             break;
664                         }
665
666                         place_projection = proj_base;
667                     }
668                 }
669                 if has_mut_interior {
670                     return Err(Unpromotable);
671                 }
672
673                 Ok(())
674             }
675
676             Rvalue::Aggregate(_, ref operands) => {
677                 for o in operands {
678                     self.validate_operand(o)?;
679                 }
680
681                 Ok(())
682             }
683         }
684     }
685
686     fn validate_call(
687         &self,
688         callee: &Operand<'tcx>,
689         args: &[Operand<'tcx>],
690     ) -> Result<(), Unpromotable> {
691         let fn_ty = callee.ty(*self.body, self.tcx);
692
693         if !self.explicit && self.const_kind.is_none() {
694             if let ty::FnDef(def_id, _) = fn_ty.kind {
695                 // Never promote runtime `const fn` calls of
696                 // functions without `#[rustc_promotable]`.
697                 if !self.tcx.is_promotable_const_fn(def_id) {
698                     return Err(Unpromotable);
699                 }
700             }
701         }
702
703         let is_const_fn = match fn_ty.kind {
704             ty::FnDef(def_id, _) => {
705                 self.tcx.is_const_fn(def_id)
706                     || self.tcx.is_unstable_const_fn(def_id).is_some()
707                     || is_lang_panic_fn(self.tcx, self.def_id)
708             }
709             _ => false,
710         };
711         if !is_const_fn {
712             return Err(Unpromotable);
713         }
714
715         self.validate_operand(callee)?;
716         for arg in args {
717             self.validate_operand(arg)?;
718         }
719
720         Ok(())
721     }
722 }
723
724 // FIXME(eddyb) remove the differences for promotability in `static`, `const`, `const fn`.
725 pub fn validate_candidates(
726     tcx: TyCtxt<'tcx>,
727     body: ReadOnlyBodyAndCache<'_, 'tcx>,
728     def_id: DefId,
729     temps: &IndexVec<Local, TempState>,
730     candidates: &[Candidate],
731 ) -> Vec<Candidate> {
732     let mut validator = Validator { item: Item::new(tcx, def_id, body), temps, explicit: false };
733
734     candidates
735         .iter()
736         .copied()
737         .filter(|&candidate| {
738             validator.explicit = candidate.forces_explicit_promotion();
739
740             // FIXME(eddyb) also emit the errors for shuffle indices
741             // and `#[rustc_args_required_const]` arguments here.
742
743             let is_promotable = validator.validate_candidate(candidate).is_ok();
744             match candidate {
745                 Candidate::Argument { bb, index } if !is_promotable => {
746                     let span = body[bb].terminator().source_info.span;
747                     let msg = format!("argument {} is required to be a constant", index + 1);
748                     tcx.sess.span_err(span, &msg);
749                 }
750                 _ => (),
751             }
752
753             is_promotable
754         })
755         .collect()
756 }
757
758 struct Promoter<'a, 'tcx> {
759     tcx: TyCtxt<'tcx>,
760     source: &'a mut BodyAndCache<'tcx>,
761     promoted: BodyAndCache<'tcx>,
762     temps: &'a mut IndexVec<Local, TempState>,
763
764     /// If true, all nested temps are also kept in the
765     /// source MIR, not moved to the promoted MIR.
766     keep_original: bool,
767 }
768
769 impl<'a, 'tcx> Promoter<'a, 'tcx> {
770     fn new_block(&mut self) -> BasicBlock {
771         let span = self.promoted.span;
772         self.promoted.basic_blocks_mut().push(BasicBlockData {
773             statements: vec![],
774             terminator: Some(Terminator {
775                 source_info: SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE },
776                 kind: TerminatorKind::Return,
777             }),
778             is_cleanup: false,
779         })
780     }
781
782     fn assign(&mut self, dest: Local, rvalue: Rvalue<'tcx>, span: Span) {
783         let last = self.promoted.basic_blocks().last().unwrap();
784         let data = &mut self.promoted[last];
785         data.statements.push(Statement {
786             source_info: SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE },
787             kind: StatementKind::Assign(box (Place::from(dest), rvalue)),
788         });
789     }
790
791     fn is_temp_kind(&self, local: Local) -> bool {
792         self.source.local_kind(local) == LocalKind::Temp
793     }
794
795     /// Copies the initialization of this temp to the
796     /// promoted MIR, recursing through temps.
797     fn promote_temp(&mut self, temp: Local) -> Local {
798         let old_keep_original = self.keep_original;
799         let loc = match self.temps[temp] {
800             TempState::Defined { location, uses } if uses > 0 => {
801                 if uses > 1 {
802                     self.keep_original = true;
803                 }
804                 location
805             }
806             state => {
807                 span_bug!(self.promoted.span, "{:?} not promotable: {:?}", temp, state);
808             }
809         };
810         if !self.keep_original {
811             self.temps[temp] = TempState::PromotedOut;
812         }
813
814         let num_stmts = self.source[loc.block].statements.len();
815         let new_temp = self.promoted.local_decls.push(LocalDecl::new_temp(
816             self.source.local_decls[temp].ty,
817             self.source.local_decls[temp].source_info.span,
818         ));
819
820         debug!("promote({:?} @ {:?}/{:?}, {:?})", temp, loc, num_stmts, self.keep_original);
821
822         // First, take the Rvalue or Call out of the source MIR,
823         // or duplicate it, depending on keep_original.
824         if loc.statement_index < num_stmts {
825             let (mut rvalue, source_info) = {
826                 let statement = &mut self.source[loc.block].statements[loc.statement_index];
827                 let rhs = match statement.kind {
828                     StatementKind::Assign(box (_, ref mut rhs)) => rhs,
829                     _ => {
830                         span_bug!(
831                             statement.source_info.span,
832                             "{:?} is not an assignment",
833                             statement
834                         );
835                     }
836                 };
837
838                 (
839                     if self.keep_original {
840                         rhs.clone()
841                     } else {
842                         let unit = Rvalue::Aggregate(box AggregateKind::Tuple, vec![]);
843                         mem::replace(rhs, unit)
844                     },
845                     statement.source_info,
846                 )
847             };
848
849             self.visit_rvalue(&mut rvalue, loc);
850             self.assign(new_temp, rvalue, source_info.span);
851         } else {
852             let terminator = if self.keep_original {
853                 self.source[loc.block].terminator().clone()
854             } else {
855                 let terminator = self.source[loc.block].terminator_mut();
856                 let target = match terminator.kind {
857                     TerminatorKind::Call { destination: Some((_, target)), .. } => target,
858                     ref kind => {
859                         span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
860                     }
861                 };
862                 Terminator {
863                     source_info: terminator.source_info,
864                     kind: mem::replace(&mut terminator.kind, TerminatorKind::Goto { target }),
865                 }
866             };
867
868             match terminator.kind {
869                 TerminatorKind::Call { mut func, mut args, from_hir_call, .. } => {
870                     self.visit_operand(&mut func, loc);
871                     for arg in &mut args {
872                         self.visit_operand(arg, loc);
873                     }
874
875                     let last = self.promoted.basic_blocks().last().unwrap();
876                     let new_target = self.new_block();
877
878                     *self.promoted[last].terminator_mut() = Terminator {
879                         kind: TerminatorKind::Call {
880                             func,
881                             args,
882                             cleanup: None,
883                             destination: Some((Place::from(new_temp), new_target)),
884                             from_hir_call,
885                         },
886                         ..terminator
887                     };
888                 }
889                 ref kind => {
890                     span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
891                 }
892             };
893         };
894
895         self.keep_original = old_keep_original;
896         new_temp
897     }
898
899     fn promote_candidate(
900         mut self,
901         def_id: DefId,
902         candidate: Candidate,
903         next_promoted_id: usize,
904     ) -> Option<BodyAndCache<'tcx>> {
905         let mut operand = {
906             let promoted = &mut self.promoted;
907             let promoted_id = Promoted::new(next_promoted_id);
908             let tcx = self.tcx;
909             let mut promoted_place = |ty, span| {
910                 promoted.span = span;
911                 promoted.local_decls[RETURN_PLACE] = LocalDecl::new_return_place(ty, span);
912                 Place {
913                     base: PlaceBase::Static(box Static {
914                         kind: StaticKind::Promoted(
915                             promoted_id,
916                             InternalSubsts::identity_for_item(tcx, def_id),
917                         ),
918                         ty,
919                         def_id,
920                     }),
921                     projection: List::empty(),
922                 }
923             };
924             let (blocks, local_decls) = self.source.basic_blocks_and_local_decls_mut();
925             match candidate {
926                 Candidate::Ref(loc) => {
927                     let ref mut statement = blocks[loc.block].statements[loc.statement_index];
928                     match statement.kind {
929                         StatementKind::Assign(box (_, Rvalue::Ref(_, _, ref mut place))) => {
930                             // Use the underlying local for this (necessarily interior) borrow.
931                             let ty = place.base.ty(local_decls).ty;
932                             let span = statement.source_info.span;
933
934                             Operand::Move(Place {
935                                 base: mem::replace(&mut place.base, promoted_place(ty, span).base),
936                                 projection: List::empty(),
937                             })
938                         }
939                         _ => bug!(),
940                     }
941                 }
942                 Candidate::Repeat(loc) => {
943                     let ref mut statement = blocks[loc.block].statements[loc.statement_index];
944                     match statement.kind {
945                         StatementKind::Assign(box (_, Rvalue::Repeat(ref mut operand, _))) => {
946                             let ty = operand.ty(local_decls, self.tcx);
947                             let span = statement.source_info.span;
948                             mem::replace(operand, Operand::Copy(promoted_place(ty, span)))
949                         }
950                         _ => bug!(),
951                     }
952                 }
953                 Candidate::Argument { bb, index } => {
954                     let terminator = blocks[bb].terminator_mut();
955                     match terminator.kind {
956                         TerminatorKind::Call { ref mut args, .. } => {
957                             let ty = args[index].ty(local_decls, self.tcx);
958                             let span = terminator.source_info.span;
959                             let operand = Operand::Copy(promoted_place(ty, span));
960                             mem::replace(&mut args[index], operand)
961                         }
962                         // We expected a `TerminatorKind::Call` for which we'd like to promote an
963                         // argument. `qualify_consts` saw a `TerminatorKind::Call` here, but
964                         // we are seeing a `Goto`. That means that the `promote_temps` method
965                         // already promoted this call away entirely. This case occurs when calling
966                         // a function requiring a constant argument and as that constant value
967                         // providing a value whose computation contains another call to a function
968                         // requiring a constant argument.
969                         TerminatorKind::Goto { .. } => return None,
970                         _ => bug!(),
971                     }
972                 }
973             }
974         };
975
976         assert_eq!(self.new_block(), START_BLOCK);
977         self.visit_operand(
978             &mut operand,
979             Location { block: BasicBlock::new(0), statement_index: usize::MAX },
980         );
981
982         let span = self.promoted.span;
983         self.assign(RETURN_PLACE, Rvalue::Use(operand), span);
984         Some(self.promoted)
985     }
986 }
987
988 /// Replaces all temporaries with their promoted counterparts.
989 impl<'a, 'tcx> MutVisitor<'tcx> for Promoter<'a, 'tcx> {
990     fn tcx(&self) -> TyCtxt<'tcx> {
991         self.tcx
992     }
993
994     fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) {
995         if self.is_temp_kind(*local) {
996             *local = self.promote_temp(*local);
997         }
998     }
999
1000     fn process_projection_elem(&mut self, elem: &PlaceElem<'tcx>) -> Option<PlaceElem<'tcx>> {
1001         match elem {
1002             PlaceElem::Index(local) if self.is_temp_kind(*local) => {
1003                 Some(PlaceElem::Index(self.promote_temp(*local)))
1004             }
1005             _ => None,
1006         }
1007     }
1008 }
1009
1010 pub fn promote_candidates<'tcx>(
1011     def_id: DefId,
1012     body: &mut BodyAndCache<'tcx>,
1013     tcx: TyCtxt<'tcx>,
1014     mut temps: IndexVec<Local, TempState>,
1015     candidates: Vec<Candidate>,
1016 ) -> IndexVec<Promoted, BodyAndCache<'tcx>> {
1017     // Visit candidates in reverse, in case they're nested.
1018     debug!("promote_candidates({:?})", candidates);
1019
1020     let mut promotions = IndexVec::new();
1021
1022     for candidate in candidates.into_iter().rev() {
1023         match candidate {
1024             Candidate::Repeat(Location { block, statement_index })
1025             | Candidate::Ref(Location { block, statement_index }) => {
1026                 match &body[block].statements[statement_index].kind {
1027                     StatementKind::Assign(box (place, _)) => {
1028                         if let Some(local) = place.as_local() {
1029                             if temps[local] == TempState::PromotedOut {
1030                                 // Already promoted.
1031                                 continue;
1032                             }
1033                         }
1034                     }
1035                     _ => {}
1036                 }
1037             }
1038             Candidate::Argument { .. } => {}
1039         }
1040
1041         // Declare return place local so that `mir::Body::new` doesn't complain.
1042         let initial_locals =
1043             iter::once(LocalDecl::new_return_place(tcx.types.never, body.span)).collect();
1044
1045         let promoter = Promoter {
1046             promoted: BodyAndCache::new(Body::new(
1047                 IndexVec::new(),
1048                 // FIXME: maybe try to filter this to avoid blowing up
1049                 // memory usage?
1050                 body.source_scopes.clone(),
1051                 initial_locals,
1052                 IndexVec::new(),
1053                 0,
1054                 vec![],
1055                 body.span,
1056                 vec![],
1057                 body.generator_kind,
1058             )),
1059             tcx,
1060             source: body,
1061             temps: &mut temps,
1062             keep_original: false,
1063         };
1064
1065         //FIXME(oli-obk): having a `maybe_push()` method on `IndexVec` might be nice
1066         if let Some(promoted) = promoter.promote_candidate(def_id, candidate, promotions.len()) {
1067             promotions.push(promoted);
1068         }
1069     }
1070
1071     // Eliminate assignments to, and drops of promoted temps.
1072     let promoted = |index: Local| temps[index] == TempState::PromotedOut;
1073     for block in body.basic_blocks_mut() {
1074         block.statements.retain(|statement| match &statement.kind {
1075             StatementKind::Assign(box (place, _)) => {
1076                 if let Some(index) = place.as_local() {
1077                     !promoted(index)
1078                 } else {
1079                     true
1080                 }
1081             }
1082             StatementKind::StorageLive(index) | StatementKind::StorageDead(index) => {
1083                 !promoted(*index)
1084             }
1085             _ => true,
1086         });
1087         let terminator = block.terminator_mut();
1088         match &terminator.kind {
1089             TerminatorKind::Drop { location: place, target, .. } => {
1090                 if let Some(index) = place.as_local() {
1091                     if promoted(index) {
1092                         terminator.kind = TerminatorKind::Goto { target: *target };
1093                     }
1094                 }
1095             }
1096             _ => {}
1097         }
1098     }
1099
1100     promotions
1101 }
1102
1103 /// This function returns `true` if the `const_in_array_repeat_expressions` feature attribute should
1104 /// be suggested. This function is probably quite expensive, it shouldn't be run in the happy path.
1105 /// Feature attribute should be suggested if `operand` can be promoted and the feature is not
1106 /// enabled.
1107 crate fn should_suggest_const_in_array_repeat_expressions_attribute<'tcx>(
1108     tcx: TyCtxt<'tcx>,
1109     mir_def_id: DefId,
1110     body: ReadOnlyBodyAndCache<'_, 'tcx>,
1111     operand: &Operand<'tcx>,
1112 ) -> bool {
1113     let mut rpo = traversal::reverse_postorder(&body);
1114     let (temps, _) = collect_temps_and_candidates(tcx, &body, &mut rpo);
1115     let validator =
1116         Validator { item: Item::new(tcx, mir_def_id, body), temps: &temps, explicit: false };
1117
1118     let should_promote = validator.validate_operand(operand).is_ok();
1119     let feature_flag = tcx.features().const_in_array_repeat_expressions;
1120     debug!(
1121         "should_suggest_const_in_array_repeat_expressions_flag: mir_def_id={:?} \
1122             should_promote={:?} feature_flag={:?}",
1123         mir_def_id, should_promote, feature_flag
1124     );
1125     should_promote && !feature_flag
1126 }