1 //! The `Visitor` responsible for actually checking a `mir::Body` for invalid operations.
3 use rustc_errors::struct_span_err;
4 use rustc_hir::lang_items;
5 use rustc_hir::{def_id::DefId, HirId};
6 use rustc_index::bit_set::BitSet;
7 use rustc_infer::infer::TyCtxtInferExt;
8 use rustc_middle::mir::visit::{MutatingUseContext, NonMutatingUseContext, PlaceContext, Visitor};
9 use rustc_middle::mir::*;
10 use rustc_middle::ty::cast::CastTy;
11 use rustc_middle::ty::{self, Instance, InstanceDef, TyCtxt};
12 use rustc_span::symbol::sym;
14 use rustc_trait_selection::traits::error_reporting::InferCtxtExt;
15 use rustc_trait_selection::traits::{self, TraitEngine};
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::MaybeMutBorrowedLocals;
26 use crate::dataflow::{self, Analysis};
28 // We are using `MaybeMutBorrowedLocals` as a proxy for whether an item may have been mutated
29 // through a pointer prior to the given point. This is okay even though `MaybeMutBorrowedLocals`
30 // kills locals upon `StorageDead` because a local will never be used after a `StorageDead`.
31 pub type IndirectlyMutableResults<'mir, 'tcx> =
32 dataflow::ResultsCursor<'mir, 'tcx, MaybeMutBorrowedLocals<'mir, 'tcx>>;
34 struct QualifCursor<'a, 'mir, 'tcx, Q: Qualif> {
35 cursor: dataflow::ResultsCursor<'mir, 'tcx, FlowSensitiveAnalysis<'a, 'mir, 'tcx, Q>>,
36 in_any_value_of_ty: BitSet<Local>,
39 impl<Q: Qualif> QualifCursor<'a, 'mir, 'tcx, Q> {
40 pub fn new(q: Q, item: &'a Item<'mir, 'tcx>) -> Self {
41 let cursor = FlowSensitiveAnalysis::new(q, item)
42 .into_engine(item.tcx, item.body, item.def_id)
43 .iterate_to_fixpoint()
44 .into_results_cursor(item.body);
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);
53 QualifCursor { cursor, in_any_value_of_ty }
57 pub struct Qualifs<'a, 'mir, 'tcx> {
58 has_mut_interior: QualifCursor<'a, 'mir, 'tcx, HasMutInterior>,
59 needs_drop: QualifCursor<'a, 'mir, 'tcx, NeedsDrop>,
60 indirectly_mutable: IndirectlyMutableResults<'mir, 'tcx>,
63 impl Qualifs<'a, 'mir, 'tcx> {
64 fn indirectly_mutable(&mut self, local: Local, location: Location) -> bool {
65 self.indirectly_mutable.seek_before(location);
66 self.indirectly_mutable.get().contains(local)
69 /// Returns `true` if `local` is `NeedsDrop` at the given `Location`.
71 /// Only updates the cursor if absolutely necessary
72 fn needs_drop(&mut self, local: Local, location: Location) -> bool {
73 if !self.needs_drop.in_any_value_of_ty.contains(local) {
77 self.needs_drop.cursor.seek_before(location);
78 self.needs_drop.cursor.get().contains(local) || self.indirectly_mutable(local, location)
81 /// Returns `true` if `local` is `HasMutInterior` at the given `Location`.
83 /// Only updates the cursor if absolutely necessary.
84 fn has_mut_interior(&mut self, local: Local, location: Location) -> bool {
85 if !self.has_mut_interior.in_any_value_of_ty.contains(local) {
89 self.has_mut_interior.cursor.seek_before(location);
90 self.has_mut_interior.cursor.get().contains(local)
91 || self.indirectly_mutable(local, location)
94 fn in_return_place(&mut self, item: &Item<'_, 'tcx>) -> ConstQualifs {
95 // Find the `Return` terminator if one exists.
97 // If no `Return` terminator exists, this MIR is divergent. Just return the conservative
98 // qualifs for the return type.
99 let return_block = item
103 .find(|(_, block)| match block.terminator().kind {
104 TerminatorKind::Return => true,
109 let return_block = match return_block {
110 None => return qualifs::in_any_value_of_ty(item, item.body.return_ty()),
114 let return_loc = item.body.terminator_loc(return_block);
117 needs_drop: self.needs_drop(RETURN_PLACE, return_loc),
118 has_mut_interior: self.has_mut_interior(RETURN_PLACE, return_loc),
123 pub struct Validator<'a, 'mir, 'tcx> {
124 item: &'a Item<'mir, 'tcx>,
125 qualifs: Qualifs<'a, 'mir, 'tcx>,
127 /// The span of the current statement.
131 impl Deref for Validator<'_, 'mir, 'tcx> {
132 type Target = Item<'mir, 'tcx>;
134 fn deref(&self) -> &Self::Target {
139 impl Validator<'a, 'mir, 'tcx> {
140 pub fn new(item: &'a Item<'mir, 'tcx>) -> Self {
141 let Item { tcx, body, def_id, param_env, .. } = *item;
143 let needs_drop = QualifCursor::new(NeedsDrop, item);
144 let has_mut_interior = QualifCursor::new(HasMutInterior, item);
146 // We can use `unsound_ignore_borrow_on_drop` here because custom drop impls are not
147 // allowed in a const.
149 // FIXME(ecstaticmorse): Someday we want to allow custom drop impls. How do we do this
150 // without breaking stable code?
151 let indirectly_mutable = MaybeMutBorrowedLocals::mut_borrows_only(tcx, body, param_env)
152 .unsound_ignore_borrow_on_drop()
153 .into_engine(tcx, body, def_id)
154 .iterate_to_fixpoint()
155 .into_results_cursor(body);
157 let qualifs = Qualifs { needs_drop, has_mut_interior, indirectly_mutable };
159 Validator { span: item.body.span, item, qualifs }
162 pub fn check_body(&mut self) {
163 let Item { tcx, body, def_id, const_kind, .. } = *self.item;
165 let use_min_const_fn_checks = (const_kind == Some(ConstKind::ConstFn)
166 && crate::const_eval::is_min_const_fn(tcx, def_id))
167 && !tcx.sess.opts.debugging_opts.unleash_the_miri_inside_of_you;
169 if use_min_const_fn_checks {
170 // Enforce `min_const_fn` for stable `const fn`s.
171 use crate::transform::qualify_min_const_fn::is_min_const_fn;
172 if let Err((span, err)) = is_min_const_fn(tcx, def_id, &body) {
173 error_min_const_fn_violation(tcx, span, err);
178 check_short_circuiting_in_const_local(self.item);
180 if body.is_cfg_cyclic() {
181 // We can't provide a good span for the error here, but this should be caught by the
182 // HIR const-checker anyways.
183 self.check_op_spanned(ops::Loop, body.span);
186 self.visit_body(&body);
188 // Ensure that the end result is `Sync` in a non-thread local `static`.
189 let should_check_for_sync =
190 const_kind == Some(ConstKind::Static) && !tcx.has_attr(def_id, sym::thread_local);
192 if should_check_for_sync {
193 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
194 check_return_ty_is_sync(tcx, &body, hir_id);
198 pub fn qualifs_in_return_place(&mut self) -> ConstQualifs {
199 self.qualifs.in_return_place(self.item)
202 /// Emits an error at the given `span` if an expression cannot be evaluated in the current
204 pub fn check_op_spanned<O>(&mut self, op: O, span: Span)
208 trace!("check_op: op={:?}", op);
210 if op.is_allowed_in_item(self) {
214 // If an operation is supported in miri (and is not already controlled by a feature gate) it
215 // can be turned on with `-Zunleash-the-miri-inside-of-you`.
216 let is_unleashable = O::IS_SUPPORTED_IN_MIRI && O::feature_gate().is_none();
218 if is_unleashable && self.tcx.sess.opts.debugging_opts.unleash_the_miri_inside_of_you {
219 self.tcx.sess.span_warn(span, "skipping const checks");
223 op.emit_error(self, span);
226 /// Emits an error if an expression cannot be evaluated in the current context.
227 pub fn check_op(&mut self, op: impl NonConstOp) {
228 let span = self.span;
229 self.check_op_spanned(op, span)
232 fn check_static(&mut self, def_id: DefId, span: Span) {
233 let is_thread_local = self.tcx.has_attr(def_id, sym::thread_local);
235 self.check_op_spanned(ops::ThreadLocalAccess, span)
237 self.check_op_spanned(ops::StaticAccess, span)
242 impl Visitor<'tcx> for Validator<'_, 'mir, 'tcx> {
243 fn visit_basic_block_data(&mut self, bb: BasicBlock, block: &BasicBlockData<'tcx>) {
244 trace!("visit_basic_block_data: bb={:?} is_cleanup={:?}", bb, block.is_cleanup);
246 // Just as the old checker did, we skip const-checking basic blocks on the unwind path.
247 // These blocks often drop locals that would otherwise be returned from the function.
249 // FIXME: This shouldn't be unsound since a panic at compile time will cause a compiler
250 // error anyway, but maybe we should do more here?
251 if block.is_cleanup {
255 self.super_basic_block_data(bb, block);
258 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
259 trace!("visit_rvalue: rvalue={:?} location={:?}", rvalue, location);
261 // Special-case reborrows to be more like a copy of a reference.
263 Rvalue::Ref(_, kind, place) => {
264 if let Some(reborrowed_proj) = place_as_reborrow(self.tcx, self.body, place) {
265 let ctx = match kind {
266 BorrowKind::Shared => {
267 PlaceContext::NonMutatingUse(NonMutatingUseContext::SharedBorrow)
269 BorrowKind::Shallow => {
270 PlaceContext::NonMutatingUse(NonMutatingUseContext::ShallowBorrow)
272 BorrowKind::Unique => {
273 PlaceContext::NonMutatingUse(NonMutatingUseContext::UniqueBorrow)
275 BorrowKind::Mut { .. } => {
276 PlaceContext::MutatingUse(MutatingUseContext::Borrow)
279 self.visit_place_base(&place.local, ctx, location);
280 self.visit_projection(place.local, reborrowed_proj, ctx, location);
284 Rvalue::AddressOf(mutbl, place) => {
285 if let Some(reborrowed_proj) = place_as_reborrow(self.tcx, self.body, place) {
286 let ctx = match mutbl {
288 PlaceContext::NonMutatingUse(NonMutatingUseContext::AddressOf)
290 Mutability::Mut => PlaceContext::MutatingUse(MutatingUseContext::AddressOf),
292 self.visit_place_base(&place.local, ctx, location);
293 self.visit_projection(place.local, reborrowed_proj, ctx, location);
300 self.super_rvalue(rvalue, location);
305 | Rvalue::UnaryOp(UnOp::Neg, _)
306 | Rvalue::UnaryOp(UnOp::Not, _)
307 | Rvalue::NullaryOp(NullOp::SizeOf, _)
308 | Rvalue::CheckedBinaryOp(..)
309 | Rvalue::Cast(CastKind::Pointer(_), ..)
310 | Rvalue::Discriminant(..)
312 | Rvalue::Aggregate(..) => {}
314 Rvalue::Ref(_, kind @ BorrowKind::Mut { .. }, ref place)
315 | Rvalue::Ref(_, kind @ BorrowKind::Unique, ref place) => {
316 let ty = place.ty(self.body, self.tcx).ty;
317 let is_allowed = match ty.kind {
318 // Inside a `static mut`, `&mut [...]` is allowed.
319 ty::Array(..) | ty::Slice(_) if self.const_kind() == ConstKind::StaticMut => {
323 // FIXME(ecstaticmorse): We could allow `&mut []` inside a const context given
324 // that this is merely a ZST and it is already eligible for promotion.
325 // This may require an RFC?
327 ty::Array(_, len) if len.try_eval_usize(cx.tcx, cx.param_env) == Some(0)
334 if let BorrowKind::Mut { .. } = kind {
335 self.check_op(ops::MutBorrow);
337 self.check_op(ops::CellBorrow);
342 Rvalue::AddressOf(Mutability::Mut, _) => self.check_op(ops::MutAddressOf),
344 Rvalue::Ref(_, BorrowKind::Shared | BorrowKind::Shallow, ref place)
345 | Rvalue::AddressOf(Mutability::Not, ref place) => {
346 let borrowed_place_has_mut_interior = qualifs::in_place::<HasMutInterior, _>(
348 &mut |local| self.qualifs.has_mut_interior(local, location),
352 if borrowed_place_has_mut_interior {
353 self.check_op(ops::CellBorrow);
357 Rvalue::Cast(CastKind::Misc, ref operand, cast_ty) => {
358 let operand_ty = operand.ty(self.body, self.tcx);
359 let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast");
360 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
362 if let (CastTy::Ptr(_) | CastTy::FnPtr, CastTy::Int(_)) = (cast_in, cast_out) {
363 self.check_op(ops::RawPtrToIntCast);
367 Rvalue::BinaryOp(op, ref lhs, _) => {
368 if let ty::RawPtr(_) | ty::FnPtr(..) = lhs.ty(self.body, self.tcx).kind {
376 || op == BinOp::Offset
379 self.check_op(ops::RawPtrComparison);
383 Rvalue::NullaryOp(NullOp::Box, _) => {
384 self.check_op(ops::HeapAllocation);
389 fn visit_place_base(&mut self, place_local: &Local, context: PlaceContext, location: Location) {
391 "visit_place_base: place_local={:?} context={:?} location={:?}",
396 self.super_place_base(place_local, context, location);
399 fn visit_operand(&mut self, op: &Operand<'tcx>, location: Location) {
400 self.super_operand(op, location);
401 if let Operand::Constant(c) = op {
402 if let Some(def_id) = c.check_static_ptr(self.tcx) {
403 self.check_static(def_id, self.span);
407 fn visit_projection_elem(
410 proj_base: &[PlaceElem<'tcx>],
411 elem: &PlaceElem<'tcx>,
412 context: PlaceContext,
416 "visit_projection_elem: place_local={:?} proj_base={:?} elem={:?} \
417 context={:?} location={:?}",
425 self.super_projection_elem(place_local, proj_base, elem, context, location);
428 ProjectionElem::Deref => {
429 let base_ty = Place::ty_from(place_local, proj_base, self.body, self.tcx).ty;
430 if let ty::RawPtr(_) = base_ty.kind {
431 if proj_base.is_empty() {
432 if let (local, []) = (place_local, proj_base) {
433 let decl = &self.body.local_decls[local];
434 if let LocalInfo::StaticRef { def_id, .. } = decl.local_info {
435 let span = decl.source_info.span;
436 self.check_static(def_id, span);
441 self.check_op(ops::RawPtrDeref);
444 if context.is_mutating_use() {
445 self.check_op(ops::MutDeref);
449 ProjectionElem::ConstantIndex { .. }
450 | ProjectionElem::Subslice { .. }
451 | ProjectionElem::Field(..)
452 | ProjectionElem::Index(_) => {
453 let base_ty = Place::ty_from(place_local, proj_base, self.body, self.tcx).ty;
454 match base_ty.ty_adt_def() {
455 Some(def) if def.is_union() => {
456 self.check_op(ops::UnionAccess);
463 ProjectionElem::Downcast(..) => {
464 self.check_op(ops::Downcast);
469 fn visit_source_info(&mut self, source_info: &SourceInfo) {
470 trace!("visit_source_info: source_info={:?}", source_info);
471 self.span = source_info.span;
474 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
475 trace!("visit_statement: statement={:?} location={:?}", statement, location);
477 match statement.kind {
478 StatementKind::Assign(..) | StatementKind::SetDiscriminant { .. } => {
479 self.super_statement(statement, location);
481 StatementKind::FakeRead(FakeReadCause::ForMatchedPlace, _) => {
482 self.check_op(ops::IfOrMatch);
484 // FIXME(eddyb) should these really do nothing?
485 StatementKind::FakeRead(..)
486 | StatementKind::StorageLive(_)
487 | StatementKind::StorageDead(_)
488 | StatementKind::LlvmInlineAsm { .. }
489 | StatementKind::Retag { .. }
490 | StatementKind::AscribeUserType(..)
491 | StatementKind::Nop => {}
495 fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
496 trace!("visit_terminator: terminator={:?} location={:?}", terminator, location);
497 self.super_terminator(terminator, location);
499 match &terminator.kind {
500 TerminatorKind::Call { func, .. } => {
501 let fn_ty = func.ty(self.body, self.tcx);
503 let (def_id, substs) = match fn_ty.kind {
504 ty::FnDef(def_id, substs) => (def_id, substs),
507 self.check_op(ops::FnCallIndirect);
511 span_bug!(terminator.source_info.span, "invalid callee of type {:?}", fn_ty)
515 // At this point, we are calling a function whose `DefId` is known...
516 if is_const_fn(self.tcx, def_id) {
520 // See if this is a trait method for a concrete type whose impl of that trait is
522 if self.tcx.features().const_trait_impl {
523 let instance = Instance::resolve(self.tcx, self.param_env, def_id, substs);
524 debug!("Resolving ({:?}) -> {:?}", def_id, instance);
525 if let Ok(Some(func)) = instance {
526 if let InstanceDef::Item(def_id) = func.def {
527 if is_const_fn(self.tcx, def_id) {
534 if is_lang_panic_fn(self.tcx, def_id) {
535 self.check_op(ops::Panic);
536 } else if let Some(feature) = is_unstable_const_fn(self.tcx, def_id) {
537 // Exempt unstable const fns inside of macros with
538 // `#[allow_internal_unstable]`.
539 if !self.span.allows_unstable(feature) {
540 self.check_op(ops::FnCallUnstable(def_id, feature));
543 self.check_op(ops::FnCallNonConst(def_id));
547 // Forbid all `Drop` terminators unless the place being dropped is a local with no
548 // projections that cannot be `NeedsDrop`.
549 TerminatorKind::Drop { location: dropped_place, .. }
550 | TerminatorKind::DropAndReplace { location: dropped_place, .. } => {
551 let mut err_span = self.span;
553 // Check to see if the type of this place can ever have a drop impl. If not, this
554 // `Drop` terminator is frivolous.
556 dropped_place.ty(self.body, self.tcx).ty.needs_drop(self.tcx, self.param_env);
562 let needs_drop = if let Some(local) = dropped_place.as_local() {
563 // Use the span where the local was declared as the span of the drop error.
564 err_span = self.body.local_decls[local].source_info.span;
565 self.qualifs.needs_drop(local, location)
571 self.check_op_spanned(ops::LiveDrop, err_span);
580 fn error_min_const_fn_violation(tcx: TyCtxt<'_>, span: Span, msg: Cow<'_, str>) {
581 struct_span_err!(tcx.sess, span, E0723, "{}", msg)
583 "see issue #57563 <https://github.com/rust-lang/rust/issues/57563> \
584 for more information",
586 .help("add `#![feature(const_fn)]` to the crate attributes to enable")
590 fn check_short_circuiting_in_const_local(item: &Item<'_, 'tcx>) {
591 let body = item.body;
593 if body.control_flow_destroyed.is_empty() {
597 let mut locals = body.vars_iter();
598 if let Some(local) = locals.next() {
599 let span = body.local_decls[local].source_info.span;
600 let mut error = item.tcx.sess.struct_span_err(
603 "new features like let bindings are not permitted in {}s \
604 which also use short circuiting operators",
608 for (span, kind) in body.control_flow_destroyed.iter() {
612 "use of {} here does not actually short circuit due to \
613 the const evaluator presently not being able to do control flow. \
614 See issue #49146 <https://github.com/rust-lang/rust/issues/49146> \
615 for more information.",
620 for local in locals {
621 let span = body.local_decls[local].source_info.span;
622 error.span_note(span, "more locals are defined here");
628 fn check_return_ty_is_sync(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, hir_id: HirId) {
629 let ty = body.return_ty();
630 tcx.infer_ctxt().enter(|infcx| {
631 let cause = traits::ObligationCause::new(body.span, hir_id, traits::SharedStatic);
632 let mut fulfillment_cx = traits::FulfillmentContext::new();
633 let sync_def_id = tcx.require_lang_item(lang_items::SyncTraitLangItem, Some(body.span));
634 fulfillment_cx.register_bound(&infcx, ty::ParamEnv::empty(), ty, sync_def_id, cause);
635 if let Err(err) = fulfillment_cx.select_all_or_error(&infcx) {
636 infcx.report_fulfillment_errors(&err, None, false);
641 fn place_as_reborrow(
645 ) -> Option<&'a [PlaceElem<'tcx>]> {
646 place.projection.split_last().and_then(|(outermost, inner)| {
647 if outermost != &ProjectionElem::Deref {
651 // A borrow of a `static` also looks like `&(*_1)` in the MIR, but `_1` is a `const`
652 // that points to the allocation for the static. Don't treat these as reborrows.
653 if body.local_decls[place.local].is_ref_to_static() {
657 // Ensure the type being derefed is a reference and not a raw pointer.
659 // This is sufficient to prevent an access to a `static mut` from being marked as a
660 // reborrow, even if the check above were to disappear.
661 let inner_ty = Place::ty_from(place.local, inner, body, tcx).ty;
662 match inner_ty.kind {
663 ty::Ref(..) => Some(inner),