1 //! The `Visitor` responsible for actually checking a `mir::Body` for invalid operations.
3 use rustc::middle::lang_items;
4 use rustc::mir::visit::{MutatingUseContext, NonMutatingUseContext, PlaceContext, Visitor};
6 use rustc::traits::{self, TraitEngine};
7 use rustc::ty::cast::CastTy;
8 use rustc::ty::{self, TyCtxt};
9 use rustc_error_codes::*;
10 use rustc_errors::struct_span_err;
11 use rustc_hir::{def_id::DefId, HirId};
12 use rustc_index::bit_set::BitSet;
13 use rustc_span::symbol::sym;
19 use self::old_dataflow::IndirectlyMutableLocals;
20 use super::ops::{self, NonConstOp};
21 use super::qualifs::{self, HasMutInterior, NeedsDrop};
22 use super::resolver::FlowSensitiveAnalysis;
23 use super::{is_lang_panic_fn, ConstKind, Item, Qualif};
24 use crate::const_eval::{is_const_fn, is_unstable_const_fn};
25 use crate::dataflow::{self as old_dataflow, generic as dataflow};
27 pub type IndirectlyMutableResults<'mir, 'tcx> =
28 old_dataflow::DataflowResultsCursor<'mir, 'tcx, IndirectlyMutableLocals<'mir, 'tcx>>;
30 struct QualifCursor<'a, 'mir, 'tcx, Q: Qualif> {
31 cursor: dataflow::ResultsCursor<'mir, 'tcx, FlowSensitiveAnalysis<'a, 'mir, 'tcx, Q>>,
32 in_any_value_of_ty: BitSet<Local>,
35 impl<Q: Qualif> QualifCursor<'a, 'mir, 'tcx, Q> {
36 pub fn new(q: Q, item: &'a Item<'mir, 'tcx>, dead_unwinds: &BitSet<BasicBlock>) -> Self {
37 let analysis = FlowSensitiveAnalysis::new(q, item);
39 dataflow::Engine::new(item.tcx, &item.body, item.def_id, dead_unwinds, analysis)
40 .iterate_to_fixpoint();
41 let cursor = dataflow::ResultsCursor::new(*item.body, results);
43 let mut in_any_value_of_ty = BitSet::new_empty(item.body.local_decls.len());
44 for (local, decl) in item.body.local_decls.iter_enumerated() {
45 if Q::in_any_value_of_ty(item, decl.ty) {
46 in_any_value_of_ty.insert(local);
50 QualifCursor { cursor, in_any_value_of_ty }
54 pub struct Qualifs<'a, 'mir, 'tcx> {
55 has_mut_interior: QualifCursor<'a, 'mir, 'tcx, HasMutInterior>,
56 needs_drop: QualifCursor<'a, 'mir, 'tcx, NeedsDrop>,
57 indirectly_mutable: IndirectlyMutableResults<'mir, 'tcx>,
60 impl Qualifs<'a, 'mir, 'tcx> {
61 fn indirectly_mutable(&mut self, local: Local, location: Location) -> bool {
62 self.indirectly_mutable.seek(location);
63 self.indirectly_mutable.get().contains(local)
66 /// Returns `true` if `local` is `NeedsDrop` at the given `Location`.
68 /// Only updates the cursor if absolutely necessary
69 fn needs_drop_lazy_seek(&mut self, local: Local, location: Location) -> bool {
70 if !self.needs_drop.in_any_value_of_ty.contains(local) {
74 self.needs_drop.cursor.seek_before(location);
75 self.needs_drop.cursor.get().contains(local) || self.indirectly_mutable(local, location)
78 /// Returns `true` if `local` is `HasMutInterior` at the given `Location`.
80 /// Only updates the cursor if absolutely necessary.
81 fn has_mut_interior_lazy_seek(&mut self, local: Local, location: Location) -> bool {
82 if !self.has_mut_interior.in_any_value_of_ty.contains(local) {
86 self.has_mut_interior.cursor.seek_before(location);
87 self.has_mut_interior.cursor.get().contains(local)
88 || self.indirectly_mutable(local, location)
91 /// Returns `true` if `local` is `HasMutInterior`, but requires the `has_mut_interior` and
92 /// `indirectly_mutable` cursors to be updated beforehand.
93 fn has_mut_interior_eager_seek(&self, local: Local) -> bool {
94 if !self.has_mut_interior.in_any_value_of_ty.contains(local) {
98 self.has_mut_interior.cursor.get().contains(local)
99 || self.indirectly_mutable.get().contains(local)
102 fn in_return_place(&mut self, item: &Item<'_, 'tcx>) -> ConstQualifs {
103 // Find the `Return` terminator if one exists.
105 // If no `Return` terminator exists, this MIR is divergent. Just return the conservative
106 // qualifs for the return type.
107 let return_block = item
111 .find(|(_, block)| match block.terminator().kind {
112 TerminatorKind::Return => true,
117 let return_block = match return_block {
118 None => return qualifs::in_any_value_of_ty(item, item.body.return_ty()),
122 let return_loc = item.body.terminator_loc(return_block);
125 needs_drop: self.needs_drop_lazy_seek(RETURN_PLACE, return_loc),
126 has_mut_interior: self.has_mut_interior_lazy_seek(RETURN_PLACE, return_loc),
131 pub struct Validator<'a, 'mir, 'tcx> {
132 item: &'a Item<'mir, 'tcx>,
133 qualifs: Qualifs<'a, 'mir, 'tcx>,
135 /// The span of the current statement.
139 impl Deref for Validator<'_, 'mir, 'tcx> {
140 type Target = Item<'mir, 'tcx>;
142 fn deref(&self) -> &Self::Target {
147 impl Validator<'a, 'mir, 'tcx> {
148 pub fn new(item: &'a Item<'mir, 'tcx>) -> Self {
149 let dead_unwinds = BitSet::new_empty(item.body.basic_blocks().len());
151 let needs_drop = QualifCursor::new(NeedsDrop, item, &dead_unwinds);
153 let has_mut_interior = QualifCursor::new(HasMutInterior, item, &dead_unwinds);
155 let indirectly_mutable = old_dataflow::do_dataflow(
159 &item.tcx.get_attrs(item.def_id),
161 old_dataflow::IndirectlyMutableLocals::new(item.tcx, *item.body, item.param_env),
162 |_, local| old_dataflow::DebugFormatted::new(&local),
165 let indirectly_mutable =
166 old_dataflow::DataflowResultsCursor::new(indirectly_mutable, *item.body);
168 let qualifs = Qualifs { needs_drop, has_mut_interior, indirectly_mutable };
170 Validator { span: item.body.span, item, qualifs }
173 pub fn check_body(&mut self) {
174 let Item { tcx, body, def_id, const_kind, .. } = *self.item;
176 let use_min_const_fn_checks = (const_kind == Some(ConstKind::ConstFn)
177 && crate::const_eval::is_min_const_fn(tcx, def_id))
178 && !tcx.sess.opts.debugging_opts.unleash_the_miri_inside_of_you;
180 if use_min_const_fn_checks {
181 // Enforce `min_const_fn` for stable `const fn`s.
182 use crate::transform::qualify_min_const_fn::is_min_const_fn;
183 if let Err((span, err)) = is_min_const_fn(tcx, def_id, &body) {
184 error_min_const_fn_violation(tcx, span, err);
189 check_short_circuiting_in_const_local(self.item);
191 if body.is_cfg_cyclic() {
192 // We can't provide a good span for the error here, but this should be caught by the
193 // HIR const-checker anyways.
194 self.check_op_spanned(ops::Loop, body.span);
197 self.visit_body(body);
199 // Ensure that the end result is `Sync` in a non-thread local `static`.
200 let should_check_for_sync =
201 const_kind == Some(ConstKind::Static) && !tcx.has_attr(def_id, sym::thread_local);
203 if should_check_for_sync {
204 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
205 check_return_ty_is_sync(tcx, &body, hir_id);
209 pub fn qualifs_in_return_place(&mut self) -> ConstQualifs {
210 self.qualifs.in_return_place(self.item)
213 /// Emits an error at the given `span` if an expression cannot be evaluated in the current
215 pub fn check_op_spanned<O>(&mut self, op: O, span: Span)
219 trace!("check_op: op={:?}", op);
221 if op.is_allowed_in_item(self) {
225 // If an operation is supported in miri (and is not already controlled by a feature gate) it
226 // can be turned on with `-Zunleash-the-miri-inside-of-you`.
227 let is_unleashable = O::IS_SUPPORTED_IN_MIRI && O::feature_gate(self.tcx).is_none();
229 if is_unleashable && self.tcx.sess.opts.debugging_opts.unleash_the_miri_inside_of_you {
230 self.tcx.sess.span_warn(span, "skipping const checks");
234 op.emit_error(self, span);
237 /// Emits an error if an expression cannot be evaluated in the current context.
238 pub fn check_op(&mut self, op: impl NonConstOp) {
239 let span = self.span;
240 self.check_op_spanned(op, span)
243 fn check_static(&mut self, def_id: DefId, span: Span) {
244 let is_thread_local = self.tcx.has_attr(def_id, sym::thread_local);
246 self.check_op_spanned(ops::ThreadLocalAccess, span)
248 self.check_op_spanned(ops::StaticAccess, span)
252 fn check_immutable_borrow_like(&mut self, location: Location, place: &Place<'tcx>) {
253 // FIXME: Change the `in_*` methods to take a `FnMut` so we don't have to manually
254 // seek the cursors beforehand.
255 self.qualifs.has_mut_interior.cursor.seek_before(location);
256 self.qualifs.indirectly_mutable.seek(location);
258 let borrowed_place_has_mut_interior = HasMutInterior::in_place(
260 &|local| self.qualifs.has_mut_interior_eager_seek(local),
264 if borrowed_place_has_mut_interior {
265 self.check_op(ops::CellBorrow);
270 impl Visitor<'tcx> for Validator<'_, 'mir, 'tcx> {
271 fn visit_basic_block_data(&mut self, bb: BasicBlock, block: &BasicBlockData<'tcx>) {
272 trace!("visit_basic_block_data: bb={:?} is_cleanup={:?}", bb, block.is_cleanup);
274 // Just as the old checker did, we skip const-checking basic blocks on the unwind path.
275 // These blocks often drop locals that would otherwise be returned from the function.
277 // FIXME: This shouldn't be unsound since a panic at compile time will cause a compiler
278 // error anyway, but maybe we should do more here?
279 if block.is_cleanup {
283 self.super_basic_block_data(bb, block);
286 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
287 trace!("visit_rvalue: rvalue={:?} location={:?}", rvalue, location);
289 // Special-case reborrows to be more like a copy of a reference.
291 Rvalue::Ref(_, kind, ref place) => {
292 if let Some(reborrowed_proj) = place_as_reborrow(self.tcx, *self.body, place) {
293 let ctx = match kind {
294 BorrowKind::Shared => {
295 PlaceContext::NonMutatingUse(NonMutatingUseContext::SharedBorrow)
297 BorrowKind::Shallow => {
298 PlaceContext::NonMutatingUse(NonMutatingUseContext::ShallowBorrow)
300 BorrowKind::Unique => {
301 PlaceContext::NonMutatingUse(NonMutatingUseContext::UniqueBorrow)
303 BorrowKind::Mut { .. } => {
304 PlaceContext::MutatingUse(MutatingUseContext::Borrow)
307 self.visit_place_base(&place.base, ctx, location);
308 self.visit_projection(&place.base, reborrowed_proj, ctx, location);
312 Rvalue::AddressOf(mutbl, ref place) => {
313 if let Some(reborrowed_proj) = place_as_reborrow(self.tcx, *self.body, place) {
314 let ctx = match mutbl {
316 PlaceContext::NonMutatingUse(NonMutatingUseContext::AddressOf)
318 Mutability::Mut => PlaceContext::MutatingUse(MutatingUseContext::AddressOf),
320 self.visit_place_base(&place.base, ctx, location);
321 self.visit_projection(&place.base, reborrowed_proj, ctx, location);
328 self.super_rvalue(rvalue, location);
333 | Rvalue::UnaryOp(UnOp::Neg, _)
334 | Rvalue::UnaryOp(UnOp::Not, _)
335 | Rvalue::NullaryOp(NullOp::SizeOf, _)
336 | Rvalue::CheckedBinaryOp(..)
337 | Rvalue::Cast(CastKind::Pointer(_), ..)
338 | Rvalue::Discriminant(..)
340 | Rvalue::Aggregate(..) => {}
342 Rvalue::Ref(_, kind @ BorrowKind::Mut { .. }, ref place)
343 | Rvalue::Ref(_, kind @ BorrowKind::Unique, ref place) => {
344 let ty = place.ty(*self.body, self.tcx).ty;
345 let is_allowed = match ty.kind {
346 // Inside a `static mut`, `&mut [...]` is allowed.
347 ty::Array(..) | ty::Slice(_) if self.const_kind() == ConstKind::StaticMut => {
351 // FIXME(ecstaticmorse): We could allow `&mut []` inside a const context given
352 // that this is merely a ZST and it is already eligible for promotion.
353 // This may require an RFC?
355 ty::Array(_, len) if len.try_eval_usize(cx.tcx, cx.param_env) == Some(0)
362 if let BorrowKind::Mut { .. } = kind {
363 self.check_op(ops::MutBorrow);
365 self.check_op(ops::CellBorrow);
370 Rvalue::AddressOf(Mutability::Mut, _) => self.check_op(ops::MutAddressOf),
372 // At the moment, `PlaceBase::Static` is only used for promoted MIR.
373 Rvalue::Ref(_, BorrowKind::Shared, ref place)
374 | Rvalue::Ref(_, BorrowKind::Shallow, ref place)
375 | Rvalue::AddressOf(Mutability::Not, ref place)
376 if matches!(place.base, PlaceBase::Static(_)) =>
378 bug!("Saw a promoted during const-checking, which must run before promotion")
381 Rvalue::Ref(_, BorrowKind::Shared, ref place)
382 | Rvalue::Ref(_, BorrowKind::Shallow, ref place) => {
383 self.check_immutable_borrow_like(location, place)
386 Rvalue::AddressOf(Mutability::Not, ref place) => {
387 self.check_immutable_borrow_like(location, place)
390 Rvalue::Cast(CastKind::Misc, ref operand, cast_ty) => {
391 let operand_ty = operand.ty(*self.body, self.tcx);
392 let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast");
393 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
395 if let (CastTy::Ptr(_), CastTy::Int(_)) | (CastTy::FnPtr, CastTy::Int(_)) =
398 self.check_op(ops::RawPtrToIntCast);
402 Rvalue::BinaryOp(op, ref lhs, _) => {
403 if let ty::RawPtr(_) | ty::FnPtr(..) = lhs.ty(*self.body, self.tcx).kind {
411 || op == BinOp::Offset
414 self.check_op(ops::RawPtrComparison);
418 Rvalue::NullaryOp(NullOp::Box, _) => {
419 self.check_op(ops::HeapAllocation);
426 place_base: &PlaceBase<'tcx>,
427 context: PlaceContext,
431 "visit_place_base: place_base={:?} context={:?} location={:?}",
436 self.super_place_base(place_base, context, location);
439 PlaceBase::Local(_) => {}
440 PlaceBase::Static(_) => {
441 bug!("Promotion must be run after const validation");
446 fn visit_operand(&mut self, op: &Operand<'tcx>, location: Location) {
447 self.super_operand(op, location);
448 if let Operand::Constant(c) = op {
449 if let Some(def_id) = c.check_static_ptr(self.tcx) {
450 self.check_static(def_id, self.span);
454 fn visit_projection_elem(
456 place_base: &PlaceBase<'tcx>,
457 proj_base: &[PlaceElem<'tcx>],
458 elem: &PlaceElem<'tcx>,
459 context: PlaceContext,
463 "visit_projection_elem: place_base={:?} proj_base={:?} elem={:?} \
464 context={:?} location={:?}",
472 self.super_projection_elem(place_base, proj_base, elem, context, location);
475 ProjectionElem::Deref => {
476 let base_ty = Place::ty_from(place_base, proj_base, *self.body, self.tcx).ty;
477 if let ty::RawPtr(_) = base_ty.kind {
478 if proj_base.is_empty() {
479 if let (PlaceBase::Local(local), []) = (place_base, proj_base) {
480 let decl = &self.body.local_decls[*local];
481 if let LocalInfo::StaticRef { def_id, .. } = decl.local_info {
482 let span = decl.source_info.span;
483 self.check_static(def_id, span);
488 self.check_op(ops::RawPtrDeref);
491 if context.is_mutating_use() {
492 self.check_op(ops::MutDeref);
496 ProjectionElem::ConstantIndex { .. }
497 | ProjectionElem::Subslice { .. }
498 | ProjectionElem::Field(..)
499 | ProjectionElem::Index(_) => {
500 let base_ty = Place::ty_from(place_base, proj_base, *self.body, self.tcx).ty;
501 match base_ty.ty_adt_def() {
502 Some(def) if def.is_union() => {
503 self.check_op(ops::UnionAccess);
510 ProjectionElem::Downcast(..) => {
511 self.check_op(ops::Downcast);
516 fn visit_source_info(&mut self, source_info: &SourceInfo) {
517 trace!("visit_source_info: source_info={:?}", source_info);
518 self.span = source_info.span;
521 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
522 trace!("visit_statement: statement={:?} location={:?}", statement, location);
524 match statement.kind {
525 StatementKind::Assign(..) | StatementKind::SetDiscriminant { .. } => {
526 self.super_statement(statement, location);
528 StatementKind::FakeRead(FakeReadCause::ForMatchedPlace, _) => {
529 self.check_op(ops::IfOrMatch);
531 // FIXME(eddyb) should these really do nothing?
532 StatementKind::FakeRead(..)
533 | StatementKind::StorageLive(_)
534 | StatementKind::StorageDead(_)
535 | StatementKind::InlineAsm { .. }
536 | StatementKind::Retag { .. }
537 | StatementKind::AscribeUserType(..)
538 | StatementKind::Nop => {}
542 fn visit_terminator_kind(&mut self, kind: &TerminatorKind<'tcx>, location: Location) {
543 trace!("visit_terminator_kind: kind={:?} location={:?}", kind, location);
544 self.super_terminator_kind(kind, location);
547 TerminatorKind::Call { func, .. } => {
548 let fn_ty = func.ty(*self.body, self.tcx);
550 let def_id = match fn_ty.kind {
551 ty::FnDef(def_id, _) => def_id,
554 self.check_op(ops::FnCallIndirect);
558 self.check_op(ops::FnCallOther);
563 // At this point, we are calling a function whose `DefId` is known...
564 if is_const_fn(self.tcx, def_id) {
568 if is_lang_panic_fn(self.tcx, def_id) {
569 self.check_op(ops::Panic);
570 } else if let Some(feature) = is_unstable_const_fn(self.tcx, def_id) {
571 // Exempt unstable const fns inside of macros with
572 // `#[allow_internal_unstable]`.
573 if !self.span.allows_unstable(feature) {
574 self.check_op(ops::FnCallUnstable(def_id, feature));
577 self.check_op(ops::FnCallNonConst(def_id));
581 // Forbid all `Drop` terminators unless the place being dropped is a local with no
582 // projections that cannot be `NeedsDrop`.
583 TerminatorKind::Drop { location: dropped_place, .. }
584 | TerminatorKind::DropAndReplace { location: dropped_place, .. } => {
585 let mut err_span = self.span;
587 // Check to see if the type of this place can ever have a drop impl. If not, this
588 // `Drop` terminator is frivolous.
590 dropped_place.ty(*self.body, self.tcx).ty.needs_drop(self.tcx, self.param_env);
596 let needs_drop = if let Some(local) = dropped_place.as_local() {
597 // Use the span where the local was declared as the span of the drop error.
598 err_span = self.body.local_decls[local].source_info.span;
599 self.qualifs.needs_drop_lazy_seek(local, location)
605 self.check_op_spanned(ops::LiveDrop, err_span);
614 fn error_min_const_fn_violation(tcx: TyCtxt<'_>, span: Span, msg: Cow<'_, str>) {
615 struct_span_err!(tcx.sess, span, E0723, "{}", msg)
616 .note("for more information, see issue https://github.com/rust-lang/rust/issues/57563")
617 .help("add `#![feature(const_fn)]` to the crate attributes to enable")
621 fn check_short_circuiting_in_const_local(item: &Item<'_, 'tcx>) {
622 let body = item.body;
624 if body.control_flow_destroyed.is_empty() {
628 let mut locals = body.vars_iter();
629 if let Some(local) = locals.next() {
630 let span = body.local_decls[local].source_info.span;
631 let mut error = item.tcx.sess.struct_span_err(
634 "new features like let bindings are not permitted in {}s \
635 which also use short circuiting operators",
639 for (span, kind) in body.control_flow_destroyed.iter() {
643 "use of {} here does not actually short circuit due to \
644 the const evaluator presently not being able to do control flow. \
645 See https://github.com/rust-lang/rust/issues/49146 for more \
651 for local in locals {
652 let span = body.local_decls[local].source_info.span;
653 error.span_note(span, "more locals defined here");
659 fn check_return_ty_is_sync(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, hir_id: HirId) {
660 let ty = body.return_ty();
661 tcx.infer_ctxt().enter(|infcx| {
662 let cause = traits::ObligationCause::new(body.span, hir_id, traits::SharedStatic);
663 let mut fulfillment_cx = traits::FulfillmentContext::new();
664 let sync_def_id = tcx.require_lang_item(lang_items::SyncTraitLangItem, Some(body.span));
665 fulfillment_cx.register_bound(&infcx, ty::ParamEnv::empty(), ty, sync_def_id, cause);
666 if let Err(err) = fulfillment_cx.select_all_or_error(&infcx) {
667 infcx.report_fulfillment_errors(&err, None, false);
672 fn place_as_reborrow(
675 place: &'a Place<'tcx>,
676 ) -> Option<&'a [PlaceElem<'tcx>]> {
677 place.projection.split_last().and_then(|(outermost, inner)| {
678 if outermost != &ProjectionElem::Deref {
682 // A borrow of a `static` also looks like `&(*_1)` in the MIR, but `_1` is a `const`
683 // that points to the allocation for the static. Don't treat these as reborrows.
684 if let PlaceBase::Local(local) = place.base {
685 if body.local_decls[local].is_ref_to_static() {
690 // Ensure the type being derefed is a reference and not a raw pointer.
692 // This is sufficient to prevent an access to a `static mut` from being marked as a
693 // reborrow, even if the check above were to disappear.
694 let inner_ty = Place::ty_from(&place.base, inner, body, tcx).ty;
695 match inner_ty.kind {
696 ty::Ref(..) => Some(inner),