1 //! A pass that qualifies constness of temporaries in constants,
2 //! static initializers and functions and also drives promotion.
4 //! The Qualif flags below can be used to also provide better
5 //! diagnostics as to why a constant rvalue wasn't promoted.
7 use rustc_index::bit_set::BitSet;
8 use rustc_index::vec::IndexVec;
9 use rustc_target::spec::abi::Abi;
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;
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};
28 use std::ops::{Deref, Index, IndexMut};
31 use rustc::hir::HirId;
32 use crate::transform::{MirPass, MirSource};
33 use crate::transform::check_consts::ops::{self, NonConstOp};
35 /// What kind of item we are in.
36 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
40 /// A `static mut` item.
42 /// A `const fn` item.
44 /// A `const` item or an anonymous constant (e.g. in array lengths).
46 /// Other type of `fn`.
51 /// Determine whether we have to do full const-checking because syntactically, we
52 /// are required to be "const".
54 fn requires_const_checking(self) -> bool {
55 self != Mode::NonConstFn
59 impl fmt::Display for Mode {
60 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
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")
70 const QUALIF_COUNT: usize = 2;
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]);
77 impl<T: Clone> PerQualif<T> {
78 fn new(x: T) -> Self {
79 PerQualif([x.clone(), x])
83 impl<T> PerQualif<T> {
84 fn as_mut(&mut self) -> PerQualif<&mut T> {
85 let [x0, x1] = &mut self.0;
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)])
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)
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;
112 impl<Q: Qualif, T> Index<Q> for PerQualif<T> {
115 fn index(&self, _: Q) -> &T {
120 impl<Q: Qualif, T> IndexMut<Q> for PerQualif<T> {
121 fn index_mut(&mut self, _: Q) -> &mut T {
126 struct ConstCx<'a, 'tcx> {
128 param_env: ty::ParamEnv<'tcx>,
130 body: &'a Body<'tcx>,
132 per_local: PerQualif<BitSet<Local>>,
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()
142 #[derive(Copy, Clone, Debug)]
143 enum ValueSource<'a, 'tcx> {
144 Rvalue(&'a Rvalue<'tcx>),
145 DropAndReplace(&'a Operand<'tcx>),
147 callee: &'a Operand<'tcx>,
148 args: &'a [Operand<'tcx>],
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.
158 /// The default implementations proceed structurally.
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> {
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)
174 fn in_local(cx: &ConstCx<'_, '_>, local: Local) -> bool {
175 cx.per_local.0[Self::IDX].contains(local)
178 fn in_static(_cx: &ConstCx<'_, 'tcx>, _static: &Static<'tcx>) -> bool {
179 // FIXME(eddyb) should we do anything here for value properties?
183 fn in_projection_structurally(
184 cx: &ConstCx<'_, 'tcx>,
185 place: PlaceRef<'_, 'tcx>,
187 if let [proj_base @ .., elem] = place.projection {
188 let base_qualif = Self::in_place(cx, PlaceRef {
190 projection: proj_base,
192 let qualif = base_qualif && Self::mask_for_ty(
194 Place::ty_from(place.base, proj_base, cx.body, cx.tcx)
195 .projection_ty(cx.tcx, elem)
199 ProjectionElem::Deref |
200 ProjectionElem::Subslice { .. } |
201 ProjectionElem::Field(..) |
202 ProjectionElem::ConstantIndex { .. } |
203 ProjectionElem::Downcast(..) => qualif,
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),
211 bug!("This should be called if projection is not empty");
216 cx: &ConstCx<'_, 'tcx>,
217 place: PlaceRef<'_, 'tcx>,
219 Self::in_projection_structurally(cx, place)
222 fn in_place(cx: &ConstCx<'_, 'tcx>, place: PlaceRef<'_, 'tcx>) -> bool {
225 base: PlaceBase::Local(local),
227 } => Self::in_local(cx, *local),
229 base: PlaceBase::Static(box Static {
230 kind: StaticKind::Promoted(..),
234 } => bug!("qualifying already promoted MIR"),
236 base: PlaceBase::Static(static_),
239 Self::in_static(cx, static_)
244 } => Self::in_projection(cx, place),
248 fn in_operand(cx: &ConstCx<'_, 'tcx>, operand: &Operand<'tcx>) -> bool {
250 Operand::Copy(ref place) |
251 Operand::Move(ref place) => Self::in_place(cx, place.as_ref()),
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)
259 let bits = cx.tcx.at(constant.span).mir_const_qualif(def_id);
261 let qualif = PerQualif::decode_from_bits(bits).0[Self::IDX];
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)
275 fn in_rvalue_structurally(cx: &ConstCx<'_, 'tcx>, rvalue: &Rvalue<'tcx>) -> bool {
277 Rvalue::NullaryOp(..) => false,
279 Rvalue::Discriminant(ref place) |
280 Rvalue::Len(ref place) => Self::in_place(cx, place.as_ref()),
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),
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)
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 {
300 projection: proj_base,
306 Self::in_place(cx, place.as_ref())
309 Rvalue::Aggregate(_, ref operands) => {
310 operands.iter().any(|o| Self::in_operand(cx, o))
315 fn in_rvalue(cx: &ConstCx<'_, 'tcx>, rvalue: &Rvalue<'tcx>) -> bool {
316 Self::in_rvalue_structurally(cx, rvalue)
320 cx: &ConstCx<'_, 'tcx>,
321 _callee: &Operand<'tcx>,
322 _args: &[Operand<'tcx>],
325 // Be conservative about the returned value of a const fn.
326 Self::in_any_value_of_ty(cx, return_ty).unwrap_or(false)
329 fn in_value(cx: &ConstCx<'_, 'tcx>, source: ValueSource<'_, 'tcx>) -> bool {
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)
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;
347 impl Qualif for HasMutInterior {
348 const IDX: usize = 0;
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))
354 fn in_rvalue(cx: &ConstCx<'_, 'tcx>, rvalue: &Rvalue<'tcx>) -> bool {
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;
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.
369 ty::Array(..) | ty::Slice(_) => {}
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 => {},
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));
398 Self::in_rvalue_structurally(cx, rvalue)
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.
408 impl Qualif for NeedsDrop {
409 const IDX: usize = 1;
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))
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) {
424 Self::in_rvalue_structurally(cx, rvalue)
428 // Ensure the `IDX` values are sequential (`0..QUALIF_COUNT`).
429 macro_rules! static_assert_seq_qualifs {
430 ($i:expr => $first:ident $(, $rest:ident)*) => {
432 static_assert_seq_qualifs!($i + 1 => $($rest),*);
438 static_assert!(QUALIF_COUNT == $i);
441 static_assert_seq_qualifs!(
442 0 => HasMutInterior, NeedsDrop
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);
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);
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);
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>,
479 /// If `true`, do not emit errors to the user, merely collect them in `errors`.
480 suppress_errors: bool,
481 errors: Vec<(Span, String)>,
484 macro_rules! unleash_miri {
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");
495 impl Deref for Checker<'a, 'tcx> {
496 type Target = ConstCx<'a, 'tcx>;
498 fn deref(&self) -> &Self::Target {
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());
507 let param_env = tcx.param_env(def_id);
509 let mut cx = ConstCx {
514 per_local: PerQualif::new(BitSet::new_empty(body.local_decls.len())),
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 {
522 per_local.insert(local);
533 suppress_errors: false,
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) {
542 if self.mode.requires_const_checking() && !self.suppress_errors {
543 self.record_error(op);
544 let mut err = struct_span_err!(
548 "{} contains unimplemented expression type",
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.");
561 fn record_error(&mut self, op: impl NonConstOp) {
562 self.record_error_spanned(op, self.span);
565 fn record_error_spanned(&mut self, op: impl NonConstOp, span: Span) {
566 self.errors.push((span, format!("{:?}", op)));
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);
573 let mut qualifs = self.qualifs_in_value(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;
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",
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 \
603 If you really want global mutable state, try using \
604 static mut or a global UnsafeCell.");
608 span_err!(self.tcx.sess, self.span, E0492,
609 "cannot borrow a constant which may contain \
610 interior mutability, create a static instead");
619 let mut dest_projection = &dest.projection[..];
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;
635 (&PlaceBase::Static(box Static {
636 kind: StaticKind::Promoted(..),
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);
649 let kind = self.body.local_kind(index);
650 debug!("store to {:?} {:?}", kind, index);
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
656 for (per_local, qualif) in &mut self.cx.per_local.as_mut().zip(qualifs).0 {
658 per_local.insert(index);
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;
667 debug!("const-checking {} {:?}", self.mode, self.def_id);
669 // FIXME: Also use the new validator when features that require it (e.g. `const_if`) are
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");
676 let item = new_checker::Item::new(self.tcx, self.def_id, self.body);
677 let mut validator = new_checker::validation::Validator::new(&item);
679 validator.suppress_errors = !use_new_validator;
680 self.suppress_errors = use_new_validator;
682 let body = self.body;
684 let mut seen_blocks = BitSet::new_empty(body.basic_blocks().len());
685 let mut bb = START_BLOCK;
687 seen_blocks.insert(bb.index());
689 self.visit_basic_block_data(bb, &body[bb]);
690 validator.visit_basic_block_data(bb, &body[bb]);
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)), .. } => {
702 // Non-terminating calls cannot produce any value.
703 TerminatorKind::Call { destination: None, .. } => {
707 TerminatorKind::SwitchInt {..} |
708 TerminatorKind::Resume |
709 TerminatorKind::Abort |
710 TerminatorKind::GeneratorDrop |
711 TerminatorKind::Yield { .. } |
712 TerminatorKind::Unreachable |
713 TerminatorKind::FalseEdges { .. } => None,
715 TerminatorKind::Return => {
722 Some(target) if !seen_blocks.contains(target.index()) => {
726 self.not_const(ops::Loop);
727 validator.check_op(ops::Loop);
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();
738 // FIXME: each checker sometimes emits the same error with the same span twice in a row.
742 if self.errors != new_errors {
746 std::mem::replace(&mut self.errors, vec![]),
752 self.qualifs_in_local(RETURN_PLACE).encode_to_bits()
756 impl<'a, 'tcx> Visitor<'tcx> for Checker<'a, 'tcx> {
759 place_base: &PlaceBase<'tcx>,
760 context: PlaceContext,
763 self.super_place_base(place_base, context, location);
765 PlaceBase::Local(_) => {}
766 PlaceBase::Static(box Static{ kind: StaticKind::Promoted(_, _), .. }) => {
769 PlaceBase::Static(box Static{ kind: StaticKind::Static, def_id, .. }) => {
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");
783 // Only allow statics (not consts) to refer to other statics.
784 if self.mode == Mode::Static || self.mode == Mode::StaticMut {
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()) {
796 "Static and const variables can refer to other const variables. \
797 But a const variable cannot refer to a static variable."
800 "To fix this, the value can be extracted as a const and then used."
809 fn visit_projection_elem(
811 place_base: &PlaceBase<'tcx>,
812 proj_base: &[PlaceElem<'tcx>],
813 elem: &PlaceElem<'tcx>,
814 context: PlaceContext,
818 "visit_projection_elem: place_base={:?} proj_base={:?} elem={:?} \
819 context={:?} location={:?}",
827 self.super_projection_elem(place_base, proj_base, elem, context, location);
830 ProjectionElem::Deref => {
831 if context.is_mutating_use() {
832 // `not_const` errors out in const contexts
833 self.not_const(ops::MutDeref)
835 let base_ty = Place::ty_from(place_base, proj_base, self.body, self.tcx).ty;
837 Mode::NonConstFn => {}
838 _ if self.suppress_errors => {}
840 if let ty::RawPtr(_) = base_ty.kind {
841 if !self.tcx.features().const_raw_ptr_deref {
842 self.record_error(ops::RawPtrDeref);
844 &self.tcx.sess.parse_sess, sym::const_raw_ptr_deref,
845 self.span, GateIssue::Language,
847 "dereferencing raw pointers in {}s is unstable",
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() {
866 if !self.tcx.features().const_fn_union
867 && !self.suppress_errors
869 self.record_error(ops::UnionAccess);
871 &self.tcx.sess.parse_sess, sym::const_fn_union,
872 self.span, GateIssue::Language,
873 "unions in const fn are unstable",
888 ProjectionElem::Downcast(..) => {
889 self.not_const(ops::Downcast)
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);
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);
906 Operand::Constant(_) => {}
910 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
911 debug!("visit_rvalue: rvalue={:?} location={:?}", rvalue, location);
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);
926 if let Some(proj) = reborrow_place {
927 let ctx = match kind {
928 BorrowKind::Shared => PlaceContext::NonMutatingUse(
929 NonMutatingUseContext::SharedBorrow,
931 BorrowKind::Shallow => PlaceContext::NonMutatingUse(
932 NonMutatingUseContext::ShallowBorrow,
934 BorrowKind::Unique => PlaceContext::NonMutatingUse(
935 NonMutatingUseContext::UniqueBorrow,
937 BorrowKind::Mut { .. } => PlaceContext::MutatingUse(
938 MutatingUseContext::Borrow,
941 self.visit_place_base(&place.base, ctx, location);
942 self.visit_projection(&place.base, proj, ctx, location);
944 self.super_rvalue(rvalue, location);
947 self.super_rvalue(rvalue, location);
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(..) |
961 Rvalue::Aggregate(..) => {}
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 => {
971 if !self.tcx.features().const_raw_ptr_to_usize_cast
972 && !self.suppress_errors
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);
978 &self.tcx.sess.parse_sess, sym::const_raw_ptr_to_usize_cast,
979 self.span, GateIssue::Language,
981 "casting pointers to integers in {}s is unstable",
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);
999 if self.mode.requires_const_checking() &&
1000 !self.tcx.features().const_compare_raw_pointers &&
1001 !self.suppress_errors
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
1007 &self.tcx.sess.parse_sess,
1008 sym::const_compare_raw_pointers,
1010 GateIssue::Language,
1011 &format!("comparing raw pointers inside {}", self.mode),
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()) {
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."
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 {
1047 return_ty: dest.ty(self.body, self.tcx).ty,
1051 let fn_ty = func.ty(self.body, self.tcx);
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
1062 if self.mode.requires_const_checking()
1063 && !self.suppress_errors
1065 // const eval transmute calls only with the feature gate
1066 if !self.tcx.features().const_transmute {
1067 self.record_error(ops::Transmute);
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));
1077 // no need to check feature gates, intrinsics are only callable
1078 // from the libstd or with forever unstable feature gates
1083 // In normal functions no calls are feature-gated.
1084 if self.mode.requires_const_checking() {
1085 let unleash_miri = self
1090 .unleash_the_miri_inside_of_you;
1091 if self.tcx.is_const_fn(def_id)
1093 || self.suppress_errors
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);
1107 &self.tcx.sess.parse_sess,
1110 GateIssue::Language,
1111 &format!("panicking in {}s is unstable", self.mode),
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() {
1126 "add `#![feature({})]` to the \
1127 crate attributes to enable",
1133 self.record_error(ops::FnCallNonConst(def_id));
1134 let mut err = struct_span_err!(
1138 "calls in {}s are limited to constant functions, \
1139 tuple structs and tuple variants",
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(
1154 "function pointers are not allowed in const fn"
1160 self.not_const(ops::FnCallOther);
1164 // Check callee and argument operands.
1165 self.visit_operand(func, location);
1167 self.visit_operand(arg, location);
1169 } else if let TerminatorKind::Drop {
1170 location: ref place, ..
1171 } | TerminatorKind::DropAndReplace {
1172 location: ref place, ..
1175 TerminatorKind::DropAndReplace { .. } => {}
1176 _ => self.super_terminator_kind(kind, location),
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)
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",
1209 TerminatorKind::DropAndReplace { ref value, .. } => {
1210 self.assign(place, ValueSource::DropAndReplace(value), location);
1211 self.visit_operand(value, location);
1216 // Qualify any operands inside other terminators.
1217 self.super_terminator_kind(kind, location);
1221 fn visit_assign(&mut self,
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);
1228 self.visit_rvalue(rvalue, location);
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;
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);
1242 StatementKind::FakeRead(FakeReadCause::ForMatchedPlace, _) => {
1243 self.not_const(ops::IfOrMatch);
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 => {}
1258 pub fn provide(providers: &mut Providers<'_>) {
1259 *providers = Providers {
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;
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();
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;
1281 Checker::new(tcx, def_id, body, Mode::Const).check_const()
1284 pub struct QualifyAndPromoteConstants<'tcx> {
1285 pub promoted: Cell<IndexVec<Promoted, Body<'tcx>>>,
1288 impl<'tcx> Default for QualifyAndPromoteConstants<'tcx> {
1289 fn default() -> Self {
1290 QualifyAndPromoteConstants {
1291 promoted: Cell::new(IndexVec::new()),
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");
1304 if src.promoted.is_some() {
1308 let def_id = src.def_id();
1309 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1311 let mode = determine_mode(tcx, hir_id, def_id);
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.
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);
1331 // `check_const` should not produce any errors, but better safe than sorry
1333 // Enforce a constant-like CFG for `const fn`.
1334 checker.check_const();
1336 check_short_circuiting_in_const_local(tcx, body, mode);
1339 Mode::Const => tcx.mir_const_qualif(def_id),
1340 _ => Checker::new(tcx, def_id, body, mode).check_const(),
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);
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,
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")
1369 fn check_short_circuiting_in_const_local(tcx: TyCtxt<'_>, body: &mut Body<'tcx>, mode: Mode) {
1370 if body.control_flow_destroyed.is_empty() {
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(
1380 "new features like let bindings are not permitted in {}s \
1381 which also use short circuiting operators",
1385 for (span, kind) in body.control_flow_destroyed.iter() {
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),
1394 for local in locals {
1395 let span = body.local_decls[local].source_info.span;
1396 error.span_note(span, "more locals defined here");
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);
1415 fn validator_mismatch(
1418 mut old_errors: Vec<(Span, String)>,
1419 mut new_errors: Vec<(Span, String)>,
1421 error!("old validator: {:?}", old_errors);
1422 error!("new validator: {:?}", new_errors);
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;
1431 if !strict_validation_enabled {
1435 // If this difference would cause a regression from the old to the new or vice versa, trigger
1437 if old_errors.is_empty() || new_errors.is_empty() {
1438 span_bug!(body.span, "{}", VALIDATOR_MISMATCH_ERR);
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.
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.
1447 let is_live_drop = |(_, s): &mut (_, String)| s.starts_with("LiveDrop");
1448 let is_mut_borrow = |(_, s): &&(_, String)| s.starts_with("MutBorrow");
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();
1453 let only_live_drops_differ = old_live_drops != new_live_drops && old_errors == new_errors;
1455 let old_mut_borrows = old_errors.iter().filter(is_mut_borrow);
1456 let new_mut_borrows = new_errors.iter().filter(is_mut_borrow);
1458 let at_least_one_mut_borrow = old_mut_borrows.clone().next().is_some();
1460 if only_live_drops_differ && at_least_one_mut_borrow && old_mut_borrows.eq(new_mut_borrows) {
1464 span_bug!(body.span, "{}", VALIDATOR_MISMATCH_ERR);
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.";