1 //! The `Visitor` responsible for actually checking a `mir::Body` for invalid operations.
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;
20 use crate::dataflow::{self as old_dataflow, generic as dataflow};
21 use self::old_dataflow::IndirectlyMutableLocals;
22 use super::ops::{self, NonConstOp};
23 use super::qualifs::{HasMutInterior, NeedsDrop};
24 use super::resolver::FlowSensitiveAnalysis;
25 use super::{ConstKind, Item, Qualif, QualifSet, is_lang_panic_fn};
27 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
28 pub enum CheckOpResult {
34 pub type IndirectlyMutableResults<'mir, 'tcx> =
35 old_dataflow::DataflowResultsCursor<'mir, 'tcx, IndirectlyMutableLocals<'mir, 'tcx>>;
37 struct QualifCursor<'a, 'mir, 'tcx, Q: Qualif> {
38 cursor: dataflow::ResultsCursor<'mir, 'tcx, FlowSensitiveAnalysis<'a, 'mir, 'tcx, Q>>,
39 in_any_value_of_ty: BitSet<Local>,
42 impl<Q: Qualif> QualifCursor<'a, 'mir, 'tcx, Q> {
45 item: &'a Item<'mir, 'tcx>,
46 dead_unwinds: &BitSet<BasicBlock>,
48 let analysis = FlowSensitiveAnalysis::new(q, item);
50 dataflow::Engine::new(item.tcx, item.body, item.def_id, dead_unwinds, analysis)
51 .iterate_to_fixpoint();
52 let cursor = dataflow::ResultsCursor::new(item.body, results);
54 let mut in_any_value_of_ty = BitSet::new_empty(item.body.local_decls.len());
55 for (local, decl) in item.body.local_decls.iter_enumerated() {
56 if Q::in_any_value_of_ty(item, decl.ty) {
57 in_any_value_of_ty.insert(local);
68 pub struct Qualifs<'a, 'mir, 'tcx> {
69 has_mut_interior: QualifCursor<'a, 'mir, 'tcx, HasMutInterior>,
70 needs_drop: QualifCursor<'a, 'mir, 'tcx, NeedsDrop>,
71 indirectly_mutable: IndirectlyMutableResults<'mir, 'tcx>,
74 impl Qualifs<'a, 'mir, 'tcx> {
75 fn indirectly_mutable(&mut self, local: Local, location: Location) -> bool {
76 self.indirectly_mutable.seek(location);
77 self.indirectly_mutable.get().contains(local)
80 /// Returns `true` if `local` is `NeedsDrop` at the given `Location`.
82 /// Only updates the cursor if absolutely necessary
83 fn needs_drop_lazy_seek(&mut self, local: Local, location: Location) -> bool {
84 if !self.needs_drop.in_any_value_of_ty.contains(local) {
88 self.needs_drop.cursor.seek_before(location);
89 self.needs_drop.cursor.get().contains(local)
90 || self.indirectly_mutable(local, location)
93 /// Returns `true` if `local` is `HasMutInterior` at the given `Location`.
95 /// Only updates the cursor if absolutely necessary.
96 fn has_mut_interior_lazy_seek(&mut self, local: Local, location: Location) -> bool {
97 if !self.has_mut_interior.in_any_value_of_ty.contains(local) {
101 self.has_mut_interior.cursor.seek_before(location);
102 self.has_mut_interior.cursor.get().contains(local)
103 || self.indirectly_mutable(local, location)
106 /// Returns `true` if `local` is `HasMutInterior`, but requires the `has_mut_interior` and
107 /// `indirectly_mutable` cursors to be updated beforehand.
108 fn has_mut_interior_eager_seek(&self, local: Local) -> bool {
109 if !self.has_mut_interior.in_any_value_of_ty.contains(local) {
113 self.has_mut_interior.cursor.get().contains(local)
114 || self.indirectly_mutable.get().contains(local)
117 fn in_return_place(&mut self, item: &Item<'_, 'tcx>) -> QualifSet {
118 // Find the `Return` terminator if one exists.
120 // If no `Return` terminator exists, this MIR is divergent. Just return the conservative
121 // qualifs for the return type.
122 let return_block = item.body
126 match block.terminator().kind {
127 TerminatorKind::Return => true,
133 let return_block = match return_block {
134 None => return QualifSet::in_any_value_of_ty(item, item.body.return_ty()),
138 let return_loc = item.body.terminator_loc(return_block);
140 let mut qualifs = QualifSet::default();
142 qualifs.set::<NeedsDrop>(self.needs_drop_lazy_seek(RETURN_PLACE, return_loc));
143 qualifs.set::<HasMutInterior>(self.has_mut_interior_lazy_seek(RETURN_PLACE, return_loc));
149 pub struct Validator<'a, 'mir, 'tcx> {
150 item: &'a Item<'mir, 'tcx>,
151 qualifs: Qualifs<'a, 'mir, 'tcx>,
153 /// The span of the current statement.
156 /// True if the local was assigned the result of an illegal borrow (`ops::MutBorrow`).
158 /// This is used to hide errors from {re,}borrowing the newly-assigned local, instead pointing
159 /// the user to the place where the illegal borrow occurred. This set is only populated once an
160 /// error has been emitted, so it will never cause an erroneous `mir::Body` to pass validation.
162 /// FIXME(ecstaticmorse): assert at the end of checking that if `tcx.has_errors() == false`,
163 /// this set is empty. Note that if we start removing locals from
164 /// `derived_from_illegal_borrow`, just checking at the end won't be enough.
165 derived_from_illegal_borrow: BitSet<Local>,
167 errors: Vec<(Span, String)>,
169 /// Whether to actually emit errors or just store them in `errors`.
170 pub(crate) suppress_errors: bool,
173 impl Deref for Validator<'_, 'mir, 'tcx> {
174 type Target = Item<'mir, 'tcx>;
176 fn deref(&self) -> &Self::Target {
181 impl Validator<'a, 'mir, 'tcx> {
183 item: &'a Item<'mir, 'tcx>,
185 let dead_unwinds = BitSet::new_empty(item.body.basic_blocks().len());
187 let needs_drop = QualifCursor::new(
193 let has_mut_interior = QualifCursor::new(
199 let indirectly_mutable = old_dataflow::do_dataflow(
203 &item.tcx.get_attrs(item.def_id),
205 old_dataflow::IndirectlyMutableLocals::new(item.tcx, item.body, item.param_env),
206 |_, local| old_dataflow::DebugFormatted::new(&local),
209 let indirectly_mutable = old_dataflow::DataflowResultsCursor::new(
214 let qualifs = Qualifs {
221 span: item.body.span,
225 derived_from_illegal_borrow: BitSet::new_empty(item.body.local_decls.len()),
226 suppress_errors: false,
230 pub fn check_body(&mut self) {
231 let Item { tcx, body, def_id, const_kind, .. } = *self.item;
233 let use_min_const_fn_checks =
234 tcx.is_min_const_fn(def_id)
235 && !tcx.sess.opts.debugging_opts.unleash_the_miri_inside_of_you;
237 if use_min_const_fn_checks {
238 // Enforce `min_const_fn` for stable `const fn`s.
239 use crate::transform::qualify_min_const_fn::is_min_const_fn;
240 if let Err((span, err)) = is_min_const_fn(tcx, def_id, body) {
241 error_min_const_fn_violation(tcx, span, err);
246 check_short_circuiting_in_const_local(self.item);
248 // FIXME: give a span for the loop
249 if body.is_cfg_cyclic() {
250 // FIXME: make this the `emit_error` impl of `ops::Loop` once the const
251 // checker is no longer run in compatability mode.
252 if !self.tcx.sess.opts.debugging_opts.unleash_the_miri_inside_of_you {
253 self.tcx.sess.delay_span_bug(
255 "complex control flow is forbidden in a const context",
260 self.visit_body(body);
262 // Ensure that the end result is `Sync` in a non-thread local `static`.
263 let should_check_for_sync = const_kind == Some(ConstKind::Static)
264 && !tcx.has_attr(def_id, sym::thread_local);
266 if should_check_for_sync {
267 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
268 check_return_ty_is_sync(tcx, body, hir_id);
272 pub fn qualifs_in_return_place(&mut self) -> QualifSet {
273 self.qualifs.in_return_place(self.item)
276 pub fn take_errors(&mut self) -> Vec<(Span, String)> {
277 std::mem::replace(&mut self.errors, vec![])
280 /// Emits an error at the given `span` if an expression cannot be evaluated in the current
281 /// context. Returns `Forbidden` if an error was emitted.
282 pub fn check_op_spanned<O>(&mut self, op: O, span: Span) -> CheckOpResult
284 O: NonConstOp + fmt::Debug
286 trace!("check_op: op={:?}", op);
288 if op.is_allowed_in_item(self) {
289 return CheckOpResult::Allowed;
292 // If an operation is supported in miri (and is not already controlled by a feature gate) it
293 // can be turned on with `-Zunleash-the-miri-inside-of-you`.
294 let is_unleashable = O::IS_SUPPORTED_IN_MIRI
295 && O::feature_gate(self.tcx).is_none();
297 if is_unleashable && self.tcx.sess.opts.debugging_opts.unleash_the_miri_inside_of_you {
298 self.tcx.sess.span_warn(span, "skipping const checks");
299 return CheckOpResult::Unleashed;
302 if !self.suppress_errors {
303 op.emit_error(self, span);
306 self.errors.push((span, format!("{:?}", op)));
307 CheckOpResult::Forbidden
310 /// Emits an error if an expression cannot be evaluated in the current context.
311 pub fn check_op(&mut self, op: impl NonConstOp + fmt::Debug) -> CheckOpResult {
312 let span = self.span;
313 self.check_op_spanned(op, span)
317 impl Visitor<'tcx> for Validator<'_, 'mir, 'tcx> {
318 fn visit_basic_block_data(
321 block: &BasicBlockData<'tcx>,
323 trace!("visit_basic_block_data: bb={:?} is_cleanup={:?}", bb, block.is_cleanup);
325 // Just as the old checker did, we skip const-checking basic blocks on the unwind path.
326 // These blocks often drop locals that would otherwise be returned from the function.
328 // FIXME: This shouldn't be unsound since a panic at compile time will cause a compiler
329 // error anyway, but maybe we should do more here?
330 if block.is_cleanup {
334 self.super_basic_block_data(bb, block);
337 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
338 trace!("visit_rvalue: rvalue={:?} location={:?}", rvalue, location);
340 // Check nested operands and places.
341 if let Rvalue::Ref(_, kind, ref place) = *rvalue {
342 // Special-case reborrows to be more like a copy of a reference.
343 let mut reborrow_place = None;
344 if let &[ref proj_base @ .., elem] = place.projection.as_ref() {
345 if elem == ProjectionElem::Deref {
346 let base_ty = Place::ty_from(&place.base, proj_base, self.body, self.tcx).ty;
347 if let ty::Ref(..) = base_ty.kind {
348 reborrow_place = Some(proj_base);
353 if let Some(proj) = reborrow_place {
354 let ctx = match kind {
355 BorrowKind::Shared => PlaceContext::NonMutatingUse(
356 NonMutatingUseContext::SharedBorrow,
358 BorrowKind::Shallow => PlaceContext::NonMutatingUse(
359 NonMutatingUseContext::ShallowBorrow,
361 BorrowKind::Unique => PlaceContext::NonMutatingUse(
362 NonMutatingUseContext::UniqueBorrow,
364 BorrowKind::Mut { .. } => PlaceContext::MutatingUse(
365 MutatingUseContext::Borrow,
368 self.visit_place_base(&place.base, ctx, location);
369 self.visit_projection(&place.base, proj, ctx, location);
371 self.super_rvalue(rvalue, location);
374 self.super_rvalue(rvalue, location);
380 Rvalue::UnaryOp(UnOp::Neg, _) |
381 Rvalue::UnaryOp(UnOp::Not, _) |
382 Rvalue::NullaryOp(NullOp::SizeOf, _) |
383 Rvalue::CheckedBinaryOp(..) |
384 Rvalue::Cast(CastKind::Pointer(_), ..) |
385 Rvalue::Discriminant(..) |
388 Rvalue::Aggregate(..) => {}
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(_))
396 | (CastTy::FnPtr, CastTy::Int(_)) = (cast_in, cast_out) {
397 self.check_op(ops::RawPtrToIntCast);
401 Rvalue::BinaryOp(op, ref lhs, _) => {
402 if let ty::RawPtr(_) | ty::FnPtr(..) = lhs.ty(self.body, self.tcx).kind {
403 assert!(op == BinOp::Eq || op == BinOp::Ne ||
404 op == BinOp::Le || op == BinOp::Lt ||
405 op == BinOp::Ge || op == BinOp::Gt ||
406 op == BinOp::Offset);
409 self.check_op(ops::RawPtrComparison);
413 Rvalue::NullaryOp(NullOp::Box, _) => {
414 self.check_op(ops::HeapAllocation);
421 place_base: &PlaceBase<'tcx>,
422 context: PlaceContext,
426 "visit_place_base: place_base={:?} context={:?} location={:?}",
431 self.super_place_base(place_base, context, location);
434 PlaceBase::Local(_) => {}
435 PlaceBase::Static(box Static{ kind: StaticKind::Promoted(_, _), .. }) => {
436 bug!("Promotion must be run after const validation");
439 PlaceBase::Static(box Static{ kind: StaticKind::Static, def_id, .. }) => {
440 let is_thread_local = self.tcx.has_attr(*def_id, sym::thread_local);
442 self.check_op(ops::ThreadLocalAccess);
443 } else if self.const_kind() != ConstKind::Static || !context.is_mutating_use() {
444 self.check_op(ops::StaticAccess);
450 fn visit_assign(&mut self, dest: &Place<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
451 trace!("visit_assign: dest={:?} rvalue={:?} location={:?}", dest, rvalue, location);
453 // Error on mutable borrows or shared borrows of values with interior mutability.
455 // This replicates the logic at the start of `assign` in the old const checker. Note that
456 // it depends on `HasMutInterior` being set for mutable borrows as well as values with
457 // interior mutability.
458 if let Rvalue::Ref(_, kind, ref borrowed_place) = *rvalue {
459 // FIXME: Change the `in_*` methods to take a `FnMut` so we don't have to manually seek
460 // the cursors beforehand.
461 self.qualifs.has_mut_interior.cursor.seek_before(location);
462 self.qualifs.indirectly_mutable.seek(location);
464 let rvalue_has_mut_interior = HasMutInterior::in_rvalue(
466 &|local| self.qualifs.has_mut_interior_eager_seek(local),
470 if rvalue_has_mut_interior {
471 let is_derived_from_illegal_borrow = match borrowed_place.as_local() {
472 // If an unprojected local was borrowed and its value was the result of an
473 // illegal borrow, suppress this error and mark the result of this borrow as
476 if self.derived_from_illegal_borrow.contains(borrowed_local) =>
481 // Otherwise proceed normally: check the legality of a mutable borrow in this
483 _ => self.check_op(ops::MutBorrow(kind)) == CheckOpResult::Forbidden,
486 // When the target of the assignment is a local with no projections, mark it as
487 // derived from an illegal borrow if necessary.
489 // FIXME: should we also clear `derived_from_illegal_borrow` when a local is
490 // assigned a new value?
491 if is_derived_from_illegal_borrow {
492 if let Some(dest) = dest.as_local() {
493 self.derived_from_illegal_borrow.insert(dest);
499 self.super_assign(dest, rvalue, location);
502 fn visit_projection_elem(
504 place_base: &PlaceBase<'tcx>,
505 proj_base: &[PlaceElem<'tcx>],
506 elem: &PlaceElem<'tcx>,
507 context: PlaceContext,
511 "visit_projection_elem: place_base={:?} proj_base={:?} elem={:?} \
512 context={:?} location={:?}",
520 self.super_projection_elem(place_base, proj_base, elem, context, location);
523 ProjectionElem::Deref => {
524 if context.is_mutating_use() {
525 self.check_op(ops::MutDeref);
528 let base_ty = Place::ty_from(place_base, proj_base, self.body, self.tcx).ty;
529 if let ty::RawPtr(_) = base_ty.kind {
530 self.check_op(ops::RawPtrDeref);
534 ProjectionElem::ConstantIndex {..} |
535 ProjectionElem::Subslice {..} |
536 ProjectionElem::Field(..) |
537 ProjectionElem::Index(_) => {
538 let base_ty = Place::ty_from(place_base, proj_base, self.body, self.tcx).ty;
539 match base_ty.ty_adt_def() {
540 Some(def) if def.is_union() => {
541 self.check_op(ops::UnionAccess);
548 ProjectionElem::Downcast(..) => {
549 self.check_op(ops::Downcast);
555 fn visit_source_info(&mut self, source_info: &SourceInfo) {
556 trace!("visit_source_info: source_info={:?}", source_info);
557 self.span = source_info.span;
560 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
561 trace!("visit_statement: statement={:?} location={:?}", statement, location);
563 match statement.kind {
564 StatementKind::Assign(..) => {
565 self.super_statement(statement, location);
567 StatementKind::FakeRead(FakeReadCause::ForMatchedPlace, _) => {
568 // FIXME: make this the `emit_error` impl of `ops::IfOrMatch` once the const
569 // checker is no longer run in compatability mode.
570 if !self.tcx.sess.opts.debugging_opts.unleash_the_miri_inside_of_you {
571 self.tcx.sess.delay_span_bug(
573 "complex control flow is forbidden in a const context",
577 // FIXME(eddyb) should these really do nothing?
578 StatementKind::FakeRead(..) |
579 StatementKind::SetDiscriminant { .. } |
580 StatementKind::StorageLive(_) |
581 StatementKind::StorageDead(_) |
582 StatementKind::InlineAsm {..} |
583 StatementKind::Retag { .. } |
584 StatementKind::AscribeUserType(..) |
585 StatementKind::Nop => {}
589 fn visit_terminator_kind(&mut self, kind: &TerminatorKind<'tcx>, location: Location) {
590 trace!("visit_terminator_kind: kind={:?} location={:?}", kind, location);
591 self.super_terminator_kind(kind, location);
594 TerminatorKind::Call { func, .. } => {
595 let fn_ty = func.ty(self.body, self.tcx);
597 let def_id = match fn_ty.kind {
598 ty::FnDef(def_id, _) => def_id,
601 self.check_op(ops::FnCallIndirect);
605 self.check_op(ops::FnCallOther);
610 // At this point, we are calling a function whose `DefId` is known...
612 if let Abi::RustIntrinsic | Abi::PlatformIntrinsic = self.tcx.fn_sig(def_id).abi() {
613 assert!(!self.tcx.is_const_fn(def_id));
615 if self.tcx.item_name(def_id) == sym::transmute {
616 self.check_op(ops::Transmute);
620 // To preserve the current semantics, we return early, allowing all
621 // intrinsics (except `transmute`) to pass unchecked to miri.
623 // FIXME: We should keep a whitelist of allowed intrinsics (or at least a
624 // blacklist of unimplemented ones) and fail here instead.
628 if self.tcx.is_const_fn(def_id) {
632 if is_lang_panic_fn(self.tcx, def_id) {
633 self.check_op(ops::Panic);
634 } else if let Some(feature) = self.tcx.is_unstable_const_fn(def_id) {
635 // Exempt unstable const fns inside of macros with
636 // `#[allow_internal_unstable]`.
637 if !self.span.allows_unstable(feature) {
638 self.check_op(ops::FnCallUnstable(def_id, feature));
641 self.check_op(ops::FnCallNonConst(def_id));
646 // Forbid all `Drop` terminators unless the place being dropped is a local with no
647 // projections that cannot be `NeedsDrop`.
648 | TerminatorKind::Drop { location: dropped_place, .. }
649 | TerminatorKind::DropAndReplace { location: dropped_place, .. }
651 let mut err_span = self.span;
653 // Check to see if the type of this place can ever have a drop impl. If not, this
654 // `Drop` terminator is frivolous.
655 let ty_needs_drop = dropped_place
656 .ty(self.body, self.tcx)
658 .needs_drop(self.tcx, self.param_env);
664 let needs_drop = if let Some(local) = dropped_place.as_local() {
665 // Use the span where the local was declared as the span of the drop error.
666 err_span = self.body.local_decls[local].source_info.span;
667 self.qualifs.needs_drop_lazy_seek(local, location)
673 self.check_op_spanned(ops::LiveDrop, err_span);
682 fn error_min_const_fn_violation(tcx: TyCtxt<'_>, span: Span, msg: Cow<'_, str>) {
683 struct_span_err!(tcx.sess, span, E0723, "{}", msg)
684 .note("for more information, see issue https://github.com/rust-lang/rust/issues/57563")
685 .help("add `#![feature(const_fn)]` to the crate attributes to enable")
689 fn check_short_circuiting_in_const_local(item: &Item<'_, 'tcx>) {
690 let body = item.body;
692 if body.control_flow_destroyed.is_empty() {
696 let mut locals = body.vars_iter();
697 if let Some(local) = locals.next() {
698 let span = body.local_decls[local].source_info.span;
699 let mut error = item.tcx.sess.struct_span_err(
702 "new features like let bindings are not permitted in {}s \
703 which also use short circuiting operators",
707 for (span, kind) in body.control_flow_destroyed.iter() {
710 &format!("use of {} here does not actually short circuit due to \
711 the const evaluator presently not being able to do control flow. \
712 See https://github.com/rust-lang/rust/issues/49146 for more \
713 information.", kind),
716 for local in locals {
717 let span = body.local_decls[local].source_info.span;
718 error.span_note(span, "more locals defined here");
724 fn check_return_ty_is_sync(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, hir_id: HirId) {
725 let ty = body.return_ty();
726 tcx.infer_ctxt().enter(|infcx| {
727 let cause = traits::ObligationCause::new(body.span, hir_id, traits::SharedStatic);
728 let mut fulfillment_cx = traits::FulfillmentContext::new();
729 let sync_def_id = tcx.require_lang_item(lang_items::SyncTraitLangItem, Some(body.span));
730 fulfillment_cx.register_bound(&infcx, ty::ParamEnv::empty(), ty, sync_def_id, cause);
731 if let Err(err) = fulfillment_cx.select_all_or_error(&infcx) {
732 infcx.report_fulfillment_errors(&err, None, false);