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::visit::{PlaceContext, Visitor, MutatingUseContext, NonMutatingUseContext};
18 use rustc::middle::lang_items;
19 use rustc::session::config::nightly_options;
20 use syntax::feature_gate::{emit_feature_err, GateIssue};
21 use syntax::symbol::sym;
22 use syntax_pos::{Span, DUMMY_SP};
27 use std::ops::{Deref, Index, IndexMut};
30 use rustc::hir::HirId;
31 use crate::transform::{MirPass, MirSource};
32 use crate::transform::check_consts::ops::{self, NonConstOp};
34 use rustc_error_codes::*;
36 /// What kind of item we are in.
37 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
41 /// A `static mut` item.
43 /// A `const fn` item.
45 /// A `const` item or an anonymous constant (e.g. in array lengths).
47 /// Other type of `fn`.
52 /// Determine whether we have to do full const-checking because syntactically, we
53 /// are required to be "const".
55 fn requires_const_checking(self) -> bool {
56 self != Mode::NonConstFn
60 impl fmt::Display for Mode {
61 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63 Mode::Const => write!(f, "constant"),
64 Mode::Static | Mode::StaticMut => write!(f, "static"),
65 Mode::ConstFn => write!(f, "constant function"),
66 Mode::NonConstFn => write!(f, "function")
71 const QUALIF_COUNT: usize = 2;
73 // FIXME(eddyb) once we can use const generics, replace this array with
74 // something like `IndexVec` but for fixed-size arrays (`IndexArray`?).
75 #[derive(Copy, Clone, Default)]
76 struct PerQualif<T>([T; QUALIF_COUNT]);
78 impl<T: Clone> PerQualif<T> {
79 fn new(x: T) -> Self {
80 PerQualif([x.clone(), x])
84 impl<T> PerQualif<T> {
85 fn as_mut(&mut self) -> PerQualif<&mut T> {
86 let [x0, x1] = &mut self.0;
90 fn zip<U>(self, other: PerQualif<U>) -> PerQualif<(T, U)> {
91 let [x0, x1] = self.0;
92 let [y0, y1] = other.0;
93 PerQualif([(x0, y0), (x1, y1)])
97 impl PerQualif<bool> {
98 fn encode_to_bits(self) -> u8 {
99 self.0.iter().enumerate().fold(0, |bits, (i, &qualif)| {
100 bits | ((qualif as u8) << i)
104 fn decode_from_bits(bits: u8) -> Self {
105 let mut qualifs = Self::default();
106 for (i, qualif) in qualifs.0.iter_mut().enumerate() {
107 *qualif = (bits & (1 << i)) != 0;
113 impl<Q: Qualif, T> Index<Q> for PerQualif<T> {
116 fn index(&self, _: Q) -> &T {
121 impl<Q: Qualif, T> IndexMut<Q> for PerQualif<T> {
122 fn index_mut(&mut self, _: Q) -> &mut T {
127 struct ConstCx<'a, 'tcx> {
129 param_env: ty::ParamEnv<'tcx>,
131 body: &'a Body<'tcx>,
133 per_local: PerQualif<BitSet<Local>>,
136 impl<'a, 'tcx> ConstCx<'a, 'tcx> {
137 fn is_const_panic_fn(&self, def_id: DefId) -> bool {
138 Some(def_id) == self.tcx.lang_items().panic_fn() ||
139 Some(def_id) == self.tcx.lang_items().begin_panic_fn()
143 #[derive(Copy, Clone, Debug)]
144 enum ValueSource<'a, 'tcx> {
145 Rvalue(&'a Rvalue<'tcx>),
146 DropAndReplace(&'a Operand<'tcx>),
148 callee: &'a Operand<'tcx>,
149 args: &'a [Operand<'tcx>],
154 /// A "qualif"(-ication) is a way to look for something "bad" in the MIR that would disqualify some
155 /// code for promotion or prevent it from evaluating at compile time. So `return true` means
156 /// "I found something bad, no reason to go on searching". `false` is only returned if we
157 /// definitely cannot find anything bad anywhere.
159 /// The default implementations proceed structurally.
163 /// Return the qualification that is (conservatively) correct for any value
164 /// of the type, or `None` if the qualification is not value/type-based.
165 fn in_any_value_of_ty(_cx: &ConstCx<'_, 'tcx>, _ty: Ty<'tcx>) -> Option<bool> {
169 /// Return a mask for the qualification, given a type. This is `false` iff
170 /// no value of that type can have the qualification.
171 fn mask_for_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool {
172 Self::in_any_value_of_ty(cx, ty).unwrap_or(true)
175 fn in_local(cx: &ConstCx<'_, '_>, local: Local) -> bool {
176 cx.per_local.0[Self::IDX].contains(local)
179 fn in_static(_cx: &ConstCx<'_, 'tcx>, _static: &Static<'tcx>) -> bool {
180 // FIXME(eddyb) should we do anything here for value properties?
184 fn in_projection_structurally(
185 cx: &ConstCx<'_, 'tcx>,
186 place: PlaceRef<'_, 'tcx>,
188 if let [proj_base @ .., elem] = place.projection {
189 let base_qualif = Self::in_place(cx, PlaceRef {
191 projection: proj_base,
193 let qualif = base_qualif && Self::mask_for_ty(
195 Place::ty_from(place.base, proj_base, cx.body, cx.tcx)
196 .projection_ty(cx.tcx, elem)
200 ProjectionElem::Deref |
201 ProjectionElem::Subslice { .. } |
202 ProjectionElem::Field(..) |
203 ProjectionElem::ConstantIndex { .. } |
204 ProjectionElem::Downcast(..) => qualif,
206 // FIXME(eddyb) shouldn't this be masked *after* including the
207 // index local? Then again, it's `usize` which is neither
208 // `HasMutInterior` nor `NeedsDrop`.
209 ProjectionElem::Index(local) => qualif || Self::in_local(cx, *local),
212 bug!("This should be called if projection is not empty");
217 cx: &ConstCx<'_, 'tcx>,
218 place: PlaceRef<'_, 'tcx>,
220 Self::in_projection_structurally(cx, place)
223 fn in_place(cx: &ConstCx<'_, 'tcx>, place: PlaceRef<'_, 'tcx>) -> bool {
226 base: PlaceBase::Local(local),
228 } => Self::in_local(cx, *local),
230 base: PlaceBase::Static(box Static {
231 kind: StaticKind::Promoted(..),
235 } => bug!("qualifying already promoted MIR"),
237 base: PlaceBase::Static(static_),
240 Self::in_static(cx, static_)
245 } => Self::in_projection(cx, place),
249 fn in_operand(cx: &ConstCx<'_, 'tcx>, operand: &Operand<'tcx>) -> bool {
251 Operand::Copy(ref place) |
252 Operand::Move(ref place) => Self::in_place(cx, place.as_ref()),
254 Operand::Constant(ref constant) => {
255 if let ty::ConstKind::Unevaluated(def_id, _) = constant.literal.val {
256 // Don't peek inside trait associated constants.
257 if cx.tcx.trait_of_item(def_id).is_some() {
258 Self::in_any_value_of_ty(cx, constant.literal.ty).unwrap_or(false)
260 let bits = cx.tcx.at(constant.span).mir_const_qualif(def_id);
262 let qualif = PerQualif::decode_from_bits(bits).0[Self::IDX];
264 // Just in case the type is more specific than
265 // the definition, e.g., impl associated const
266 // with type parameters, take it into account.
267 qualif && Self::mask_for_ty(cx, constant.literal.ty)
276 fn in_rvalue_structurally(cx: &ConstCx<'_, 'tcx>, rvalue: &Rvalue<'tcx>) -> bool {
278 Rvalue::NullaryOp(..) => false,
280 Rvalue::Discriminant(ref place) |
281 Rvalue::Len(ref place) => Self::in_place(cx, place.as_ref()),
283 Rvalue::Use(ref operand) |
284 Rvalue::Repeat(ref operand, _) |
285 Rvalue::UnaryOp(_, ref operand) |
286 Rvalue::Cast(_, ref operand, _) => Self::in_operand(cx, operand),
288 Rvalue::BinaryOp(_, ref lhs, ref rhs) |
289 Rvalue::CheckedBinaryOp(_, ref lhs, ref rhs) => {
290 Self::in_operand(cx, lhs) || Self::in_operand(cx, rhs)
293 Rvalue::Ref(_, _, ref place) => {
294 // Special-case reborrows to be more like a copy of the reference.
295 if let &[ref proj_base @ .., elem] = place.projection.as_ref() {
296 if ProjectionElem::Deref == elem {
297 let base_ty = Place::ty_from(&place.base, proj_base, cx.body, cx.tcx).ty;
298 if let ty::Ref(..) = base_ty.kind {
299 return Self::in_place(cx, PlaceRef {
301 projection: proj_base,
307 Self::in_place(cx, place.as_ref())
310 Rvalue::Aggregate(_, ref operands) => {
311 operands.iter().any(|o| Self::in_operand(cx, o))
316 fn in_rvalue(cx: &ConstCx<'_, 'tcx>, rvalue: &Rvalue<'tcx>) -> bool {
317 Self::in_rvalue_structurally(cx, rvalue)
321 cx: &ConstCx<'_, 'tcx>,
322 _callee: &Operand<'tcx>,
323 _args: &[Operand<'tcx>],
326 // Be conservative about the returned value of a const fn.
327 Self::in_any_value_of_ty(cx, return_ty).unwrap_or(false)
330 fn in_value(cx: &ConstCx<'_, 'tcx>, source: ValueSource<'_, 'tcx>) -> bool {
332 ValueSource::Rvalue(rvalue) => Self::in_rvalue(cx, rvalue),
333 ValueSource::DropAndReplace(source) => Self::in_operand(cx, source),
334 ValueSource::Call { callee, args, return_ty } => {
335 Self::in_call(cx, callee, args, return_ty)
341 /// Constant containing interior mutability (`UnsafeCell<T>`).
342 /// This must be ruled out to make sure that evaluating the constant at compile-time
343 /// and at *any point* during the run-time would produce the same result. In particular,
344 /// promotion of temporaries must not change program behavior; if the promoted could be
345 /// written to, that would be a problem.
346 struct HasMutInterior;
348 impl Qualif for HasMutInterior {
349 const IDX: usize = 0;
351 fn in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> Option<bool> {
352 Some(!ty.is_freeze(cx.tcx, cx.param_env, DUMMY_SP))
355 fn in_rvalue(cx: &ConstCx<'_, 'tcx>, rvalue: &Rvalue<'tcx>) -> bool {
357 // Returning `true` for `Rvalue::Ref` indicates the borrow isn't
358 // allowed in constants (and the `Checker` will error), and/or it
359 // won't be promoted, due to `&mut ...` or interior mutability.
360 Rvalue::Ref(_, kind, ref place) => {
361 let ty = place.ty(cx.body, cx.tcx).ty;
363 if let BorrowKind::Mut { .. } = kind {
364 // In theory, any zero-sized value could be borrowed
365 // mutably without consequences. However, only &mut []
366 // is allowed right now, and only in functions.
367 if cx.mode == Mode::StaticMut {
368 // Inside a `static mut`, &mut [...] is also allowed.
370 ty::Array(..) | ty::Slice(_) => {}
373 } else if let ty::Array(_, len) = ty.kind {
374 // FIXME(eddyb) the `cx.mode == Mode::NonConstFn` condition
375 // seems unnecessary, given that this is merely a ZST.
376 match len.try_eval_usize(cx.tcx, cx.param_env) {
377 Some(0) if cx.mode == Mode::NonConstFn => {},
386 Rvalue::Aggregate(ref kind, _) => {
387 if let AggregateKind::Adt(def, ..) = **kind {
388 if Some(def.did) == cx.tcx.lang_items().unsafe_cell_type() {
389 let ty = rvalue.ty(cx.body, cx.tcx);
390 assert_eq!(Self::in_any_value_of_ty(cx, ty), Some(true));
399 Self::in_rvalue_structurally(cx, rvalue)
403 /// Constant containing an ADT that implements `Drop`.
404 /// This must be ruled out (a) because we cannot run `Drop` during compile-time
405 /// as that might not be a `const fn`, and (b) because implicit promotion would
406 /// remove side-effects that occur as part of dropping that value.
409 impl Qualif for NeedsDrop {
410 const IDX: usize = 1;
412 fn in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> Option<bool> {
413 Some(ty.needs_drop(cx.tcx, cx.param_env))
416 fn in_rvalue(cx: &ConstCx<'_, 'tcx>, rvalue: &Rvalue<'tcx>) -> bool {
417 if let Rvalue::Aggregate(ref kind, _) = *rvalue {
418 if let AggregateKind::Adt(def, ..) = **kind {
419 if def.has_dtor(cx.tcx) {
425 Self::in_rvalue_structurally(cx, rvalue)
429 // Ensure the `IDX` values are sequential (`0..QUALIF_COUNT`).
430 macro_rules! static_assert_seq_qualifs {
431 ($i:expr => $first:ident $(, $rest:ident)*) => {
433 static_assert_seq_qualifs!($i + 1 => $($rest),*);
439 static_assert!(QUALIF_COUNT == $i);
442 static_assert_seq_qualifs!(
443 0 => HasMutInterior, NeedsDrop
446 impl ConstCx<'_, 'tcx> {
447 fn qualifs_in_any_value_of_ty(&self, ty: Ty<'tcx>) -> PerQualif<bool> {
448 let mut qualifs = PerQualif::default();
449 qualifs[HasMutInterior] = HasMutInterior::in_any_value_of_ty(self, ty).unwrap_or(false);
450 qualifs[NeedsDrop] = NeedsDrop::in_any_value_of_ty(self, ty).unwrap_or(false);
454 fn qualifs_in_local(&self, local: Local) -> PerQualif<bool> {
455 let mut qualifs = PerQualif::default();
456 qualifs[HasMutInterior] = HasMutInterior::in_local(self, local);
457 qualifs[NeedsDrop] = NeedsDrop::in_local(self, local);
461 fn qualifs_in_value(&self, source: ValueSource<'_, 'tcx>) -> PerQualif<bool> {
462 let mut qualifs = PerQualif::default();
463 qualifs[HasMutInterior] = HasMutInterior::in_value(self, source);
464 qualifs[NeedsDrop] = NeedsDrop::in_value(self, source);
469 /// Checks MIR for being admissible as a compile-time constant, using `ConstCx`
470 /// for value qualifications, and accumulates writes of
471 /// rvalue/call results to locals, in `local_qualif`.
472 /// It also records candidates for promotion in `promotion_candidates`,
473 /// both in functions and const/static items.
474 struct Checker<'a, 'tcx> {
475 cx: ConstCx<'a, 'tcx>,
480 /// If `true`, do not emit errors to the user, merely collect them in `errors`.
481 suppress_errors: bool,
482 errors: Vec<(Span, String)>,
485 macro_rules! unleash_miri {
487 if $this.tcx.sess.opts.debugging_opts.unleash_the_miri_inside_of_you {
488 if $this.mode.requires_const_checking() && !$this.suppress_errors {
489 $this.tcx.sess.span_warn($this.span, "skipping const checks");
496 impl Deref for Checker<'a, 'tcx> {
497 type Target = ConstCx<'a, 'tcx>;
499 fn deref(&self) -> &Self::Target {
504 impl<'a, 'tcx> Checker<'a, 'tcx> {
505 fn new(tcx: TyCtxt<'tcx>, def_id: DefId, body: &'a Body<'tcx>, mode: Mode) -> Self {
506 assert!(def_id.is_local());
508 let param_env = tcx.param_env(def_id);
510 let mut cx = ConstCx {
515 per_local: PerQualif::new(BitSet::new_empty(body.local_decls.len())),
518 for (local, decl) in body.local_decls.iter_enumerated() {
519 if let LocalKind::Arg = body.local_kind(local) {
520 let qualifs = cx.qualifs_in_any_value_of_ty(decl.ty);
521 for (per_local, qualif) in &mut cx.per_local.as_mut().zip(qualifs).0 {
523 per_local.insert(local);
534 suppress_errors: false,
538 // FIXME(eddyb) we could split the errors into meaningful
539 // categories, but enabling full miri would make that
540 // slightly pointless (even with feature-gating).
541 fn not_const(&mut self, op: impl NonConstOp) {
543 if self.mode.requires_const_checking() && !self.suppress_errors {
544 self.record_error(op);
545 let mut err = struct_span_err!(
549 "{} contains unimplemented expression type",
552 if self.tcx.sess.teach(&err.get_code().unwrap()) {
553 err.note("A function call isn't allowed in the const's initialization expression \
554 because the expression's value must be known at compile-time.");
555 err.note("Remember: you can't use a function call inside a const's initialization \
556 expression! However, you can use it anywhere else.");
562 fn record_error(&mut self, op: impl NonConstOp) {
563 self.record_error_spanned(op, self.span);
566 fn record_error_spanned(&mut self, op: impl NonConstOp, span: Span) {
567 self.errors.push((span, format!("{:?}", op)));
570 /// Assigns an rvalue/call qualification to the given destination.
571 fn assign(&mut self, dest: &Place<'tcx>, source: ValueSource<'_, 'tcx>, location: Location) {
572 trace!("assign: {:?} <- {:?}", dest, source);
574 let mut qualifs = self.qualifs_in_value(source);
577 ValueSource::Rvalue(&Rvalue::Ref(_, kind, _)) => {
578 // Getting `true` from `HasMutInterior::in_rvalue` means
579 // the borrowed place is disallowed from being borrowed,
580 // due to either a mutable borrow (with some exceptions),
581 // or an shared borrow of a value with interior mutability.
582 // Then `HasMutInterior` is cleared
583 // to avoid duplicate errors (e.g. from reborrowing).
584 if qualifs[HasMutInterior] {
585 qualifs[HasMutInterior] = false;
587 debug!("suppress_errors: {}", self.suppress_errors);
588 if self.mode.requires_const_checking() && !self.suppress_errors {
589 if !self.tcx.sess.opts.debugging_opts.unleash_the_miri_inside_of_you {
590 self.record_error(ops::MutBorrow(kind));
591 if let BorrowKind::Mut { .. } = kind {
592 let mut err = struct_span_err!(self.tcx.sess, self.span, E0017,
593 "references in {}s may only refer \
594 to immutable values", self.mode);
595 err.span_label(self.span, format!("{}s require immutable values",
597 if self.tcx.sess.teach(&err.get_code().unwrap()) {
598 err.note("References in statics and constants may only refer \
599 to immutable values.\n\n\
600 Statics are shared everywhere, and if they refer to \
601 mutable data one might violate memory safety since \
602 holding multiple mutable references to shared data \
604 If you really want global mutable state, try using \
605 static mut or a global UnsafeCell.");
609 span_err!(self.tcx.sess, self.span, E0492,
610 "cannot borrow a constant which may contain \
611 interior mutability, create a static instead");
620 let mut dest_projection = &dest.projection[..];
622 match (&dest.base, dest_projection) {
623 // We treat all locals equal in constants
624 (&PlaceBase::Local(index), []) => break index,
625 // projections are transparent for assignments
626 // we qualify the entire destination at once, even if just a field would have
627 // stricter qualification
628 (base, [proj_base @ .., _]) => {
629 // Catch more errors in the destination. `visit_place` also checks various
630 // projection rules like union field access and raw pointer deref
631 let context = PlaceContext::MutatingUse(MutatingUseContext::Store);
632 self.visit_place_base(base, context, location);
633 self.visit_projection(base, dest_projection, context, location);
634 dest_projection = proj_base;
636 (&PlaceBase::Static(box Static {
637 kind: StaticKind::Promoted(..),
639 }), []) => bug!("promoteds don't exist yet during promotion"),
640 (&PlaceBase::Static(box Static{ kind: _, .. }), []) => {
641 // Catch more errors in the destination. `visit_place` also checks that we
642 // do not try to access statics from constants or try to mutate statics
643 let context = PlaceContext::MutatingUse(MutatingUseContext::Store);
644 self.visit_place_base(&dest.base, context, location);
650 let kind = self.body.local_kind(index);
651 debug!("store to {:?} {:?}", kind, index);
653 // this is overly restrictive, because even full assignments do not clear the qualif
654 // While we could special case full assignments, this would be inconsistent with
655 // aggregates where we overwrite all fields via assignments, which would not get
657 for (per_local, qualif) in &mut self.cx.per_local.as_mut().zip(qualifs).0 {
659 per_local.insert(index);
664 /// Check a whole const, static initializer or const fn.
665 fn check_const(&mut self) -> u8 {
666 use crate::transform::check_consts as new_checker;
668 debug!("const-checking {} {:?}", self.mode, self.def_id);
670 // FIXME: Also use the new validator when features that require it (e.g. `const_if`) are
672 let use_new_validator = self.tcx.sess.opts.debugging_opts.unleash_the_miri_inside_of_you;
673 if use_new_validator {
674 debug!("Using dataflow-based const validator");
677 let item = new_checker::Item::new(self.tcx, self.def_id, self.body);
678 let mut validator = new_checker::validation::Validator::new(&item);
680 validator.suppress_errors = !use_new_validator;
681 self.suppress_errors = use_new_validator;
683 let body = self.body;
685 let mut seen_blocks = BitSet::new_empty(body.basic_blocks().len());
686 let mut bb = START_BLOCK;
688 seen_blocks.insert(bb.index());
690 self.visit_basic_block_data(bb, &body[bb]);
691 validator.visit_basic_block_data(bb, &body[bb]);
693 let target = match body[bb].terminator().kind {
694 TerminatorKind::Goto { target } |
695 TerminatorKind::FalseUnwind { real_target: target, .. } |
696 TerminatorKind::Drop { target, .. } |
697 TerminatorKind::DropAndReplace { target, .. } |
698 TerminatorKind::Assert { target, .. } |
699 TerminatorKind::Call { destination: Some((_, target)), .. } => {
703 // Non-terminating calls cannot produce any value.
704 TerminatorKind::Call { destination: None, .. } => {
708 TerminatorKind::SwitchInt {..} |
709 TerminatorKind::Resume |
710 TerminatorKind::Abort |
711 TerminatorKind::GeneratorDrop |
712 TerminatorKind::Yield { .. } |
713 TerminatorKind::Unreachable |
714 TerminatorKind::FalseEdges { .. } => None,
716 TerminatorKind::Return => {
723 Some(target) if !seen_blocks.contains(target.index()) => {
727 if !self.tcx.sess.opts.debugging_opts.unleash_the_miri_inside_of_you {
728 self.tcx.sess.delay_span_bug(
730 "complex control flow is forbidden in a const context",
738 // The new validation pass should agree with the old when running on simple const bodies
739 // (e.g. no `if` or `loop`).
740 if !use_new_validator {
741 let mut new_errors = validator.take_errors();
743 // FIXME: each checker sometimes emits the same error with the same span twice in a row.
747 if self.errors != new_errors {
751 std::mem::replace(&mut self.errors, vec![]),
757 self.qualifs_in_local(RETURN_PLACE).encode_to_bits()
761 impl<'a, 'tcx> Visitor<'tcx> for Checker<'a, 'tcx> {
764 place_base: &PlaceBase<'tcx>,
765 context: PlaceContext,
768 self.super_place_base(place_base, context, location);
770 PlaceBase::Local(_) => {}
771 PlaceBase::Static(box Static{ kind: StaticKind::Promoted(_, _), .. }) => {
774 PlaceBase::Static(box Static{ kind: StaticKind::Static, def_id, .. }) => {
778 .any(|attr| attr.check_name(sym::thread_local)) {
779 if self.mode.requires_const_checking() && !self.suppress_errors {
780 self.record_error(ops::ThreadLocalAccess);
781 span_err!(self.tcx.sess, self.span, E0625,
782 "thread-local statics cannot be \
783 accessed at compile-time");
788 // Only allow statics (not consts) to refer to other statics.
789 if self.mode == Mode::Static || self.mode == Mode::StaticMut {
794 if self.mode.requires_const_checking() && !self.suppress_errors {
795 self.record_error(ops::StaticAccess);
796 let mut err = struct_span_err!(self.tcx.sess, self.span, E0013,
797 "{}s cannot refer to statics, use \
798 a constant instead", self.mode);
799 if self.tcx.sess.teach(&err.get_code().unwrap()) {
801 "Static and const variables can refer to other const variables. \
802 But a const variable cannot refer to a static variable."
805 "To fix this, the value can be extracted as a const and then used."
814 fn visit_projection_elem(
816 place_base: &PlaceBase<'tcx>,
817 proj_base: &[PlaceElem<'tcx>],
818 elem: &PlaceElem<'tcx>,
819 context: PlaceContext,
823 "visit_projection_elem: place_base={:?} proj_base={:?} elem={:?} \
824 context={:?} location={:?}",
832 self.super_projection_elem(place_base, proj_base, elem, context, location);
835 ProjectionElem::Deref => {
836 if context.is_mutating_use() {
837 // `not_const` errors out in const contexts
838 self.not_const(ops::MutDeref)
840 let base_ty = Place::ty_from(place_base, proj_base, self.body, self.tcx).ty;
842 Mode::NonConstFn => {}
843 _ if self.suppress_errors => {}
845 if let ty::RawPtr(_) = base_ty.kind {
846 if !self.tcx.features().const_raw_ptr_deref {
847 self.record_error(ops::RawPtrDeref);
849 &self.tcx.sess.parse_sess, sym::const_raw_ptr_deref,
850 self.span, GateIssue::Language,
852 "dereferencing raw pointers in {}s is unstable",
862 ProjectionElem::ConstantIndex {..} |
863 ProjectionElem::Subslice {..} |
864 ProjectionElem::Field(..) |
865 ProjectionElem::Index(_) => {
866 let base_ty = Place::ty_from(place_base, proj_base, self.body, self.tcx).ty;
867 if let Some(def) = base_ty.ty_adt_def() {
871 if !self.tcx.features().const_fn_union
872 && !self.suppress_errors
874 self.record_error(ops::UnionAccess);
876 &self.tcx.sess.parse_sess, sym::const_fn_union,
877 self.span, GateIssue::Language,
878 "unions in const fn are unstable",
893 ProjectionElem::Downcast(..) => {
894 self.not_const(ops::Downcast)
899 fn visit_operand(&mut self, operand: &Operand<'tcx>, location: Location) {
900 debug!("visit_operand: operand={:?} location={:?}", operand, location);
901 self.super_operand(operand, location);
904 Operand::Move(ref place) => {
905 // Mark the consumed locals to indicate later drops are noops.
906 if let Some(local) = place.as_local() {
907 self.cx.per_local[NeedsDrop].remove(local);
911 Operand::Constant(_) => {}
915 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
916 debug!("visit_rvalue: rvalue={:?} location={:?}", rvalue, location);
918 // Check nested operands and places.
919 if let Rvalue::Ref(_, kind, ref place) = *rvalue {
920 // Special-case reborrows.
921 let mut reborrow_place = None;
922 if let &[ref proj_base @ .., elem] = place.projection.as_ref() {
923 if elem == ProjectionElem::Deref {
924 let base_ty = Place::ty_from(&place.base, proj_base, self.body, self.tcx).ty;
925 if let ty::Ref(..) = base_ty.kind {
926 reborrow_place = Some(proj_base);
931 if let Some(proj) = reborrow_place {
932 let ctx = match kind {
933 BorrowKind::Shared => PlaceContext::NonMutatingUse(
934 NonMutatingUseContext::SharedBorrow,
936 BorrowKind::Shallow => PlaceContext::NonMutatingUse(
937 NonMutatingUseContext::ShallowBorrow,
939 BorrowKind::Unique => PlaceContext::NonMutatingUse(
940 NonMutatingUseContext::UniqueBorrow,
942 BorrowKind::Mut { .. } => PlaceContext::MutatingUse(
943 MutatingUseContext::Borrow,
946 self.visit_place_base(&place.base, ctx, location);
947 self.visit_projection(&place.base, proj, ctx, location);
949 self.super_rvalue(rvalue, location);
952 self.super_rvalue(rvalue, location);
958 Rvalue::UnaryOp(UnOp::Neg, _) |
959 Rvalue::UnaryOp(UnOp::Not, _) |
960 Rvalue::NullaryOp(NullOp::SizeOf, _) |
961 Rvalue::CheckedBinaryOp(..) |
962 Rvalue::Cast(CastKind::Pointer(_), ..) |
963 Rvalue::Discriminant(..) |
966 Rvalue::Aggregate(..) => {}
968 Rvalue::Cast(CastKind::Misc, ref operand, cast_ty) => {
969 let operand_ty = operand.ty(self.body, self.tcx);
970 let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast");
971 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
972 match (cast_in, cast_out) {
973 (CastTy::Ptr(_), CastTy::Int(_)) |
974 (CastTy::FnPtr, CastTy::Int(_)) if self.mode != Mode::NonConstFn => {
976 if !self.tcx.features().const_raw_ptr_to_usize_cast
977 && !self.suppress_errors
979 // in const fn and constants require the feature gate
980 // FIXME: make it unsafe inside const fn and constants
981 self.record_error(ops::RawPtrToIntCast);
983 &self.tcx.sess.parse_sess, sym::const_raw_ptr_to_usize_cast,
984 self.span, GateIssue::Language,
986 "casting pointers to integers in {}s is unstable",
996 Rvalue::BinaryOp(op, ref lhs, _) => {
997 if let ty::RawPtr(_) | ty::FnPtr(..) = lhs.ty(self.body, self.tcx).kind {
998 assert!(op == BinOp::Eq || op == BinOp::Ne ||
999 op == BinOp::Le || op == BinOp::Lt ||
1000 op == BinOp::Ge || op == BinOp::Gt ||
1001 op == BinOp::Offset);
1003 unleash_miri!(self);
1004 if self.mode.requires_const_checking() &&
1005 !self.tcx.features().const_compare_raw_pointers &&
1006 !self.suppress_errors
1008 self.record_error(ops::RawPtrComparison);
1009 // require the feature gate inside constants and const fn
1010 // FIXME: make it unsafe to use these operations
1012 &self.tcx.sess.parse_sess,
1013 sym::const_compare_raw_pointers,
1015 GateIssue::Language,
1016 &format!("comparing raw pointers inside {}", self.mode),
1022 Rvalue::NullaryOp(NullOp::Box, _) => {
1023 unleash_miri!(self);
1024 if self.mode.requires_const_checking() && !self.suppress_errors {
1025 self.record_error(ops::HeapAllocation);
1026 let mut err = struct_span_err!(self.tcx.sess, self.span, E0010,
1027 "allocations are not allowed in {}s", self.mode);
1028 err.span_label(self.span, format!("allocation not allowed in {}s", self.mode));
1029 if self.tcx.sess.teach(&err.get_code().unwrap()) {
1031 "The value of statics and constants must be known at compile time, \
1032 and they live for the entire lifetime of a program. Creating a boxed \
1033 value allocates memory on the heap at runtime, and therefore cannot \
1034 be done at compile time."
1043 fn visit_terminator_kind(&mut self,
1044 kind: &TerminatorKind<'tcx>,
1045 location: Location) {
1046 debug!("visit_terminator_kind: kind={:?} location={:?}", kind, location);
1047 if let TerminatorKind::Call { ref func, ref args, ref destination, .. } = *kind {
1048 if let Some((ref dest, _)) = *destination {
1049 self.assign(dest, ValueSource::Call {
1052 return_ty: dest.ty(self.body, self.tcx).ty,
1056 let fn_ty = func.ty(self.body, self.tcx);
1058 ty::FnDef(def_id, _) => {
1059 match self.tcx.fn_sig(def_id).abi() {
1060 Abi::RustIntrinsic |
1061 Abi::PlatformIntrinsic => {
1062 assert!(!self.tcx.is_const_fn(def_id));
1063 match &*self.tcx.item_name(def_id).as_str() {
1064 // special intrinsic that can be called diretly without an intrinsic
1065 // feature gate needs a language feature gate
1067 if self.mode.requires_const_checking()
1068 && !self.suppress_errors
1070 // const eval transmute calls only with the feature gate
1071 if !self.tcx.features().const_transmute {
1072 self.record_error(ops::Transmute);
1074 &self.tcx.sess.parse_sess, sym::const_transmute,
1075 self.span, GateIssue::Language,
1076 &format!("The use of std::mem::transmute() \
1077 is gated in {}s", self.mode));
1082 // no need to check feature gates, intrinsics are only callable
1083 // from the libstd or with forever unstable feature gates
1088 // In normal functions no calls are feature-gated.
1089 if self.mode.requires_const_checking() {
1090 let unleash_miri = self
1095 .unleash_the_miri_inside_of_you;
1096 if self.tcx.is_const_fn(def_id)
1098 || self.suppress_errors
1100 // stable const fns or unstable const fns
1101 // with their feature gate active
1102 // FIXME(eddyb) move stability checks from `is_const_fn` here.
1103 } else if self.is_const_panic_fn(def_id) {
1104 // Check the const_panic feature gate.
1105 // FIXME: cannot allow this inside `allow_internal_unstable`
1106 // because that would make `panic!` insta stable in constants,
1107 // since the macro is marked with the attribute.
1108 if !self.tcx.features().const_panic {
1109 // Don't allow panics in constants without the feature gate.
1110 self.record_error(ops::Panic);
1112 &self.tcx.sess.parse_sess,
1115 GateIssue::Language,
1116 &format!("panicking in {}s is unstable", self.mode),
1119 } else if let Some(feature)
1120 = self.tcx.is_unstable_const_fn(def_id) {
1121 // Check `#[unstable]` const fns or `#[rustc_const_unstable]`
1122 // functions without the feature gate active in this crate in
1123 // order to report a better error message than the one below.
1124 if !self.span.allows_unstable(feature) {
1125 self.record_error(ops::FnCallUnstable(def_id, feature));
1126 let mut err = self.tcx.sess.struct_span_err(self.span,
1127 &format!("`{}` is not yet stable as a const fn",
1128 self.tcx.def_path_str(def_id)));
1129 if nightly_options::is_nightly_build() {
1131 "add `#![feature({})]` to the \
1132 crate attributes to enable",
1138 self.record_error(ops::FnCallNonConst(def_id));
1139 let mut err = struct_span_err!(
1143 "calls in {}s are limited to constant functions, \
1144 tuple structs and tuple variants",
1154 unleash_miri!(self);
1155 if self.mode.requires_const_checking() && !self.suppress_errors {
1156 self.record_error(ops::FnCallIndirect);
1157 let mut err = self.tcx.sess.struct_span_err(
1159 "function pointers are not allowed in const fn"
1165 self.not_const(ops::FnCallOther);
1169 // Check callee and argument operands.
1170 self.visit_operand(func, location);
1172 self.visit_operand(arg, location);
1174 } else if let TerminatorKind::Drop {
1175 location: ref place, ..
1176 } | TerminatorKind::DropAndReplace {
1177 location: ref place, ..
1180 TerminatorKind::DropAndReplace { .. } => {}
1181 _ => self.super_terminator_kind(kind, location),
1184 // Deny *any* live drops anywhere other than functions.
1185 if self.mode.requires_const_checking() && !self.suppress_errors {
1186 unleash_miri!(self);
1187 // HACK(eddyb): emulate a bit of dataflow analysis,
1188 // conservatively, that drop elaboration will do.
1189 let needs_drop = if let Some(local) = place.as_local() {
1190 if NeedsDrop::in_local(self, local) {
1191 Some(self.body.local_decls[local].source_info.span)
1199 if let Some(span) = needs_drop {
1200 // Double-check the type being dropped, to minimize false positives.
1201 let ty = place.ty(self.body, self.tcx).ty;
1202 if ty.needs_drop(self.tcx, self.param_env) {
1203 self.record_error_spanned(ops::LiveDrop, span);
1204 struct_span_err!(self.tcx.sess, span, E0493,
1205 "destructors cannot be evaluated at compile-time")
1206 .span_label(span, format!("{}s cannot evaluate destructors",
1214 TerminatorKind::DropAndReplace { ref value, .. } => {
1215 self.assign(place, ValueSource::DropAndReplace(value), location);
1216 self.visit_operand(value, location);
1221 // Qualify any operands inside other terminators.
1222 self.super_terminator_kind(kind, location);
1226 fn visit_assign(&mut self,
1228 rvalue: &Rvalue<'tcx>,
1229 location: Location) {
1230 debug!("visit_assign: dest={:?} rvalue={:?} location={:?}", dest, rvalue, location);
1231 self.assign(dest, ValueSource::Rvalue(rvalue), location);
1233 self.visit_rvalue(rvalue, location);
1236 fn visit_source_info(&mut self, source_info: &SourceInfo) {
1237 debug!("visit_source_info: source_info={:?}", source_info);
1238 self.span = source_info.span;
1241 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
1242 debug!("visit_statement: statement={:?} location={:?}", statement, location);
1243 match statement.kind {
1244 StatementKind::Assign(..) => {
1245 self.super_statement(statement, location);
1247 StatementKind::FakeRead(FakeReadCause::ForMatchedPlace, _) => {
1248 if !self.tcx.sess.opts.debugging_opts.unleash_the_miri_inside_of_you {
1249 self.tcx.sess.delay_span_bug(
1251 "complex control flow is forbidden in a const context",
1255 // FIXME(eddyb) should these really do nothing?
1256 StatementKind::FakeRead(..) |
1257 StatementKind::SetDiscriminant { .. } |
1258 StatementKind::StorageLive(_) |
1259 StatementKind::StorageDead(_) |
1260 StatementKind::InlineAsm {..} |
1261 StatementKind::Retag { .. } |
1262 StatementKind::AscribeUserType(..) |
1263 StatementKind::Nop => {}
1268 pub fn provide(providers: &mut Providers<'_>) {
1269 *providers = Providers {
1275 // FIXME(eddyb) this is only left around for the validation logic
1276 // in `promote_consts`, see the comment in `validate_operand`.
1277 pub(super) const QUALIF_ERROR_BIT: u8 = 1 << 2;
1279 fn mir_const_qualif(tcx: TyCtxt<'_>, def_id: DefId) -> u8 {
1280 // N.B., this `borrow()` is guaranteed to be valid (i.e., the value
1281 // cannot yet be stolen), because `mir_validated()`, which steals
1282 // from `mir_const(), forces this query to execute before
1283 // performing the steal.
1284 let body = &tcx.mir_const(def_id).borrow();
1286 if body.return_ty().references_error() {
1287 tcx.sess.delay_span_bug(body.span, "mir_const_qualif: MIR had errors");
1288 return QUALIF_ERROR_BIT;
1291 Checker::new(tcx, def_id, body, Mode::Const).check_const()
1294 pub struct QualifyAndPromoteConstants<'tcx> {
1295 pub promoted: Cell<IndexVec<Promoted, Body<'tcx>>>,
1298 impl<'tcx> Default for QualifyAndPromoteConstants<'tcx> {
1299 fn default() -> Self {
1300 QualifyAndPromoteConstants {
1301 promoted: Cell::new(IndexVec::new()),
1306 impl<'tcx> MirPass<'tcx> for QualifyAndPromoteConstants<'tcx> {
1307 fn run_pass(&self, tcx: TyCtxt<'tcx>, src: MirSource<'tcx>, body: &mut Body<'tcx>) {
1308 // There's not really any point in promoting errorful MIR.
1309 if body.return_ty().references_error() {
1310 tcx.sess.delay_span_bug(body.span, "QualifyAndPromoteConstants: MIR had errors");
1314 if src.promoted.is_some() {
1318 let def_id = src.def_id();
1319 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
1321 let mode = determine_mode(tcx, hir_id, def_id);
1323 debug!("run_pass: mode={:?}", mode);
1324 if let Mode::NonConstFn = mode {
1325 // No need to const-check a non-const `fn` now that we don't do promotion here.
1327 } else if let Mode::ConstFn = mode {
1328 let mut checker = Checker::new(tcx, def_id, body, mode);
1329 let use_min_const_fn_checks =
1330 !tcx.sess.opts.debugging_opts.unleash_the_miri_inside_of_you &&
1331 tcx.is_min_const_fn(def_id);
1332 if use_min_const_fn_checks {
1333 // Enforce `min_const_fn` for stable `const fn`s.
1334 use super::qualify_min_const_fn::is_min_const_fn;
1335 if let Err((span, err)) = is_min_const_fn(tcx, def_id, body) {
1336 error_min_const_fn_violation(tcx, span, err);
1341 // `check_const` should not produce any errors, but better safe than sorry
1343 // Enforce a constant-like CFG for `const fn`.
1344 checker.check_const();
1346 check_short_circuiting_in_const_local(tcx, body, mode);
1349 Mode::Const => tcx.mir_const_qualif(def_id),
1350 _ => Checker::new(tcx, def_id, body, mode).check_const(),
1354 if mode == Mode::Static && !tcx.has_attr(def_id, sym::thread_local) {
1355 // `static`s (not `static mut`s) which are not `#[thread_local]` must be `Sync`.
1356 check_static_is_sync(tcx, body, hir_id);
1361 fn determine_mode(tcx: TyCtxt<'_>, hir_id: HirId, def_id: DefId) -> Mode {
1362 match tcx.hir().body_owner_kind(hir_id) {
1363 hir::BodyOwnerKind::Closure => Mode::NonConstFn,
1364 hir::BodyOwnerKind::Fn if tcx.is_const_fn(def_id) => Mode::ConstFn,
1365 hir::BodyOwnerKind::Fn => Mode::NonConstFn,
1366 hir::BodyOwnerKind::Const => Mode::Const,
1367 hir::BodyOwnerKind::Static(hir::Mutability::Immutable) => Mode::Static,
1368 hir::BodyOwnerKind::Static(hir::Mutability::Mutable) => Mode::StaticMut,
1372 fn error_min_const_fn_violation(tcx: TyCtxt<'_>, span: Span, msg: Cow<'_, str>) {
1373 struct_span_err!(tcx.sess, span, E0723, "{}", msg)
1374 .note("for more information, see issue https://github.com/rust-lang/rust/issues/57563")
1375 .help("add `#![feature(const_fn)]` to the crate attributes to enable")
1379 fn check_short_circuiting_in_const_local(tcx: TyCtxt<'_>, body: &mut Body<'tcx>, mode: Mode) {
1380 if body.control_flow_destroyed.is_empty() {
1384 let mut locals = body.vars_iter();
1385 if let Some(local) = locals.next() {
1386 let span = body.local_decls[local].source_info.span;
1387 let mut error = tcx.sess.struct_span_err(
1390 "new features like let bindings are not permitted in {}s \
1391 which also use short circuiting operators",
1395 for (span, kind) in body.control_flow_destroyed.iter() {
1398 &format!("use of {} here does not actually short circuit due to \
1399 the const evaluator presently not being able to do control flow. \
1400 See https://github.com/rust-lang/rust/issues/49146 for more \
1401 information.", kind),
1404 for local in locals {
1405 let span = body.local_decls[local].source_info.span;
1406 error.span_note(span, "more locals defined here");
1412 fn check_static_is_sync(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>, hir_id: HirId) {
1413 let ty = body.return_ty();
1414 tcx.infer_ctxt().enter(|infcx| {
1415 let cause = traits::ObligationCause::new(body.span, hir_id, traits::SharedStatic);
1416 let mut fulfillment_cx = traits::FulfillmentContext::new();
1417 let sync_def_id = tcx.require_lang_item(lang_items::SyncTraitLangItem, Some(body.span));
1418 fulfillment_cx.register_bound(&infcx, ty::ParamEnv::empty(), ty, sync_def_id, cause);
1419 if let Err(err) = fulfillment_cx.select_all_or_error(&infcx) {
1420 infcx.report_fulfillment_errors(&err, None, false);
1425 fn validator_mismatch(
1428 mut old_errors: Vec<(Span, String)>,
1429 mut new_errors: Vec<(Span, String)>,
1431 error!("old validator: {:?}", old_errors);
1432 error!("new validator: {:?}", new_errors);
1434 // ICE on nightly if the validators do not emit exactly the same errors.
1435 // Users can supress this panic with an unstable compiler flag (hopefully after
1436 // filing an issue).
1437 let opts = &tcx.sess.opts;
1438 let strict_validation_enabled = opts.unstable_features.is_nightly_build()
1439 && !opts.debugging_opts.suppress_const_validation_back_compat_ice;
1441 if !strict_validation_enabled {
1445 // If this difference would cause a regression from the old to the new or vice versa, trigger
1447 if old_errors.is_empty() || new_errors.is_empty() {
1448 span_bug!(body.span, "{}", VALIDATOR_MISMATCH_ERR);
1451 // HACK: Borrows that would allow mutation are forbidden in const contexts, but they cause the
1452 // new validator to be more conservative about when a dropped local has been moved out of.
1454 // Supress the mismatch ICE in cases where the validators disagree only on the number of
1455 // `LiveDrop` errors and both observe the same sequence of `MutBorrow`s.
1457 let is_live_drop = |(_, s): &mut (_, String)| s.starts_with("LiveDrop");
1458 let is_mut_borrow = |(_, s): &&(_, String)| s.starts_with("MutBorrow");
1460 let old_live_drops: Vec<_> = old_errors.drain_filter(is_live_drop).collect();
1461 let new_live_drops: Vec<_> = new_errors.drain_filter(is_live_drop).collect();
1463 let only_live_drops_differ = old_live_drops != new_live_drops && old_errors == new_errors;
1465 let old_mut_borrows = old_errors.iter().filter(is_mut_borrow);
1466 let new_mut_borrows = new_errors.iter().filter(is_mut_borrow);
1468 let at_least_one_mut_borrow = old_mut_borrows.clone().next().is_some();
1470 if only_live_drops_differ && at_least_one_mut_borrow && old_mut_borrows.eq(new_mut_borrows) {
1474 span_bug!(body.span, "{}", VALIDATOR_MISMATCH_ERR);
1477 const VALIDATOR_MISMATCH_ERR: &str =
1478 r"Disagreement between legacy and dataflow-based const validators.
1479 After filing an issue, use `-Zsuppress-const-validation-back-compat-ice` to compile your code.";