]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/qualify_consts.rs
qualify-const remove cannot mutate statics in initializer of another static error
[rust.git] / src / librustc_mir / transform / qualify_consts.rs
1 //! A pass that qualifies constness of temporaries in constants,
2 //! static initializers and functions and also drives promotion.
3 //!
4 //! The Qualif flags below can be used to also provide better
5 //! diagnostics as to why a constant rvalue wasn't promoted.
6
7 use rustc_index::bit_set::BitSet;
8 use rustc_index::vec::IndexVec;
9 use rustc_target::spec::abi::Abi;
10 use rustc::hir;
11 use rustc::hir::def_id::DefId;
12 use rustc::traits::{self, TraitEngine};
13 use rustc::ty::{self, TyCtxt, Ty, TypeFoldable};
14 use rustc::ty::cast::CastTy;
15 use rustc::ty::query::Providers;
16 use rustc::mir::*;
17 use rustc::mir::interpret::ConstValue;
18 use rustc::mir::visit::{PlaceContext, Visitor, MutatingUseContext, NonMutatingUseContext};
19 use rustc::middle::lang_items;
20 use rustc::session::config::nightly_options;
21 use syntax::feature_gate::{emit_feature_err, GateIssue};
22 use syntax::symbol::sym;
23 use syntax_pos::{Span, DUMMY_SP};
24
25 use std::borrow::Cow;
26 use std::cell::Cell;
27 use std::fmt;
28 use std::ops::{Deref, Index, IndexMut};
29 use std::usize;
30
31 use rustc::hir::HirId;
32 use crate::transform::{MirPass, MirSource};
33 use crate::transform::check_consts::ops::{self, NonConstOp};
34
35 /// What kind of item we are in.
36 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
37 enum Mode {
38     /// A `static` item.
39     Static,
40     /// A `static mut` item.
41     StaticMut,
42     /// A `const fn` item.
43     ConstFn,
44     /// A `const` item or an anonymous constant (e.g. in array lengths).
45     Const,
46     /// Other type of `fn`.
47     NonConstFn,
48 }
49
50 impl Mode {
51     /// Determine whether we have to do full const-checking because syntactically, we
52     /// are required to be "const".
53     #[inline]
54     fn requires_const_checking(self) -> bool {
55         self != Mode::NonConstFn
56     }
57 }
58
59 impl fmt::Display for Mode {
60     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61         match *self {
62             Mode::Const => write!(f, "constant"),
63             Mode::Static | Mode::StaticMut => write!(f, "static"),
64             Mode::ConstFn => write!(f, "constant function"),
65             Mode::NonConstFn => write!(f, "function")
66         }
67     }
68 }
69
70 const QUALIF_COUNT: usize = 2;
71
72 // FIXME(eddyb) once we can use const generics, replace this array with
73 // something like `IndexVec` but for fixed-size arrays (`IndexArray`?).
74 #[derive(Copy, Clone, Default)]
75 struct PerQualif<T>([T; QUALIF_COUNT]);
76
77 impl<T: Clone> PerQualif<T> {
78     fn new(x: T) -> Self {
79         PerQualif([x.clone(), x])
80     }
81 }
82
83 impl<T> PerQualif<T> {
84     fn as_mut(&mut self) -> PerQualif<&mut T> {
85         let [x0, x1] = &mut self.0;
86         PerQualif([x0, x1])
87     }
88
89     fn zip<U>(self, other: PerQualif<U>) -> PerQualif<(T, U)> {
90         let [x0, x1] = self.0;
91         let [y0, y1] = other.0;
92         PerQualif([(x0, y0), (x1, y1)])
93     }
94 }
95
96 impl PerQualif<bool> {
97     fn encode_to_bits(self) -> u8 {
98         self.0.iter().enumerate().fold(0, |bits, (i, &qualif)| {
99             bits | ((qualif as u8) << i)
100         })
101     }
102
103     fn decode_from_bits(bits: u8) -> Self {
104         let mut qualifs = Self::default();
105         for (i, qualif) in qualifs.0.iter_mut().enumerate() {
106             *qualif = (bits & (1 << i)) != 0;
107         }
108         qualifs
109     }
110 }
111
112 impl<Q: Qualif, T> Index<Q> for PerQualif<T> {
113     type Output = T;
114
115     fn index(&self, _: Q) -> &T {
116         &self.0[Q::IDX]
117     }
118 }
119
120 impl<Q: Qualif, T> IndexMut<Q> for PerQualif<T> {
121     fn index_mut(&mut self, _: Q) -> &mut T {
122         &mut self.0[Q::IDX]
123     }
124 }
125
126 struct ConstCx<'a, 'tcx> {
127     tcx: TyCtxt<'tcx>,
128     param_env: ty::ParamEnv<'tcx>,
129     mode: Mode,
130     body: &'a Body<'tcx>,
131
132     per_local: PerQualif<BitSet<Local>>,
133 }
134
135 impl<'a, 'tcx> ConstCx<'a, 'tcx> {
136     fn is_const_panic_fn(&self, def_id: DefId) -> bool {
137         Some(def_id) == self.tcx.lang_items().panic_fn() ||
138         Some(def_id) == self.tcx.lang_items().begin_panic_fn()
139     }
140 }
141
142 #[derive(Copy, Clone, Debug)]
143 enum ValueSource<'a, 'tcx> {
144     Rvalue(&'a Rvalue<'tcx>),
145     DropAndReplace(&'a Operand<'tcx>),
146     Call {
147         callee: &'a Operand<'tcx>,
148         args: &'a [Operand<'tcx>],
149         return_ty: Ty<'tcx>,
150     },
151 }
152
153 /// A "qualif"(-ication) is a way to look for something "bad" in the MIR that would disqualify some
154 /// code for promotion or prevent it from evaluating at compile time. So `return true` means
155 /// "I found something bad, no reason to go on searching". `false` is only returned if we
156 /// definitely cannot find anything bad anywhere.
157 ///
158 /// The default implementations proceed structurally.
159 trait Qualif {
160     const IDX: usize;
161
162     /// Return the qualification that is (conservatively) correct for any value
163     /// of the type, or `None` if the qualification is not value/type-based.
164     fn in_any_value_of_ty(_cx: &ConstCx<'_, 'tcx>, _ty: Ty<'tcx>) -> Option<bool> {
165         None
166     }
167
168     /// Return a mask for the qualification, given a type. This is `false` iff
169     /// no value of that type can have the qualification.
170     fn mask_for_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
171         Self::in_any_value_of_ty(cx, ty).unwrap_or(true)
172     }
173
174     fn in_local(cx: &ConstCx<'_, '_>, local: Local) -> bool {
175         cx.per_local.0[Self::IDX].contains(local)
176     }
177
178     fn in_static(_cx: &ConstCx<'_, 'tcx>, _static: &Static<'tcx>) -> bool {
179         // FIXME(eddyb) should we do anything here for value properties?
180         false
181     }
182
183     fn in_projection_structurally(
184         cx: &ConstCx<'_, 'tcx>,
185         place: PlaceRef<'_, 'tcx>,
186     ) -> bool {
187         if let [proj_base @ .., elem] = place.projection {
188             let base_qualif = Self::in_place(cx, PlaceRef {
189                 base: place.base,
190                 projection: proj_base,
191             });
192             let qualif = base_qualif && Self::mask_for_ty(
193                 cx,
194                 Place::ty_from(place.base, proj_base, cx.body, cx.tcx)
195                     .projection_ty(cx.tcx, elem)
196                     .ty,
197             );
198             match elem {
199                 ProjectionElem::Deref |
200                 ProjectionElem::Subslice { .. } |
201                 ProjectionElem::Field(..) |
202                 ProjectionElem::ConstantIndex { .. } |
203                 ProjectionElem::Downcast(..) => qualif,
204
205                 // FIXME(eddyb) shouldn't this be masked *after* including the
206                 // index local? Then again, it's `usize` which is neither
207                 // `HasMutInterior` nor `NeedsDrop`.
208                 ProjectionElem::Index(local) => qualif || Self::in_local(cx, *local),
209             }
210         } else {
211             bug!("This should be called if projection is not empty");
212         }
213     }
214
215     fn in_projection(
216         cx: &ConstCx<'_, 'tcx>,
217         place: PlaceRef<'_, 'tcx>,
218     ) -> bool {
219         Self::in_projection_structurally(cx, place)
220     }
221
222     fn in_place(cx: &ConstCx<'_, 'tcx>, place: PlaceRef<'_, 'tcx>) -> bool {
223         match place {
224             PlaceRef {
225                 base: PlaceBase::Local(local),
226                 projection: [],
227             } => Self::in_local(cx, *local),
228             PlaceRef {
229                 base: PlaceBase::Static(box Static {
230                     kind: StaticKind::Promoted(..),
231                     ..
232                 }),
233                 projection: [],
234             } => bug!("qualifying already promoted MIR"),
235             PlaceRef {
236                 base: PlaceBase::Static(static_),
237                 projection: [],
238             } => {
239                 Self::in_static(cx, static_)
240             },
241             PlaceRef {
242                 base: _,
243                 projection: [.., _],
244             } => Self::in_projection(cx, place),
245         }
246     }
247
248     fn in_operand(cx: &ConstCx<'_, 'tcx>, operand: &Operand<'tcx>) -> bool {
249         match *operand {
250             Operand::Copy(ref place) |
251             Operand::Move(ref place) => Self::in_place(cx, place.as_ref()),
252
253             Operand::Constant(ref constant) => {
254                 if let ConstValue::Unevaluated(def_id, _) = constant.literal.val {
255                     // Don't peek inside trait associated constants.
256                     if cx.tcx.trait_of_item(def_id).is_some() {
257                         Self::in_any_value_of_ty(cx, constant.literal.ty).unwrap_or(false)
258                     } else {
259                         let bits = cx.tcx.at(constant.span).mir_const_qualif(def_id);
260
261                         let qualif = PerQualif::decode_from_bits(bits).0[Self::IDX];
262
263                         // Just in case the type is more specific than
264                         // the definition, e.g., impl associated const
265                         // with type parameters, take it into account.
266                         qualif && Self::mask_for_ty(cx, constant.literal.ty)
267                     }
268                 } else {
269                     false
270                 }
271             }
272         }
273     }
274
275     fn in_rvalue_structurally(cx: &ConstCx<'_, 'tcx>, rvalue: &Rvalue<'tcx>) -> bool {
276         match *rvalue {
277             Rvalue::NullaryOp(..) => false,
278
279             Rvalue::Discriminant(ref place) |
280             Rvalue::Len(ref place) => Self::in_place(cx, place.as_ref()),
281
282             Rvalue::Use(ref operand) |
283             Rvalue::Repeat(ref operand, _) |
284             Rvalue::UnaryOp(_, ref operand) |
285             Rvalue::Cast(_, ref operand, _) => Self::in_operand(cx, operand),
286
287             Rvalue::BinaryOp(_, ref lhs, ref rhs) |
288             Rvalue::CheckedBinaryOp(_, ref lhs, ref rhs) => {
289                 Self::in_operand(cx, lhs) || Self::in_operand(cx, rhs)
290             }
291
292             Rvalue::Ref(_, _, ref place) => {
293                 // Special-case reborrows to be more like a copy of the reference.
294                 if let &[ref proj_base @ .., elem] = place.projection.as_ref() {
295                     if ProjectionElem::Deref == elem {
296                         let base_ty = Place::ty_from(&place.base, proj_base, cx.body, cx.tcx).ty;
297                         if let ty::Ref(..) = base_ty.kind {
298                             return Self::in_place(cx, PlaceRef {
299                                 base: &place.base,
300                                 projection: proj_base,
301                             });
302                         }
303                     }
304                 }
305
306                 Self::in_place(cx, place.as_ref())
307             }
308
309             Rvalue::Aggregate(_, ref operands) => {
310                 operands.iter().any(|o| Self::in_operand(cx, o))
311             }
312         }
313     }
314
315     fn in_rvalue(cx: &ConstCx<'_, 'tcx>, rvalue: &Rvalue<'tcx>) -> bool {
316         Self::in_rvalue_structurally(cx, rvalue)
317     }
318
319     fn in_call(
320         cx: &ConstCx<'_, 'tcx>,
321         _callee: &Operand<'tcx>,
322         _args: &[Operand<'tcx>],
323         return_ty: Ty<'tcx>,
324     ) -> bool {
325         // Be conservative about the returned value of a const fn.
326         Self::in_any_value_of_ty(cx, return_ty).unwrap_or(false)
327     }
328
329     fn in_value(cx: &ConstCx<'_, 'tcx>, source: ValueSource<'_, 'tcx>) -> bool {
330         match source {
331             ValueSource::Rvalue(rvalue) => Self::in_rvalue(cx, rvalue),
332             ValueSource::DropAndReplace(source) => Self::in_operand(cx, source),
333             ValueSource::Call { callee, args, return_ty } => {
334                 Self::in_call(cx, callee, args, return_ty)
335             }
336         }
337     }
338 }
339
340 /// Constant containing interior mutability (`UnsafeCell<T>`).
341 /// This must be ruled out to make sure that evaluating the constant at compile-time
342 /// and at *any point* during the run-time would produce the same result. In particular,
343 /// promotion of temporaries must not change program behavior; if the promoted could be
344 /// written to, that would be a problem.
345 struct HasMutInterior;
346
347 impl Qualif for HasMutInterior {
348     const IDX: usize = 0;
349
350     fn in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> Option<bool> {
351         Some(!ty.is_freeze(cx.tcx, cx.param_env, DUMMY_SP))
352     }
353
354     fn in_rvalue(cx: &ConstCx<'_, 'tcx>, rvalue: &Rvalue<'tcx>) -> bool {
355         match *rvalue {
356             // Returning `true` for `Rvalue::Ref` indicates the borrow isn't
357             // allowed in constants (and the `Checker` will error), and/or it
358             // won't be promoted, due to `&mut ...` or interior mutability.
359             Rvalue::Ref(_, kind, ref place) => {
360                 let ty = place.ty(cx.body, cx.tcx).ty;
361
362                 if let BorrowKind::Mut { .. } = kind {
363                     // In theory, any zero-sized value could be borrowed
364                     // mutably without consequences. However, only &mut []
365                     // is allowed right now, and only in functions.
366                     if cx.mode == Mode::StaticMut {
367                         // Inside a `static mut`, &mut [...] is also allowed.
368                         match ty.kind {
369                             ty::Array(..) | ty::Slice(_) => {}
370                             _ => return true,
371                         }
372                     } else if let ty::Array(_, len) = ty.kind {
373                         // FIXME(eddyb) the `cx.mode == Mode::NonConstFn` condition
374                         // seems unnecessary, given that this is merely a ZST.
375                         match len.try_eval_usize(cx.tcx, cx.param_env) {
376                             Some(0) if cx.mode == Mode::NonConstFn => {},
377                             _ => return true,
378                         }
379                     } else {
380                         return true;
381                     }
382                 }
383             }
384
385             Rvalue::Aggregate(ref kind, _) => {
386                 if let AggregateKind::Adt(def, ..) = **kind {
387                     if Some(def.did) == cx.tcx.lang_items().unsafe_cell_type() {
388                         let ty = rvalue.ty(cx.body, cx.tcx);
389                         assert_eq!(Self::in_any_value_of_ty(cx, ty), Some(true));
390                         return true;
391                     }
392                 }
393             }
394
395             _ => {}
396         }
397
398         Self::in_rvalue_structurally(cx, rvalue)
399     }
400 }
401
402 /// Constant containing an ADT that implements `Drop`.
403 /// This must be ruled out (a) because we cannot run `Drop` during compile-time
404 /// as that might not be a `const fn`, and (b) because implicit promotion would
405 /// remove side-effects that occur as part of dropping that value.
406 struct NeedsDrop;
407
408 impl Qualif for NeedsDrop {
409     const IDX: usize = 1;
410
411     fn in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> Option<bool> {
412         Some(ty.needs_drop(cx.tcx, cx.param_env))
413     }
414
415     fn in_rvalue(cx: &ConstCx<'_, 'tcx>, rvalue: &Rvalue<'tcx>) -> bool {
416         if let Rvalue::Aggregate(ref kind, _) = *rvalue {
417             if let AggregateKind::Adt(def, ..) = **kind {
418                 if def.has_dtor(cx.tcx) {
419                     return true;
420                 }
421             }
422         }
423
424         Self::in_rvalue_structurally(cx, rvalue)
425     }
426 }
427
428 // Ensure the `IDX` values are sequential (`0..QUALIF_COUNT`).
429 macro_rules! static_assert_seq_qualifs {
430     ($i:expr => $first:ident $(, $rest:ident)*) => {
431         static_assert!({
432             static_assert_seq_qualifs!($i + 1 => $($rest),*);
433
434             $first::IDX == $i
435         });
436     };
437     ($i:expr =>) => {
438         static_assert!(QUALIF_COUNT == $i);
439     };
440 }
441 static_assert_seq_qualifs!(
442     0 => HasMutInterior, NeedsDrop
443 );
444
445 impl ConstCx<'_, 'tcx> {
446     fn qualifs_in_any_value_of_ty(&self, ty: Ty<'tcx>) -> PerQualif<bool> {
447         let mut qualifs = PerQualif::default();
448         qualifs[HasMutInterior] = HasMutInterior::in_any_value_of_ty(self, ty).unwrap_or(false);
449         qualifs[NeedsDrop] = NeedsDrop::in_any_value_of_ty(self, ty).unwrap_or(false);
450         qualifs
451     }
452
453     fn qualifs_in_local(&self, local: Local) -> PerQualif<bool> {
454         let mut qualifs = PerQualif::default();
455         qualifs[HasMutInterior] = HasMutInterior::in_local(self, local);
456         qualifs[NeedsDrop] = NeedsDrop::in_local(self, local);
457         qualifs
458     }
459
460     fn qualifs_in_value(&self, source: ValueSource<'_, 'tcx>) -> PerQualif<bool> {
461         let mut qualifs = PerQualif::default();
462         qualifs[HasMutInterior] = HasMutInterior::in_value(self, source);
463         qualifs[NeedsDrop] = NeedsDrop::in_value(self, source);
464         qualifs
465     }
466 }
467
468 /// Checks MIR for being admissible as a compile-time constant, using `ConstCx`
469 /// for value qualifications, and accumulates writes of
470 /// rvalue/call results to locals, in `local_qualif`.
471 /// It also records candidates for promotion in `promotion_candidates`,
472 /// both in functions and const/static items.
473 struct Checker<'a, 'tcx> {
474     cx: ConstCx<'a, 'tcx>,
475
476     span: Span,
477     def_id: DefId,
478
479     /// If `true`, do not emit errors to the user, merely collect them in `errors`.
480     suppress_errors: bool,
481     errors: Vec<(Span, String)>,
482 }
483
484 macro_rules! unleash_miri {
485     ($this:expr) => {{
486         if $this.tcx.sess.opts.debugging_opts.unleash_the_miri_inside_of_you {
487             if $this.mode.requires_const_checking() && !$this.suppress_errors {
488                 $this.tcx.sess.span_warn($this.span, "skipping const checks");
489             }
490             return;
491         }
492     }}
493 }
494
495 impl Deref for Checker<'a, 'tcx> {
496     type Target = ConstCx<'a, 'tcx>;
497
498     fn deref(&self) -> &Self::Target {
499         &self.cx
500     }
501 }
502
503 impl<'a, 'tcx> Checker<'a, 'tcx> {
504     fn new(tcx: TyCtxt<'tcx>, def_id: DefId, body: &'a Body<'tcx>, mode: Mode) -> Self {
505         assert!(def_id.is_local());
506
507         let param_env = tcx.param_env(def_id);
508
509         let mut cx = ConstCx {
510             tcx,
511             param_env,
512             mode,
513             body,
514             per_local: PerQualif::new(BitSet::new_empty(body.local_decls.len())),
515         };
516
517         for (local, decl) in body.local_decls.iter_enumerated() {
518             if let LocalKind::Arg = body.local_kind(local) {
519                 let qualifs = cx.qualifs_in_any_value_of_ty(decl.ty);
520                 for (per_local, qualif) in &mut cx.per_local.as_mut().zip(qualifs).0 {
521                     if *qualif {
522                         per_local.insert(local);
523                     }
524                 }
525             }
526         }
527
528         Checker {
529             cx,
530             span: body.span,
531             def_id,
532             errors: vec![],
533             suppress_errors: false,
534         }
535     }
536
537     // FIXME(eddyb) we could split the errors into meaningful
538     // categories, but enabling full miri would make that
539     // slightly pointless (even with feature-gating).
540     fn not_const(&mut self, op: impl NonConstOp) {
541         unleash_miri!(self);
542         if self.mode.requires_const_checking() && !self.suppress_errors {
543             self.record_error(op);
544             let mut err = struct_span_err!(
545                 self.tcx.sess,
546                 self.span,
547                 E0019,
548                 "{} contains unimplemented expression type",
549                 self.mode
550             );
551             if self.tcx.sess.teach(&err.get_code().unwrap()) {
552                 err.note("A function call isn't allowed in the const's initialization expression \
553                           because the expression's value must be known at compile-time.");
554                 err.note("Remember: you can't use a function call inside a const's initialization \
555                           expression! However, you can use it anywhere else.");
556             }
557             err.emit();
558         }
559     }
560
561     fn record_error(&mut self, op: impl NonConstOp) {
562         self.record_error_spanned(op, self.span);
563     }
564
565     fn record_error_spanned(&mut self, op: impl NonConstOp, span: Span) {
566         self.errors.push((span, format!("{:?}", op)));
567     }
568
569     /// Assigns an rvalue/call qualification to the given destination.
570     fn assign(&mut self, dest: &Place<'tcx>, source: ValueSource<'_, 'tcx>, location: Location) {
571         trace!("assign: {:?} <- {:?}", dest, source);
572
573         let mut qualifs = self.qualifs_in_value(source);
574
575         match source {
576             ValueSource::Rvalue(&Rvalue::Ref(_, kind, _)) => {
577                 // Getting `true` from `HasMutInterior::in_rvalue` means
578                 // the borrowed place is disallowed from being borrowed,
579                 // due to either a mutable borrow (with some exceptions),
580                 // or an shared borrow of a value with interior mutability.
581                 // Then `HasMutInterior` is cleared
582                 // to avoid duplicate errors (e.g. from reborrowing).
583                 if qualifs[HasMutInterior] {
584                     qualifs[HasMutInterior] = false;
585
586                     debug!("suppress_errors: {}", self.suppress_errors);
587                     if self.mode.requires_const_checking() && !self.suppress_errors {
588                         if !self.tcx.sess.opts.debugging_opts.unleash_the_miri_inside_of_you {
589                             self.record_error(ops::MutBorrow(kind));
590                             if let BorrowKind::Mut { .. } = kind {
591                                 let mut err = struct_span_err!(self.tcx.sess,  self.span, E0017,
592                                                                "references in {}s may only refer \
593                                                                 to immutable values", self.mode);
594                                 err.span_label(self.span, format!("{}s require immutable values",
595                                                                     self.mode));
596                                 if self.tcx.sess.teach(&err.get_code().unwrap()) {
597                                     err.note("References in statics and constants may only refer \
598                                               to immutable values.\n\n\
599                                               Statics are shared everywhere, and if they refer to \
600                                               mutable data one might violate memory safety since \
601                                               holding multiple mutable references to shared data \
602                                               is not allowed.\n\n\
603                                               If you really want global mutable state, try using \
604                                               static mut or a global UnsafeCell.");
605                                 }
606                                 err.emit();
607                             } else {
608                                 span_err!(self.tcx.sess, self.span, E0492,
609                                           "cannot borrow a constant which may contain \
610                                            interior mutability, create a static instead");
611                             }
612                         }
613                     }
614                 }
615             },
616             _ => {},
617         }
618
619         let mut dest_projection = &dest.projection[..];
620         let index = loop {
621             match (&dest.base, dest_projection) {
622                 // We treat all locals equal in constants
623                 (&PlaceBase::Local(index), []) => break index,
624                 // projections are transparent for assignments
625                 // we qualify the entire destination at once, even if just a field would have
626                 // stricter qualification
627                 (base, [proj_base @ .., _]) => {
628                     // Catch more errors in the destination. `visit_place` also checks various
629                     // projection rules like union field access and raw pointer deref
630                     let context = PlaceContext::MutatingUse(MutatingUseContext::Store);
631                     self.visit_place_base(base, context, location);
632                     self.visit_projection(base, dest_projection, context, location);
633                     dest_projection = proj_base;
634                 },
635                 (&PlaceBase::Static(box Static {
636                     kind: StaticKind::Promoted(..),
637                     ..
638                 }), []) => bug!("promoteds don't exist yet during promotion"),
639                 (&PlaceBase::Static(box Static{ kind: _, .. }), []) => {
640                     // Catch more errors in the destination. `visit_place` also checks that we
641                     // do not try to access statics from constants or try to mutate statics
642                     let context = PlaceContext::MutatingUse(MutatingUseContext::Store);
643                     self.visit_place_base(&dest.base, context, location);
644                     return;
645                 }
646             }
647         };
648
649         let kind = self.body.local_kind(index);
650         debug!("store to {:?} {:?}", kind, index);
651
652         // this is overly restrictive, because even full assignments do not clear the qualif
653         // While we could special case full assignments, this would be inconsistent with
654         // aggregates where we overwrite all fields via assignments, which would not get
655         // that feature.
656         for (per_local, qualif) in &mut self.cx.per_local.as_mut().zip(qualifs).0 {
657             if *qualif {
658                 per_local.insert(index);
659             }
660         }
661     }
662
663     /// Check a whole const, static initializer or const fn.
664     fn check_const(&mut self) -> u8 {
665         use crate::transform::check_consts as new_checker;
666
667         debug!("const-checking {} {:?}", self.mode, self.def_id);
668
669         // FIXME: Also use the new validator when features that require it (e.g. `const_if`) are
670         // enabled.
671         let use_new_validator = self.tcx.sess.opts.debugging_opts.unleash_the_miri_inside_of_you;
672         if use_new_validator {
673             debug!("Using dataflow-based const validator");
674         }
675
676         let item = new_checker::Item::new(self.tcx, self.def_id, self.body);
677         let mut validator = new_checker::validation::Validator::new(&item);
678
679         validator.suppress_errors = !use_new_validator;
680         self.suppress_errors = use_new_validator;
681
682         let body = self.body;
683
684         let mut seen_blocks = BitSet::new_empty(body.basic_blocks().len());
685         let mut bb = START_BLOCK;
686         loop {
687             seen_blocks.insert(bb.index());
688
689             self.visit_basic_block_data(bb, &body[bb]);
690             validator.visit_basic_block_data(bb, &body[bb]);
691
692             let target = match body[bb].terminator().kind {
693                 TerminatorKind::Goto { target } |
694                 TerminatorKind::FalseUnwind { real_target: target, .. } |
695                 TerminatorKind::Drop { target, .. } |
696                 TerminatorKind::DropAndReplace { target, .. } |
697                 TerminatorKind::Assert { target, .. } |
698                 TerminatorKind::Call { destination: Some((_, target)), .. } => {
699                     Some(target)
700                 }
701
702                 // Non-terminating calls cannot produce any value.
703                 TerminatorKind::Call { destination: None, .. } => {
704                     break;
705                 }
706
707                 TerminatorKind::SwitchInt {..} |
708                 TerminatorKind::Resume |
709                 TerminatorKind::Abort |
710                 TerminatorKind::GeneratorDrop |
711                 TerminatorKind::Yield { .. } |
712                 TerminatorKind::Unreachable |
713                 TerminatorKind::FalseEdges { .. } => None,
714
715                 TerminatorKind::Return => {
716                     break;
717                 }
718             };
719
720             match target {
721                 // No loops allowed.
722                 Some(target) if !seen_blocks.contains(target.index()) => {
723                     bb = target;
724                 }
725                 _ => {
726                     self.not_const(ops::Loop);
727                     validator.check_op(ops::Loop);
728                     break;
729                 }
730             }
731         }
732
733         // The new validation pass should agree with the old when running on simple const bodies
734         // (e.g. no `if` or `loop`).
735         if !use_new_validator {
736             let mut new_errors = validator.take_errors();
737
738             // FIXME: each checker sometimes emits the same error with the same span twice in a row.
739             self.errors.dedup();
740             new_errors.dedup();
741
742             if self.errors != new_errors {
743                 validator_mismatch(
744                     self.tcx,
745                     body,
746                     std::mem::replace(&mut self.errors, vec![]),
747                     new_errors,
748                 );
749             }
750         }
751
752         self.qualifs_in_local(RETURN_PLACE).encode_to_bits()
753     }
754 }
755
756 impl<'a, 'tcx> Visitor<'tcx> for Checker<'a, 'tcx> {
757     fn visit_place_base(
758         &mut self,
759         place_base: &PlaceBase<'tcx>,
760         context: PlaceContext,
761         location: Location,
762     ) {
763         self.super_place_base(place_base, context, location);
764         match place_base {
765             PlaceBase::Local(_) => {}
766             PlaceBase::Static(box Static{ kind: StaticKind::Promoted(_, _), .. }) => {
767                 unreachable!()
768             }
769             PlaceBase::Static(box Static{ kind: StaticKind::Static, def_id, .. }) => {
770                 if self.tcx
771                         .get_attrs(*def_id)
772                         .iter()
773                         .any(|attr| attr.check_name(sym::thread_local)) {
774                     if self.mode.requires_const_checking() && !self.suppress_errors {
775                         self.record_error(ops::ThreadLocalAccess);
776                         span_err!(self.tcx.sess, self.span, E0625,
777                                     "thread-local statics cannot be \
778                                     accessed at compile-time");
779                     }
780                     return;
781                 }
782
783                 // Only allow statics (not consts) to refer to other statics.
784                 if self.mode == Mode::Static || self.mode == Mode::StaticMut {
785                     return;
786                 }
787                 unleash_miri!(self);
788
789                 if self.mode.requires_const_checking() && !self.suppress_errors {
790                     self.record_error(ops::StaticAccess);
791                     let mut err = struct_span_err!(self.tcx.sess, self.span, E0013,
792                                                     "{}s cannot refer to statics, use \
793                                                     a constant instead", self.mode);
794                     if self.tcx.sess.teach(&err.get_code().unwrap()) {
795                         err.note(
796                             "Static and const variables can refer to other const variables. \
797                                 But a const variable cannot refer to a static variable."
798                         );
799                         err.help(
800                             "To fix this, the value can be extracted as a const and then used."
801                         );
802                     }
803                     err.emit()
804                 }
805             }
806         }
807     }
808
809     fn visit_projection_elem(
810         &mut self,
811         place_base: &PlaceBase<'tcx>,
812         proj_base: &[PlaceElem<'tcx>],
813         elem: &PlaceElem<'tcx>,
814         context: PlaceContext,
815         location: Location,
816     ) {
817         debug!(
818             "visit_projection_elem: place_base={:?} proj_base={:?} elem={:?} \
819             context={:?} location={:?}",
820             place_base,
821             proj_base,
822             elem,
823             context,
824             location,
825         );
826
827         self.super_projection_elem(place_base, proj_base, elem, context, location);
828
829         match elem {
830             ProjectionElem::Deref => {
831                 if context.is_mutating_use() {
832                     // `not_const` errors out in const contexts
833                     self.not_const(ops::MutDeref)
834                 }
835                 let base_ty = Place::ty_from(place_base, proj_base, self.body, self.tcx).ty;
836                 match self.mode {
837                     Mode::NonConstFn => {}
838                     _ if self.suppress_errors => {}
839                     _ => {
840                         if let ty::RawPtr(_) = base_ty.kind {
841                             if !self.tcx.features().const_raw_ptr_deref {
842                                 self.record_error(ops::RawPtrDeref);
843                                 emit_feature_err(
844                                     &self.tcx.sess.parse_sess, sym::const_raw_ptr_deref,
845                                     self.span, GateIssue::Language,
846                                     &format!(
847                                         "dereferencing raw pointers in {}s is unstable",
848                                         self.mode,
849                                     ),
850                                 );
851                             }
852                         }
853                     }
854                 }
855             }
856
857             ProjectionElem::ConstantIndex {..} |
858             ProjectionElem::Subslice {..} |
859             ProjectionElem::Field(..) |
860             ProjectionElem::Index(_) => {
861                 let base_ty = Place::ty_from(place_base, proj_base, self.body, self.tcx).ty;
862                 if let Some(def) = base_ty.ty_adt_def() {
863                     if def.is_union() {
864                         match self.mode {
865                             Mode::ConstFn => {
866                                 if !self.tcx.features().const_fn_union
867                                     && !self.suppress_errors
868                                 {
869                                     self.record_error(ops::UnionAccess);
870                                     emit_feature_err(
871                                         &self.tcx.sess.parse_sess, sym::const_fn_union,
872                                         self.span, GateIssue::Language,
873                                         "unions in const fn are unstable",
874                                     );
875                                 }
876                             },
877
878                             | Mode::NonConstFn
879                             | Mode::Static
880                             | Mode::StaticMut
881                             | Mode::Const
882                             => {},
883                         }
884                     }
885                 }
886             }
887
888             ProjectionElem::Downcast(..) => {
889                 self.not_const(ops::Downcast)
890             }
891         }
892     }
893
894     fn visit_operand(&mut self, operand: &Operand<'tcx>, location: Location) {
895         debug!("visit_operand: operand={:?} location={:?}", operand, location);
896         self.super_operand(operand, location);
897
898         match *operand {
899             Operand::Move(ref place) => {
900                 // Mark the consumed locals to indicate later drops are noops.
901                 if let Some(local) = place.as_local() {
902                     self.cx.per_local[NeedsDrop].remove(local);
903                 }
904             }
905             Operand::Copy(_) |
906             Operand::Constant(_) => {}
907         }
908     }
909
910     fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
911         debug!("visit_rvalue: rvalue={:?} location={:?}", rvalue, location);
912
913         // Check nested operands and places.
914         if let Rvalue::Ref(_, kind, ref place) = *rvalue {
915             // Special-case reborrows.
916             let mut reborrow_place = None;
917             if let &[ref proj_base @ .., elem] = place.projection.as_ref() {
918                 if elem == ProjectionElem::Deref {
919                     let base_ty = Place::ty_from(&place.base, proj_base, self.body, self.tcx).ty;
920                     if let ty::Ref(..) = base_ty.kind {
921                         reborrow_place = Some(proj_base);
922                     }
923                 }
924             }
925
926             if let Some(proj) = reborrow_place {
927                 let ctx = match kind {
928                     BorrowKind::Shared => PlaceContext::NonMutatingUse(
929                         NonMutatingUseContext::SharedBorrow,
930                     ),
931                     BorrowKind::Shallow => PlaceContext::NonMutatingUse(
932                         NonMutatingUseContext::ShallowBorrow,
933                     ),
934                     BorrowKind::Unique => PlaceContext::NonMutatingUse(
935                         NonMutatingUseContext::UniqueBorrow,
936                     ),
937                     BorrowKind::Mut { .. } => PlaceContext::MutatingUse(
938                         MutatingUseContext::Borrow,
939                     ),
940                 };
941                 self.visit_place_base(&place.base, ctx, location);
942                 self.visit_projection(&place.base, proj, ctx, location);
943             } else {
944                 self.super_rvalue(rvalue, location);
945             }
946         } else {
947             self.super_rvalue(rvalue, location);
948         }
949
950         match *rvalue {
951             Rvalue::Use(_) |
952             Rvalue::Repeat(..) |
953             Rvalue::UnaryOp(UnOp::Neg, _) |
954             Rvalue::UnaryOp(UnOp::Not, _) |
955             Rvalue::NullaryOp(NullOp::SizeOf, _) |
956             Rvalue::CheckedBinaryOp(..) |
957             Rvalue::Cast(CastKind::Pointer(_), ..) |
958             Rvalue::Discriminant(..) |
959             Rvalue::Len(_) |
960             Rvalue::Ref(..) |
961             Rvalue::Aggregate(..) => {}
962
963             Rvalue::Cast(CastKind::Misc, ref operand, cast_ty) => {
964                 let operand_ty = operand.ty(self.body, self.tcx);
965                 let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast");
966                 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
967                 match (cast_in, cast_out) {
968                     (CastTy::Ptr(_), CastTy::Int(_)) |
969                     (CastTy::FnPtr, CastTy::Int(_)) if self.mode != Mode::NonConstFn => {
970                         unleash_miri!(self);
971                         if !self.tcx.features().const_raw_ptr_to_usize_cast
972                             && !self.suppress_errors
973                         {
974                             // in const fn and constants require the feature gate
975                             // FIXME: make it unsafe inside const fn and constants
976                             self.record_error(ops::RawPtrToIntCast);
977                             emit_feature_err(
978                                 &self.tcx.sess.parse_sess, sym::const_raw_ptr_to_usize_cast,
979                                 self.span, GateIssue::Language,
980                                 &format!(
981                                     "casting pointers to integers in {}s is unstable",
982                                     self.mode,
983                                 ),
984                             );
985                         }
986                     }
987                     _ => {}
988                 }
989             }
990
991             Rvalue::BinaryOp(op, ref lhs, _) => {
992                 if let ty::RawPtr(_) | ty::FnPtr(..) = lhs.ty(self.body, self.tcx).kind {
993                     assert!(op == BinOp::Eq || op == BinOp::Ne ||
994                             op == BinOp::Le || op == BinOp::Lt ||
995                             op == BinOp::Ge || op == BinOp::Gt ||
996                             op == BinOp::Offset);
997
998                     unleash_miri!(self);
999                     if self.mode.requires_const_checking() &&
1000                         !self.tcx.features().const_compare_raw_pointers &&
1001                         !self.suppress_errors
1002                     {
1003                         self.record_error(ops::RawPtrComparison);
1004                         // require the feature gate inside constants and const fn
1005                         // FIXME: make it unsafe to use these operations
1006                         emit_feature_err(
1007                             &self.tcx.sess.parse_sess,
1008                             sym::const_compare_raw_pointers,
1009                             self.span,
1010                             GateIssue::Language,
1011                             &format!("comparing raw pointers inside {}", self.mode),
1012                         );
1013                     }
1014                 }
1015             }
1016
1017             Rvalue::NullaryOp(NullOp::Box, _) => {
1018                 unleash_miri!(self);
1019                 if self.mode.requires_const_checking() && !self.suppress_errors {
1020                     self.record_error(ops::HeapAllocation);
1021                     let mut err = struct_span_err!(self.tcx.sess, self.span, E0010,
1022                                                    "allocations are not allowed in {}s", self.mode);
1023                     err.span_label(self.span, format!("allocation not allowed in {}s", self.mode));
1024                     if self.tcx.sess.teach(&err.get_code().unwrap()) {
1025                         err.note(
1026                             "The value of statics and constants must be known at compile time, \
1027                              and they live for the entire lifetime of a program. Creating a boxed \
1028                              value allocates memory on the heap at runtime, and therefore cannot \
1029                              be done at compile time."
1030                         );
1031                     }
1032                     err.emit();
1033                 }
1034             }
1035         }
1036     }
1037
1038     fn visit_terminator_kind(&mut self,
1039                              kind: &TerminatorKind<'tcx>,
1040                              location: Location) {
1041         debug!("visit_terminator_kind: kind={:?} location={:?}", kind, location);
1042         if let TerminatorKind::Call { ref func, ref args, ref destination, .. } = *kind {
1043             if let Some((ref dest, _)) = *destination {
1044                 self.assign(dest, ValueSource::Call {
1045                     callee: func,
1046                     args,
1047                     return_ty: dest.ty(self.body, self.tcx).ty,
1048                 }, location);
1049             }
1050
1051             let fn_ty = func.ty(self.body, self.tcx);
1052             match fn_ty.kind {
1053                 ty::FnDef(def_id, _) => {
1054                     match self.tcx.fn_sig(def_id).abi() {
1055                         Abi::RustIntrinsic |
1056                         Abi::PlatformIntrinsic => {
1057                             assert!(!self.tcx.is_const_fn(def_id));
1058                             match &*self.tcx.item_name(def_id).as_str() {
1059                                 // special intrinsic that can be called diretly without an intrinsic
1060                                 // feature gate needs a language feature gate
1061                                 "transmute" => {
1062                                     if self.mode.requires_const_checking()
1063                                         && !self.suppress_errors
1064                                     {
1065                                         // const eval transmute calls only with the feature gate
1066                                         if !self.tcx.features().const_transmute {
1067                                             self.record_error(ops::Transmute);
1068                                             emit_feature_err(
1069                                                 &self.tcx.sess.parse_sess, sym::const_transmute,
1070                                                 self.span, GateIssue::Language,
1071                                                 &format!("The use of std::mem::transmute() \
1072                                                 is gated in {}s", self.mode));
1073                                         }
1074                                     }
1075                                 }
1076
1077                                 // no need to check feature gates, intrinsics are only callable
1078                                 // from the libstd or with forever unstable feature gates
1079                                 _ => {}
1080                             }
1081                         }
1082                         _ => {
1083                             // In normal functions no calls are feature-gated.
1084                             if self.mode.requires_const_checking() {
1085                                 let unleash_miri = self
1086                                     .tcx
1087                                     .sess
1088                                     .opts
1089                                     .debugging_opts
1090                                     .unleash_the_miri_inside_of_you;
1091                                 if self.tcx.is_const_fn(def_id)
1092                                     || unleash_miri
1093                                     || self.suppress_errors
1094                                 {
1095                                     // stable const fns or unstable const fns
1096                                     // with their feature gate active
1097                                     // FIXME(eddyb) move stability checks from `is_const_fn` here.
1098                                 } else if self.is_const_panic_fn(def_id) {
1099                                     // Check the const_panic feature gate.
1100                                     // FIXME: cannot allow this inside `allow_internal_unstable`
1101                                     // because that would make `panic!` insta stable in constants,
1102                                     // since the macro is marked with the attribute.
1103                                     if !self.tcx.features().const_panic {
1104                                         // Don't allow panics in constants without the feature gate.
1105                                         self.record_error(ops::Panic);
1106                                         emit_feature_err(
1107                                             &self.tcx.sess.parse_sess,
1108                                             sym::const_panic,
1109                                             self.span,
1110                                             GateIssue::Language,
1111                                             &format!("panicking in {}s is unstable", self.mode),
1112                                         );
1113                                     }
1114                                 } else if let Some(feature)
1115                                               = self.tcx.is_unstable_const_fn(def_id) {
1116                                     // Check `#[unstable]` const fns or `#[rustc_const_unstable]`
1117                                     // functions without the feature gate active in this crate in
1118                                     // order to report a better error message than the one below.
1119                                     if !self.span.allows_unstable(feature) {
1120                                         self.record_error(ops::FnCallUnstable(def_id, feature));
1121                                         let mut err = self.tcx.sess.struct_span_err(self.span,
1122                                             &format!("`{}` is not yet stable as a const fn",
1123                                                     self.tcx.def_path_str(def_id)));
1124                                         if nightly_options::is_nightly_build() {
1125                                             help!(&mut err,
1126                                                   "add `#![feature({})]` to the \
1127                                                    crate attributes to enable",
1128                                                   feature);
1129                                         }
1130                                         err.emit();
1131                                     }
1132                                 } else {
1133                                     self.record_error(ops::FnCallNonConst(def_id));
1134                                     let mut err = struct_span_err!(
1135                                         self.tcx.sess,
1136                                         self.span,
1137                                         E0015,
1138                                         "calls in {}s are limited to constant functions, \
1139                                          tuple structs and tuple variants",
1140                                         self.mode,
1141                                     );
1142                                     err.emit();
1143                                 }
1144                             }
1145                         }
1146                     }
1147                 }
1148                 ty::FnPtr(_) => {
1149                     unleash_miri!(self);
1150                     if self.mode.requires_const_checking() && !self.suppress_errors {
1151                         self.record_error(ops::FnCallIndirect);
1152                         let mut err = self.tcx.sess.struct_span_err(
1153                             self.span,
1154                             "function pointers are not allowed in const fn"
1155                         );
1156                         err.emit();
1157                     }
1158                 }
1159                 _ => {
1160                     self.not_const(ops::FnCallOther);
1161                 }
1162             }
1163
1164             // Check callee and argument operands.
1165             self.visit_operand(func, location);
1166             for arg in args {
1167                 self.visit_operand(arg, location);
1168             }
1169         } else if let TerminatorKind::Drop {
1170             location: ref place, ..
1171         } | TerminatorKind::DropAndReplace {
1172             location: ref place, ..
1173         } = *kind {
1174             match *kind {
1175                 TerminatorKind::DropAndReplace { .. } => {}
1176                 _ => self.super_terminator_kind(kind, location),
1177             }
1178
1179             // Deny *any* live drops anywhere other than functions.
1180             if self.mode.requires_const_checking() && !self.suppress_errors {
1181                 unleash_miri!(self);
1182                 // HACK(eddyb): emulate a bit of dataflow analysis,
1183                 // conservatively, that drop elaboration will do.
1184                 let needs_drop = if let Some(local) = place.as_local() {
1185                     if NeedsDrop::in_local(self, local) {
1186                         Some(self.body.local_decls[local].source_info.span)
1187                     } else {
1188                         None
1189                     }
1190                 } else {
1191                     Some(self.span)
1192                 };
1193
1194                 if let Some(span) = needs_drop {
1195                     // Double-check the type being dropped, to minimize false positives.
1196                     let ty = place.ty(self.body, self.tcx).ty;
1197                     if ty.needs_drop(self.tcx, self.param_env) {
1198                         self.record_error_spanned(ops::LiveDrop, span);
1199                         struct_span_err!(self.tcx.sess, span, E0493,
1200                                          "destructors cannot be evaluated at compile-time")
1201                             .span_label(span, format!("{}s cannot evaluate destructors",
1202                                                       self.mode))
1203                             .emit();
1204                     }
1205                 }
1206             }
1207
1208             match *kind {
1209                 TerminatorKind::DropAndReplace { ref value, .. } => {
1210                     self.assign(place, ValueSource::DropAndReplace(value), location);
1211                     self.visit_operand(value, location);
1212                 }
1213                 _ => {}
1214             }
1215         } else {
1216             // Qualify any operands inside other terminators.
1217             self.super_terminator_kind(kind, location);
1218         }
1219     }
1220
1221     fn visit_assign(&mut self,
1222                     dest: &Place<'tcx>,
1223                     rvalue: &Rvalue<'tcx>,
1224                     location: Location) {
1225         debug!("visit_assign: dest={:?} rvalue={:?} location={:?}", dest, rvalue, location);
1226         self.assign(dest, ValueSource::Rvalue(rvalue), location);
1227
1228         self.visit_rvalue(rvalue, location);
1229     }
1230
1231     fn visit_source_info(&mut self, source_info: &SourceInfo) {
1232         debug!("visit_source_info: source_info={:?}", source_info);
1233         self.span = source_info.span;
1234     }
1235
1236     fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
1237         debug!("visit_statement: statement={:?} location={:?}", statement, location);
1238         match statement.kind {
1239             StatementKind::Assign(..) => {
1240                 self.super_statement(statement, location);
1241             }
1242             StatementKind::FakeRead(FakeReadCause::ForMatchedPlace, _) => {
1243                 self.not_const(ops::IfOrMatch);
1244             }
1245             // FIXME(eddyb) should these really do nothing?
1246             StatementKind::FakeRead(..) |
1247             StatementKind::SetDiscriminant { .. } |
1248             StatementKind::StorageLive(_) |
1249             StatementKind::StorageDead(_) |
1250             StatementKind::InlineAsm {..} |
1251             StatementKind::Retag { .. } |
1252             StatementKind::AscribeUserType(..) |
1253             StatementKind::Nop => {}
1254         }
1255     }
1256 }
1257
1258 pub fn provide(providers: &mut Providers<'_>) {
1259     *providers = Providers {
1260         mir_const_qualif,
1261         ..*providers
1262     };
1263 }
1264
1265 // FIXME(eddyb) this is only left around for the validation logic
1266 // in `promote_consts`, see the comment in `validate_operand`.
1267 pub(super) const QUALIF_ERROR_BIT: u8 = 1 << 2;
1268
1269 fn mir_const_qualif(tcx: TyCtxt<'_>, def_id: DefId) -> u8 {
1270     // N.B., this `borrow()` is guaranteed to be valid (i.e., the value
1271     // cannot yet be stolen), because `mir_validated()`, which steals
1272     // from `mir_const(), forces this query to execute before
1273     // performing the steal.
1274     let body = &tcx.mir_const(def_id).borrow();
1275
1276     if body.return_ty().references_error() {
1277         tcx.sess.delay_span_bug(body.span, "mir_const_qualif: MIR had errors");
1278         return QUALIF_ERROR_BIT;
1279     }
1280
1281     Checker::new(tcx, def_id, body, Mode::Const).check_const()
1282 }
1283
1284 pub struct QualifyAndPromoteConstants<'tcx> {
1285     pub promoted: Cell<IndexVec<Promoted, Body<'tcx>>>,
1286 }
1287
1288 impl<'tcx> Default for QualifyAndPromoteConstants<'tcx> {
1289     fn default() -> Self {
1290         QualifyAndPromoteConstants {
1291             promoted: Cell::new(IndexVec::new()),
1292         }
1293     }
1294 }
1295
1296 impl<'tcx> MirPass<'tcx> for QualifyAndPromoteConstants<'tcx> {
1297     fn run_pass(&self, tcx: TyCtxt<'tcx>, src: MirSource<'tcx>, body: &mut Body<'tcx>) {
1298         // There's not really any point in promoting errorful MIR.
1299         if body.return_ty().references_error() {
1300             tcx.sess.delay_span_bug(body.span, "QualifyAndPromoteConstants: MIR had errors");
1301             return;
1302         }
1303
1304         if src.promoted.is_some() {
1305             return;
1306         }
1307
1308         let def_id = src.def_id();
1309         let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1310
1311         let mode = determine_mode(tcx, hir_id, def_id);
1312
1313         debug!("run_pass: mode={:?}", mode);
1314         if let Mode::NonConstFn = mode {
1315             // No need to const-check a non-const `fn` now that we don't do promotion here.
1316             return;
1317         } else if let Mode::ConstFn = mode {
1318             let mut checker = Checker::new(tcx, def_id, body, mode);
1319             let use_min_const_fn_checks =
1320                 !tcx.sess.opts.debugging_opts.unleash_the_miri_inside_of_you &&
1321                 tcx.is_min_const_fn(def_id);
1322             if use_min_const_fn_checks {
1323                 // Enforce `min_const_fn` for stable `const fn`s.
1324                 use super::qualify_min_const_fn::is_min_const_fn;
1325                 if let Err((span, err)) = is_min_const_fn(tcx, def_id, body) {
1326                     error_min_const_fn_violation(tcx, span, err);
1327                     return;
1328                 }
1329             }
1330
1331             // `check_const` should not produce any errors, but better safe than sorry
1332             // FIXME(#53819)
1333             // Enforce a constant-like CFG for `const fn`.
1334             checker.check_const();
1335         } else {
1336             check_short_circuiting_in_const_local(tcx, body, mode);
1337
1338             match mode {
1339                 Mode::Const => tcx.mir_const_qualif(def_id),
1340                 _ => Checker::new(tcx, def_id, body, mode).check_const(),
1341             };
1342         }
1343
1344         if mode == Mode::Static && !tcx.has_attr(def_id, sym::thread_local) {
1345             // `static`s (not `static mut`s) which are not `#[thread_local]` must be `Sync`.
1346             check_static_is_sync(tcx, body, hir_id);
1347         }
1348     }
1349 }
1350
1351 fn determine_mode(tcx: TyCtxt<'_>, hir_id: HirId, def_id: DefId) -> Mode {
1352     match tcx.hir().body_owner_kind(hir_id) {
1353         hir::BodyOwnerKind::Closure => Mode::NonConstFn,
1354         hir::BodyOwnerKind::Fn if tcx.is_const_fn(def_id) => Mode::ConstFn,
1355         hir::BodyOwnerKind::Fn => Mode::NonConstFn,
1356         hir::BodyOwnerKind::Const => Mode::Const,
1357         hir::BodyOwnerKind::Static(hir::MutImmutable) => Mode::Static,
1358         hir::BodyOwnerKind::Static(hir::MutMutable) => Mode::StaticMut,
1359     }
1360 }
1361
1362 fn error_min_const_fn_violation(tcx: TyCtxt<'_>, span: Span, msg: Cow<'_, str>) {
1363     struct_span_err!(tcx.sess, span, E0723, "{}", msg)
1364         .note("for more information, see issue https://github.com/rust-lang/rust/issues/57563")
1365         .help("add `#![feature(const_fn)]` to the crate attributes to enable")
1366         .emit();
1367 }
1368
1369 fn check_short_circuiting_in_const_local(tcx: TyCtxt<'_>, body: &mut Body<'tcx>, mode: Mode) {
1370     if body.control_flow_destroyed.is_empty() {
1371         return;
1372     }
1373
1374     let mut locals = body.vars_iter();
1375     if let Some(local) = locals.next() {
1376         let span = body.local_decls[local].source_info.span;
1377         let mut error = tcx.sess.struct_span_err(
1378             span,
1379             &format!(
1380                 "new features like let bindings are not permitted in {}s \
1381                 which also use short circuiting operators",
1382                 mode,
1383             ),
1384         );
1385         for (span, kind) in body.control_flow_destroyed.iter() {
1386             error.span_note(
1387                 *span,
1388                 &format!("use of {} here does not actually short circuit due to \
1389                 the const evaluator presently not being able to do control flow. \
1390                 See https://github.com/rust-lang/rust/issues/49146 for more \
1391                 information.", kind),
1392             );
1393         }
1394         for local in locals {
1395             let span = body.local_decls[local].source_info.span;
1396             error.span_note(span, "more locals defined here");
1397         }
1398         error.emit();
1399     }
1400 }
1401
1402 fn check_static_is_sync(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>, hir_id: HirId) {
1403     let ty = body.return_ty();
1404     tcx.infer_ctxt().enter(|infcx| {
1405         let cause = traits::ObligationCause::new(body.span, hir_id, traits::SharedStatic);
1406         let mut fulfillment_cx = traits::FulfillmentContext::new();
1407         let sync_def_id = tcx.require_lang_item(lang_items::SyncTraitLangItem, Some(body.span));
1408         fulfillment_cx.register_bound(&infcx, ty::ParamEnv::empty(), ty, sync_def_id, cause);
1409         if let Err(err) = fulfillment_cx.select_all_or_error(&infcx) {
1410             infcx.report_fulfillment_errors(&err, None, false);
1411         }
1412     });
1413 }
1414
1415 fn validator_mismatch(
1416     tcx: TyCtxt<'tcx>,
1417     body: &Body<'tcx>,
1418     mut old_errors: Vec<(Span, String)>,
1419     mut new_errors: Vec<(Span, String)>,
1420 ) {
1421     error!("old validator: {:?}", old_errors);
1422     error!("new validator: {:?}", new_errors);
1423
1424     // ICE on nightly if the validators do not emit exactly the same errors.
1425     // Users can supress this panic with an unstable compiler flag (hopefully after
1426     // filing an issue).
1427     let opts = &tcx.sess.opts;
1428     let strict_validation_enabled = opts.unstable_features.is_nightly_build()
1429         && !opts.debugging_opts.suppress_const_validation_back_compat_ice;
1430
1431     if !strict_validation_enabled {
1432         return;
1433     }
1434
1435     // If this difference would cause a regression from the old to the new or vice versa, trigger
1436     // the ICE.
1437     if old_errors.is_empty() || new_errors.is_empty() {
1438         span_bug!(body.span, "{}", VALIDATOR_MISMATCH_ERR);
1439     }
1440
1441     // HACK: Borrows that would allow mutation are forbidden in const contexts, but they cause the
1442     // new validator to be more conservative about when a dropped local has been moved out of.
1443     //
1444     // Supress the mismatch ICE in cases where the validators disagree only on the number of
1445     // `LiveDrop` errors and both observe the same sequence of `MutBorrow`s.
1446
1447     let is_live_drop = |(_, s): &mut (_, String)| s.starts_with("LiveDrop");
1448     let is_mut_borrow = |(_, s): &&(_, String)| s.starts_with("MutBorrow");
1449
1450     let old_live_drops: Vec<_> = old_errors.drain_filter(is_live_drop).collect();
1451     let new_live_drops: Vec<_> = new_errors.drain_filter(is_live_drop).collect();
1452
1453     let only_live_drops_differ = old_live_drops != new_live_drops && old_errors == new_errors;
1454
1455     let old_mut_borrows = old_errors.iter().filter(is_mut_borrow);
1456     let new_mut_borrows = new_errors.iter().filter(is_mut_borrow);
1457
1458     let at_least_one_mut_borrow = old_mut_borrows.clone().next().is_some();
1459
1460     if only_live_drops_differ && at_least_one_mut_borrow && old_mut_borrows.eq(new_mut_borrows) {
1461         return;
1462     }
1463
1464     span_bug!(body.span, "{}", VALIDATOR_MISMATCH_ERR);
1465 }
1466
1467 const VALIDATOR_MISMATCH_ERR: &str =
1468     r"Disagreement between legacy and dataflow-based const validators.
1469     After filing an issue, use `-Zsuppress-const-validation-back-compat-ice` to compile your code.";