1 //! The `Visitor` responsible for actually checking a `mir::Body` for invalid operations.
3 use rustc::hir::{HirId, def_id::DefId};
4 use rustc::middle::lang_items;
5 use rustc::mir::visit::{PlaceContext, Visitor, MutatingUseContext, NonMutatingUseContext};
7 use rustc::traits::{self, TraitEngine};
8 use rustc::ty::cast::CastTy;
9 use rustc::ty::{self, TyCtxt};
10 use rustc_index::bit_set::BitSet;
11 use rustc_target::spec::abi::Abi;
12 use rustc_error_codes::*;
13 use syntax::symbol::sym;
19 use crate::dataflow::{self as old_dataflow, generic as dataflow};
20 use self::old_dataflow::IndirectlyMutableLocals;
21 use super::ops::{self, NonConstOp};
22 use super::qualifs::{self, HasMutInterior, NeedsDrop};
23 use super::resolver::FlowSensitiveAnalysis;
24 use super::{ConstKind, Item, Qualif, is_lang_panic_fn};
26 pub type IndirectlyMutableResults<'mir, 'tcx> =
27 old_dataflow::DataflowResultsCursor<'mir, 'tcx, IndirectlyMutableLocals<'mir, 'tcx>>;
29 struct QualifCursor<'a, 'mir, 'tcx, Q: Qualif> {
30 cursor: dataflow::ResultsCursor<'mir, 'tcx, FlowSensitiveAnalysis<'a, 'mir, 'tcx, Q>>,
31 in_any_value_of_ty: BitSet<Local>,
34 impl<Q: Qualif> QualifCursor<'a, 'mir, 'tcx, Q> {
37 item: &'a Item<'mir, 'tcx>,
38 dead_unwinds: &BitSet<BasicBlock>,
40 let analysis = FlowSensitiveAnalysis::new(q, item);
42 dataflow::Engine::new(item.tcx, item.body, item.def_id, dead_unwinds, analysis)
43 .iterate_to_fixpoint();
44 let cursor = dataflow::ResultsCursor::new(item.body, results);
46 let mut in_any_value_of_ty = BitSet::new_empty(item.body.local_decls.len());
47 for (local, decl) in item.body.local_decls.iter_enumerated() {
48 if Q::in_any_value_of_ty(item, decl.ty) {
49 in_any_value_of_ty.insert(local);
60 pub struct Qualifs<'a, 'mir, 'tcx> {
61 has_mut_interior: QualifCursor<'a, 'mir, 'tcx, HasMutInterior>,
62 needs_drop: QualifCursor<'a, 'mir, 'tcx, NeedsDrop>,
63 indirectly_mutable: IndirectlyMutableResults<'mir, 'tcx>,
66 impl Qualifs<'a, 'mir, 'tcx> {
67 fn indirectly_mutable(&mut self, local: Local, location: Location) -> bool {
68 self.indirectly_mutable.seek(location);
69 self.indirectly_mutable.get().contains(local)
72 /// Returns `true` if `local` is `NeedsDrop` at the given `Location`.
74 /// Only updates the cursor if absolutely necessary
75 fn needs_drop_lazy_seek(&mut self, local: Local, location: Location) -> bool {
76 if !self.needs_drop.in_any_value_of_ty.contains(local) {
80 self.needs_drop.cursor.seek_before(location);
81 self.needs_drop.cursor.get().contains(local)
82 || self.indirectly_mutable(local, location)
85 /// Returns `true` if `local` is `HasMutInterior` at the given `Location`.
87 /// Only updates the cursor if absolutely necessary.
88 fn has_mut_interior_lazy_seek(&mut self, local: Local, location: Location) -> bool {
89 if !self.has_mut_interior.in_any_value_of_ty.contains(local) {
93 self.has_mut_interior.cursor.seek_before(location);
94 self.has_mut_interior.cursor.get().contains(local)
95 || self.indirectly_mutable(local, location)
98 /// Returns `true` if `local` is `HasMutInterior`, but requires the `has_mut_interior` and
99 /// `indirectly_mutable` cursors to be updated beforehand.
100 fn has_mut_interior_eager_seek(&self, local: Local) -> bool {
101 if !self.has_mut_interior.in_any_value_of_ty.contains(local) {
105 self.has_mut_interior.cursor.get().contains(local)
106 || self.indirectly_mutable.get().contains(local)
109 fn in_return_place(&mut self, item: &Item<'_, 'tcx>) -> ConstQualifs {
110 // Find the `Return` terminator if one exists.
112 // If no `Return` terminator exists, this MIR is divergent. Just return the conservative
113 // qualifs for the return type.
114 let return_block = item.body
118 match block.terminator().kind {
119 TerminatorKind::Return => true,
125 let return_block = match return_block {
126 None => return qualifs::in_any_value_of_ty(item, item.body.return_ty()),
130 let return_loc = item.body.terminator_loc(return_block);
133 needs_drop: self.needs_drop_lazy_seek(RETURN_PLACE, return_loc),
134 has_mut_interior: self.has_mut_interior_lazy_seek(RETURN_PLACE, return_loc),
139 pub struct Validator<'a, 'mir, 'tcx> {
140 item: &'a Item<'mir, 'tcx>,
141 qualifs: Qualifs<'a, 'mir, 'tcx>,
143 /// The span of the current statement.
147 impl Deref for Validator<'_, 'mir, 'tcx> {
148 type Target = Item<'mir, 'tcx>;
150 fn deref(&self) -> &Self::Target {
155 impl Validator<'a, 'mir, 'tcx> {
157 item: &'a Item<'mir, 'tcx>,
159 let dead_unwinds = BitSet::new_empty(item.body.basic_blocks().len());
161 let needs_drop = QualifCursor::new(
167 let has_mut_interior = QualifCursor::new(
173 let indirectly_mutable = old_dataflow::do_dataflow(
177 &item.tcx.get_attrs(item.def_id),
179 old_dataflow::IndirectlyMutableLocals::new(item.tcx, item.body, item.param_env),
180 |_, local| old_dataflow::DebugFormatted::new(&local),
183 let indirectly_mutable = old_dataflow::DataflowResultsCursor::new(
188 let qualifs = Qualifs {
195 span: item.body.span,
201 pub fn check_body(&mut self) {
202 let Item { tcx, body, def_id, const_kind, .. } = *self.item;
204 let use_min_const_fn_checks =
205 tcx.is_min_const_fn(def_id)
206 && !tcx.sess.opts.debugging_opts.unleash_the_miri_inside_of_you;
208 if use_min_const_fn_checks {
209 // Enforce `min_const_fn` for stable `const fn`s.
210 use crate::transform::qualify_min_const_fn::is_min_const_fn;
211 if let Err((span, err)) = is_min_const_fn(tcx, def_id, body) {
212 error_min_const_fn_violation(tcx, span, err);
217 check_short_circuiting_in_const_local(self.item);
219 if body.is_cfg_cyclic() {
220 // We can't provide a good span for the error here, but this should be caught by the
221 // HIR const-checker anyways.
222 self.check_op_spanned(ops::Loop, body.span);
225 self.visit_body(body);
227 // Ensure that the end result is `Sync` in a non-thread local `static`.
228 let should_check_for_sync = const_kind == Some(ConstKind::Static)
229 && !tcx.has_attr(def_id, sym::thread_local);
231 if should_check_for_sync {
232 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
233 check_return_ty_is_sync(tcx, body, hir_id);
237 pub fn qualifs_in_return_place(&mut self) -> ConstQualifs {
238 self.qualifs.in_return_place(self.item)
241 /// Emits an error at the given `span` if an expression cannot be evaluated in the current
243 pub fn check_op_spanned<O>(&mut self, op: O, span: Span)
247 trace!("check_op: op={:?}", op);
249 if op.is_allowed_in_item(self) {
253 // If an operation is supported in miri (and is not already controlled by a feature gate) it
254 // can be turned on with `-Zunleash-the-miri-inside-of-you`.
255 let is_unleashable = O::IS_SUPPORTED_IN_MIRI
256 && O::feature_gate(self.tcx).is_none();
258 if is_unleashable && self.tcx.sess.opts.debugging_opts.unleash_the_miri_inside_of_you {
259 self.tcx.sess.span_warn(span, "skipping const checks");
263 op.emit_error(self, span);
266 /// Emits an error if an expression cannot be evaluated in the current context.
267 pub fn check_op(&mut self, op: impl NonConstOp) {
268 let span = self.span;
269 self.check_op_spanned(op, span)
272 fn check_static(&mut self, def_id: DefId, span: Span) {
273 let is_thread_local = self.tcx.has_attr(def_id, sym::thread_local);
275 self.check_op_spanned(ops::ThreadLocalAccess, span)
277 self.check_op_spanned(ops::StaticAccess, span)
282 impl Visitor<'tcx> for Validator<'_, 'mir, 'tcx> {
283 fn visit_basic_block_data(
286 block: &BasicBlockData<'tcx>,
288 trace!("visit_basic_block_data: bb={:?} is_cleanup={:?}", bb, block.is_cleanup);
290 // Just as the old checker did, we skip const-checking basic blocks on the unwind path.
291 // These blocks often drop locals that would otherwise be returned from the function.
293 // FIXME: This shouldn't be unsound since a panic at compile time will cause a compiler
294 // error anyway, but maybe we should do more here?
295 if block.is_cleanup {
299 self.super_basic_block_data(bb, block);
302 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
303 trace!("visit_rvalue: rvalue={:?} location={:?}", rvalue, location);
305 // Special-case reborrows to be more like a copy of a reference.
306 if let Rvalue::Ref(_, kind, ref place) = *rvalue {
307 if let Some(reborrowed_proj) = place_as_reborrow(self.tcx, self.body, place) {
308 let ctx = match kind {
309 BorrowKind::Shared => PlaceContext::NonMutatingUse(
310 NonMutatingUseContext::SharedBorrow,
312 BorrowKind::Shallow => PlaceContext::NonMutatingUse(
313 NonMutatingUseContext::ShallowBorrow,
315 BorrowKind::Unique => PlaceContext::NonMutatingUse(
316 NonMutatingUseContext::UniqueBorrow,
318 BorrowKind::Mut { .. } => PlaceContext::MutatingUse(
319 MutatingUseContext::Borrow,
322 self.visit_place_base(&place.base, ctx, location);
323 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)
345 let ty = place.ty(self.body, self.tcx).ty;
346 let is_allowed = match ty.kind {
347 // Inside a `static mut`, `&mut [...]` is allowed.
348 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)
363 self.check_op(ops::MutBorrow(kind));
367 // At the moment, `PlaceBase::Static` is only used for promoted MIR.
368 | Rvalue::Ref(_, BorrowKind::Shared, ref place)
369 | Rvalue::Ref(_, BorrowKind::Shallow, ref place)
370 if matches!(place.base, PlaceBase::Static(_))
371 => bug!("Saw a promoted during const-checking, which must run before promotion"),
373 | Rvalue::Ref(_, kind @ BorrowKind::Shared, ref place)
374 | Rvalue::Ref(_, kind @ BorrowKind::Shallow, ref place)
376 // FIXME: Change the `in_*` methods to take a `FnMut` so we don't have to manually
377 // seek the cursors beforehand.
378 self.qualifs.has_mut_interior.cursor.seek_before(location);
379 self.qualifs.indirectly_mutable.seek(location);
381 let borrowed_place_has_mut_interior = HasMutInterior::in_place(
383 &|local| self.qualifs.has_mut_interior_eager_seek(local),
387 if borrowed_place_has_mut_interior {
388 self.check_op(ops::MutBorrow(kind));
392 Rvalue::Cast(CastKind::Misc, ref operand, cast_ty) => {
393 let operand_ty = operand.ty(self.body, self.tcx);
394 let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast");
395 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
397 if let (CastTy::Ptr(_), CastTy::Int(_))
398 | (CastTy::FnPtr, CastTy::Int(_)) = (cast_in, cast_out) {
399 self.check_op(ops::RawPtrToIntCast);
403 Rvalue::BinaryOp(op, ref lhs, _) => {
404 if let ty::RawPtr(_) | ty::FnPtr(..) = lhs.ty(self.body, self.tcx).kind {
405 assert!(op == BinOp::Eq || op == BinOp::Ne ||
406 op == BinOp::Le || op == BinOp::Lt ||
407 op == BinOp::Ge || op == BinOp::Gt ||
408 op == BinOp::Offset);
411 self.check_op(ops::RawPtrComparison);
415 Rvalue::NullaryOp(NullOp::Box, _) => {
416 self.check_op(ops::HeapAllocation);
423 place_base: &PlaceBase<'tcx>,
424 context: PlaceContext,
428 "visit_place_base: place_base={:?} context={:?} location={:?}",
433 self.super_place_base(place_base, context, location);
436 PlaceBase::Local(_) => {}
437 PlaceBase::Static(_) => {
438 bug!("Promotion must be run after const validation");
448 self.super_operand(op, location);
449 if let Operand::Constant(c) = op {
450 if let Some(def_id) = c.check_static_ptr(self.tcx) {
451 self.check_static(def_id, self.span);
456 fn visit_projection_elem(
458 place_base: &PlaceBase<'tcx>,
459 proj_base: &[PlaceElem<'tcx>],
460 elem: &PlaceElem<'tcx>,
461 context: PlaceContext,
465 "visit_projection_elem: place_base={:?} proj_base={:?} elem={:?} \
466 context={:?} location={:?}",
474 self.super_projection_elem(place_base, proj_base, elem, context, location);
477 ProjectionElem::Deref => {
478 let base_ty = Place::ty_from(place_base, proj_base, self.body, self.tcx).ty;
479 if let ty::RawPtr(_) = base_ty.kind {
480 if proj_base.is_empty() {
481 if let (PlaceBase::Local(local), []) = (place_base, proj_base) {
482 let decl = &self.body.local_decls[*local];
483 if let LocalInfo::StaticRef { def_id, .. } = decl.local_info {
484 let span = decl.source_info.span;
485 self.check_static(def_id, span);
490 self.check_op(ops::RawPtrDeref);
493 if context.is_mutating_use() {
494 self.check_op(ops::MutDeref);
498 ProjectionElem::ConstantIndex {..} |
499 ProjectionElem::Subslice {..} |
500 ProjectionElem::Field(..) |
501 ProjectionElem::Index(_) => {
502 let base_ty = Place::ty_from(place_base, proj_base, self.body, self.tcx).ty;
503 match base_ty.ty_adt_def() {
504 Some(def) if def.is_union() => {
505 self.check_op(ops::UnionAccess);
512 ProjectionElem::Downcast(..) => {
513 self.check_op(ops::Downcast);
519 fn visit_source_info(&mut self, source_info: &SourceInfo) {
520 trace!("visit_source_info: source_info={:?}", source_info);
521 self.span = source_info.span;
524 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
525 trace!("visit_statement: statement={:?} location={:?}", statement, location);
527 match statement.kind {
528 StatementKind::Assign(..) => {
529 self.super_statement(statement, location);
531 StatementKind::FakeRead(FakeReadCause::ForMatchedPlace, _) => {
532 self.check_op(ops::IfOrMatch);
534 // FIXME(eddyb) should these really do nothing?
535 StatementKind::FakeRead(..) |
536 StatementKind::SetDiscriminant { .. } |
537 StatementKind::StorageLive(_) |
538 StatementKind::StorageDead(_) |
539 StatementKind::InlineAsm {..} |
540 StatementKind::Retag { .. } |
541 StatementKind::AscribeUserType(..) |
542 StatementKind::Nop => {}
546 fn visit_terminator_kind(&mut self, kind: &TerminatorKind<'tcx>, location: Location) {
547 trace!("visit_terminator_kind: kind={:?} location={:?}", kind, location);
548 self.super_terminator_kind(kind, location);
551 TerminatorKind::Call { func, .. } => {
552 let fn_ty = func.ty(self.body, self.tcx);
554 let def_id = match fn_ty.kind {
555 ty::FnDef(def_id, _) => def_id,
558 self.check_op(ops::FnCallIndirect);
562 self.check_op(ops::FnCallOther);
567 // At this point, we are calling a function whose `DefId` is known...
569 if let Abi::RustIntrinsic | Abi::PlatformIntrinsic = self.tcx.fn_sig(def_id).abi() {
570 assert!(!self.tcx.is_const_fn(def_id));
572 if self.tcx.item_name(def_id) == sym::transmute {
573 self.check_op(ops::Transmute);
577 // To preserve the current semantics, we return early, allowing all
578 // intrinsics (except `transmute`) to pass unchecked to miri.
580 // FIXME: We should keep a whitelist of allowed intrinsics (or at least a
581 // blacklist of unimplemented ones) and fail here instead.
585 if self.tcx.is_const_fn(def_id) {
589 if is_lang_panic_fn(self.tcx, def_id) {
590 self.check_op(ops::Panic);
591 } else if let Some(feature) = self.tcx.is_unstable_const_fn(def_id) {
592 // Exempt unstable const fns inside of macros with
593 // `#[allow_internal_unstable]`.
594 if !self.span.allows_unstable(feature) {
595 self.check_op(ops::FnCallUnstable(def_id, feature));
598 self.check_op(ops::FnCallNonConst(def_id));
603 // Forbid all `Drop` terminators unless the place being dropped is a local with no
604 // projections that cannot be `NeedsDrop`.
605 | TerminatorKind::Drop { location: dropped_place, .. }
606 | TerminatorKind::DropAndReplace { location: dropped_place, .. }
608 let mut err_span = self.span;
610 // Check to see if the type of this place can ever have a drop impl. If not, this
611 // `Drop` terminator is frivolous.
612 let ty_needs_drop = dropped_place
613 .ty(self.body, self.tcx)
615 .needs_drop(self.tcx, self.param_env);
621 let needs_drop = if let Some(local) = dropped_place.as_local() {
622 // Use the span where the local was declared as the span of the drop error.
623 err_span = self.body.local_decls[local].source_info.span;
624 self.qualifs.needs_drop_lazy_seek(local, location)
630 self.check_op_spanned(ops::LiveDrop, err_span);
639 fn error_min_const_fn_violation(tcx: TyCtxt<'_>, span: Span, msg: Cow<'_, str>) {
640 struct_span_err!(tcx.sess, span, E0723, "{}", msg)
641 .note("for more information, see issue https://github.com/rust-lang/rust/issues/57563")
642 .help("add `#![feature(const_fn)]` to the crate attributes to enable")
646 fn check_short_circuiting_in_const_local(item: &Item<'_, 'tcx>) {
647 let body = item.body;
649 if body.control_flow_destroyed.is_empty() {
653 let mut locals = body.vars_iter();
654 if let Some(local) = locals.next() {
655 let span = body.local_decls[local].source_info.span;
656 let mut error = item.tcx.sess.struct_span_err(
659 "new features like let bindings are not permitted in {}s \
660 which also use short circuiting operators",
664 for (span, kind) in body.control_flow_destroyed.iter() {
667 &format!("use of {} here does not actually short circuit due to \
668 the const evaluator presently not being able to do control flow. \
669 See https://github.com/rust-lang/rust/issues/49146 for more \
670 information.", kind),
673 for local in locals {
674 let span = body.local_decls[local].source_info.span;
675 error.span_note(span, "more locals defined here");
681 fn check_return_ty_is_sync(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, hir_id: HirId) {
682 let ty = body.return_ty();
683 tcx.infer_ctxt().enter(|infcx| {
684 let cause = traits::ObligationCause::new(body.span, hir_id, traits::SharedStatic);
685 let mut fulfillment_cx = traits::FulfillmentContext::new();
686 let sync_def_id = tcx.require_lang_item(lang_items::SyncTraitLangItem, Some(body.span));
687 fulfillment_cx.register_bound(&infcx, ty::ParamEnv::empty(), ty, sync_def_id, cause);
688 if let Err(err) = fulfillment_cx.select_all_or_error(&infcx) {
689 infcx.report_fulfillment_errors(&err, None, false);
694 fn place_as_reborrow(
697 place: &'a Place<'tcx>,
698 ) -> Option<&'a [PlaceElem<'tcx>]> {
702 .and_then(|(outermost, inner)| {
703 if outermost != &ProjectionElem::Deref {
707 // A borrow of a `static` also looks like `&(*_1)` in the MIR, but `_1` is a `const`
708 // that points to the allocation for the static. Don't treat these as reborrows.
709 if let PlaceBase::Local(local) = place.base {
710 if body.local_decls[local].is_ref_to_static() {
715 // Ensure the type being derefed is a reference and not a raw pointer.
717 // This is sufficient to prevent an access to a `static mut` from being marked as a
718 // reborrow, even if the check above were to disappear.
719 let inner_ty = Place::ty_from(&place.base, inner, body, tcx).ty;
720 match inner_ty.kind {
721 ty::Ref(..) => Some(inner),