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.local, ctx, location);
308 self.visit_projection(&place.local, 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.local, ctx, location);
321 self.visit_projection(&place.local, 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 Rvalue::Ref(_, BorrowKind::Shared, ref place)
373 | Rvalue::Ref(_, BorrowKind::Shallow, ref place) => {
374 self.check_immutable_borrow_like(location, place)
377 Rvalue::AddressOf(Mutability::Not, ref place) => {
378 self.check_immutable_borrow_like(location, place)
381 Rvalue::Cast(CastKind::Misc, ref operand, cast_ty) => {
382 let operand_ty = operand.ty(*self.body, self.tcx);
383 let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast");
384 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
386 if let (CastTy::Ptr(_), CastTy::Int(_)) | (CastTy::FnPtr, CastTy::Int(_)) =
389 self.check_op(ops::RawPtrToIntCast);
393 Rvalue::BinaryOp(op, ref lhs, _) => {
394 if let ty::RawPtr(_) | ty::FnPtr(..) = lhs.ty(*self.body, self.tcx).kind {
402 || op == BinOp::Offset
405 self.check_op(ops::RawPtrComparison);
409 Rvalue::NullaryOp(NullOp::Box, _) => {
410 self.check_op(ops::HeapAllocation);
415 fn visit_place_base(&mut self, place_local: &Local, context: PlaceContext, location: Location) {
417 "visit_place_base: place_local={:?} context={:?} location={:?}",
422 self.super_place_base(place_local, context, location);
425 fn visit_operand(&mut self, op: &Operand<'tcx>, location: Location) {
426 self.super_operand(op, location);
427 if let Operand::Constant(c) = op {
428 if let Some(def_id) = c.check_static_ptr(self.tcx) {
429 self.check_static(def_id, self.span);
433 fn visit_projection_elem(
436 proj_base: &[PlaceElem<'tcx>],
437 elem: &PlaceElem<'tcx>,
438 context: PlaceContext,
442 "visit_projection_elem: place_local={:?} proj_base={:?} elem={:?} \
443 context={:?} location={:?}",
451 self.super_projection_elem(place_local, proj_base, elem, context, location);
454 ProjectionElem::Deref => {
455 let base_ty = Place::ty_from(place_local, proj_base, *self.body, self.tcx).ty;
456 if let ty::RawPtr(_) = base_ty.kind {
457 if proj_base.is_empty() {
458 if let (local, []) = (place_local, proj_base) {
459 let decl = &self.body.local_decls[*local];
460 if let LocalInfo::StaticRef { def_id, .. } = decl.local_info {
461 let span = decl.source_info.span;
462 self.check_static(def_id, span);
467 self.check_op(ops::RawPtrDeref);
470 if context.is_mutating_use() {
471 self.check_op(ops::MutDeref);
475 ProjectionElem::ConstantIndex { .. }
476 | ProjectionElem::Subslice { .. }
477 | ProjectionElem::Field(..)
478 | ProjectionElem::Index(_) => {
479 let base_ty = Place::ty_from(place_local, proj_base, *self.body, self.tcx).ty;
480 match base_ty.ty_adt_def() {
481 Some(def) if def.is_union() => {
482 self.check_op(ops::UnionAccess);
489 ProjectionElem::Downcast(..) => {
490 self.check_op(ops::Downcast);
495 fn visit_source_info(&mut self, source_info: &SourceInfo) {
496 trace!("visit_source_info: source_info={:?}", source_info);
497 self.span = source_info.span;
500 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
501 trace!("visit_statement: statement={:?} location={:?}", statement, location);
503 match statement.kind {
504 StatementKind::Assign(..) | StatementKind::SetDiscriminant { .. } => {
505 self.super_statement(statement, location);
507 StatementKind::FakeRead(FakeReadCause::ForMatchedPlace, _) => {
508 self.check_op(ops::IfOrMatch);
510 // FIXME(eddyb) should these really do nothing?
511 StatementKind::FakeRead(..)
512 | StatementKind::StorageLive(_)
513 | StatementKind::StorageDead(_)
514 | StatementKind::InlineAsm { .. }
515 | StatementKind::Retag { .. }
516 | StatementKind::AscribeUserType(..)
517 | StatementKind::Nop => {}
521 fn visit_terminator_kind(&mut self, kind: &TerminatorKind<'tcx>, location: Location) {
522 trace!("visit_terminator_kind: kind={:?} location={:?}", kind, location);
523 self.super_terminator_kind(kind, location);
526 TerminatorKind::Call { func, .. } => {
527 let fn_ty = func.ty(*self.body, self.tcx);
529 let def_id = match fn_ty.kind {
530 ty::FnDef(def_id, _) => def_id,
533 self.check_op(ops::FnCallIndirect);
537 self.check_op(ops::FnCallOther);
542 // At this point, we are calling a function whose `DefId` is known...
543 if is_const_fn(self.tcx, def_id) {
547 if is_lang_panic_fn(self.tcx, def_id) {
548 self.check_op(ops::Panic);
549 } else if let Some(feature) = is_unstable_const_fn(self.tcx, def_id) {
550 // Exempt unstable const fns inside of macros with
551 // `#[allow_internal_unstable]`.
552 if !self.span.allows_unstable(feature) {
553 self.check_op(ops::FnCallUnstable(def_id, feature));
556 self.check_op(ops::FnCallNonConst(def_id));
560 // Forbid all `Drop` terminators unless the place being dropped is a local with no
561 // projections that cannot be `NeedsDrop`.
562 TerminatorKind::Drop { location: dropped_place, .. }
563 | TerminatorKind::DropAndReplace { location: dropped_place, .. } => {
564 let mut err_span = self.span;
566 // Check to see if the type of this place can ever have a drop impl. If not, this
567 // `Drop` terminator is frivolous.
569 dropped_place.ty(*self.body, self.tcx).ty.needs_drop(self.tcx, self.param_env);
575 let needs_drop = if let Some(local) = dropped_place.as_local() {
576 // Use the span where the local was declared as the span of the drop error.
577 err_span = self.body.local_decls[local].source_info.span;
578 self.qualifs.needs_drop_lazy_seek(local, location)
584 self.check_op_spanned(ops::LiveDrop, err_span);
593 fn error_min_const_fn_violation(tcx: TyCtxt<'_>, span: Span, msg: Cow<'_, str>) {
594 struct_span_err!(tcx.sess, span, E0723, "{}", msg)
595 .note("for more information, see issue https://github.com/rust-lang/rust/issues/57563")
596 .help("add `#![feature(const_fn)]` to the crate attributes to enable")
600 fn check_short_circuiting_in_const_local(item: &Item<'_, 'tcx>) {
601 let body = item.body;
603 if body.control_flow_destroyed.is_empty() {
607 let mut locals = body.vars_iter();
608 if let Some(local) = locals.next() {
609 let span = body.local_decls[local].source_info.span;
610 let mut error = item.tcx.sess.struct_span_err(
613 "new features like let bindings are not permitted in {}s \
614 which also use short circuiting operators",
618 for (span, kind) in body.control_flow_destroyed.iter() {
622 "use of {} here does not actually short circuit due to \
623 the const evaluator presently not being able to do control flow. \
624 See https://github.com/rust-lang/rust/issues/49146 for more \
630 for local in locals {
631 let span = body.local_decls[local].source_info.span;
632 error.span_note(span, "more locals defined here");
638 fn check_return_ty_is_sync(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, hir_id: HirId) {
639 let ty = body.return_ty();
640 tcx.infer_ctxt().enter(|infcx| {
641 let cause = traits::ObligationCause::new(body.span, hir_id, traits::SharedStatic);
642 let mut fulfillment_cx = traits::FulfillmentContext::new();
643 let sync_def_id = tcx.require_lang_item(lang_items::SyncTraitLangItem, Some(body.span));
644 fulfillment_cx.register_bound(&infcx, ty::ParamEnv::empty(), ty, sync_def_id, cause);
645 if let Err(err) = fulfillment_cx.select_all_or_error(&infcx) {
646 infcx.report_fulfillment_errors(&err, None, false);
651 fn place_as_reborrow(
654 place: &'a Place<'tcx>,
655 ) -> Option<&'a [PlaceElem<'tcx>]> {
656 place.projection.split_last().and_then(|(outermost, inner)| {
657 if outermost != &ProjectionElem::Deref {
661 // A borrow of a `static` also looks like `&(*_1)` in the MIR, but `_1` is a `const`
662 // that points to the allocation for the static. Don't treat these as reborrows.
663 if body.local_decls[place.local].is_ref_to_static() {
667 // Ensure the type being derefed is a reference and not a raw pointer.
669 // This is sufficient to prevent an access to a `static mut` from being marked as a
670 // reborrow, even if the check above were to disappear.
671 let inner_ty = Place::ty_from(&place.local, inner, body, tcx).ty;
672 match inner_ty.kind {
673 ty::Ref(..) => Some(inner),