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, ConstCx, ConstKind, 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, ccx: &'a ConstCx<'mir, 'tcx>) -> Self {
41 let cursor = FlowSensitiveAnalysis::new(q, ccx)
42 .into_engine(ccx.tcx, ccx.body, ccx.def_id)
43 .iterate_to_fixpoint()
44 .into_results_cursor(ccx.body);
46 let mut in_any_value_of_ty = BitSet::new_empty(ccx.body.local_decls.len());
47 for (local, decl) in ccx.body.local_decls.iter_enumerated() {
48 if Q::in_any_value_of_ty(ccx, 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, ccx: &ConstCx<'_, '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 = ccx
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(ccx, ccx.body.return_ty()),
114 let return_loc = ccx.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 ccx: &'a ConstCx<'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 = ConstCx<'mir, 'tcx>;
134 fn deref(&self) -> &Self::Target {
139 impl Validator<'a, 'mir, 'tcx> {
140 pub fn new(ccx: &'a ConstCx<'mir, 'tcx>) -> Self {
141 let ConstCx { tcx, body, def_id, param_env, .. } = *ccx;
143 let needs_drop = QualifCursor::new(NeedsDrop, ccx);
144 let has_mut_interior = QualifCursor::new(HasMutInterior, ccx);
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: ccx.body.span, ccx, qualifs }
162 pub fn check_body(&mut self) {
163 let ConstCx { tcx, body, def_id, const_kind, .. } = *self.ccx;
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.ccx);
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.ccx)
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_local(&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_local(&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_local(&mut self, place_local: &Local, context: PlaceContext, location: Location) {
391 "visit_local: place_local={:?} context={:?} location={:?}",
398 fn visit_operand(&mut self, op: &Operand<'tcx>, location: Location) {
399 self.super_operand(op, location);
400 if let Operand::Constant(c) = op {
401 if let Some(def_id) = c.check_static_ptr(self.tcx) {
402 self.check_static(def_id, self.span);
406 fn visit_projection_elem(
409 proj_base: &[PlaceElem<'tcx>],
410 elem: &PlaceElem<'tcx>,
411 context: PlaceContext,
415 "visit_projection_elem: place_local={:?} proj_base={:?} elem={:?} \
416 context={:?} location={:?}",
424 self.super_projection_elem(place_local, proj_base, elem, context, location);
427 ProjectionElem::Deref => {
428 let base_ty = Place::ty_from(place_local, proj_base, self.body, self.tcx).ty;
429 if let ty::RawPtr(_) = base_ty.kind {
430 if proj_base.is_empty() {
431 if let (local, []) = (place_local, proj_base) {
432 let decl = &self.body.local_decls[local];
433 if let LocalInfo::StaticRef { def_id, .. } = decl.local_info {
434 let span = decl.source_info.span;
435 self.check_static(def_id, span);
440 self.check_op(ops::RawPtrDeref);
443 if context.is_mutating_use() {
444 self.check_op(ops::MutDeref);
448 ProjectionElem::ConstantIndex { .. }
449 | ProjectionElem::Subslice { .. }
450 | ProjectionElem::Field(..)
451 | ProjectionElem::Index(_) => {
452 let base_ty = Place::ty_from(place_local, proj_base, self.body, self.tcx).ty;
453 match base_ty.ty_adt_def() {
454 Some(def) if def.is_union() => {
455 self.check_op(ops::UnionAccess);
462 ProjectionElem::Downcast(..) => {
463 self.check_op(ops::Downcast);
468 fn visit_source_info(&mut self, source_info: &SourceInfo) {
469 trace!("visit_source_info: source_info={:?}", source_info);
470 self.span = source_info.span;
473 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
474 trace!("visit_statement: statement={:?} location={:?}", statement, location);
476 match statement.kind {
477 StatementKind::Assign(..) | StatementKind::SetDiscriminant { .. } => {
478 self.super_statement(statement, location);
481 StatementKind::FakeRead(
482 FakeReadCause::ForMatchedPlace
483 | FakeReadCause::ForMatchGuard
484 | FakeReadCause::ForGuardBinding,
487 self.super_statement(statement, location);
488 self.check_op(ops::IfOrMatch);
490 StatementKind::LlvmInlineAsm { .. } => {
491 self.super_statement(statement, location);
492 self.check_op(ops::InlineAsm);
495 StatementKind::FakeRead(FakeReadCause::ForLet | FakeReadCause::ForIndex, _)
496 | StatementKind::StorageLive(_)
497 | StatementKind::StorageDead(_)
498 | StatementKind::Retag { .. }
499 | StatementKind::AscribeUserType(..)
500 | StatementKind::Nop => {}
504 fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
505 trace!("visit_terminator: terminator={:?} location={:?}", terminator, location);
506 self.super_terminator(terminator, location);
508 match &terminator.kind {
509 TerminatorKind::Call { func, .. } => {
510 let fn_ty = func.ty(self.body, self.tcx);
512 let (def_id, substs) = match fn_ty.kind {
513 ty::FnDef(def_id, substs) => (def_id, substs),
516 self.check_op(ops::FnCallIndirect);
520 span_bug!(terminator.source_info.span, "invalid callee of type {:?}", fn_ty)
524 // At this point, we are calling a function whose `DefId` is known...
525 if is_const_fn(self.tcx, def_id) {
529 // See if this is a trait method for a concrete type whose impl of that trait is
531 if self.tcx.features().const_trait_impl {
532 let instance = Instance::resolve(self.tcx, self.param_env, def_id, substs);
533 debug!("Resolving ({:?}) -> {:?}", def_id, instance);
534 if let Ok(Some(func)) = instance {
535 if let InstanceDef::Item(def_id) = func.def {
536 if is_const_fn(self.tcx, def_id) {
543 if is_lang_panic_fn(self.tcx, def_id) {
544 self.check_op(ops::Panic);
545 } else if let Some(feature) = is_unstable_const_fn(self.tcx, def_id) {
546 // Exempt unstable const fns inside of macros with
547 // `#[allow_internal_unstable]`.
548 if !self.span.allows_unstable(feature) {
549 self.check_op(ops::FnCallUnstable(def_id, feature));
552 self.check_op(ops::FnCallNonConst(def_id));
556 // Forbid all `Drop` terminators unless the place being dropped is a local with no
557 // projections that cannot be `NeedsDrop`.
558 TerminatorKind::Drop { location: dropped_place, .. }
559 | TerminatorKind::DropAndReplace { location: dropped_place, .. } => {
560 let mut err_span = self.span;
562 // Check to see if the type of this place can ever have a drop impl. If not, this
563 // `Drop` terminator is frivolous.
565 dropped_place.ty(self.body, self.tcx).ty.needs_drop(self.tcx, self.param_env);
571 let needs_drop = if let Some(local) = dropped_place.as_local() {
572 // Use the span where the local was declared as the span of the drop error.
573 err_span = self.body.local_decls[local].source_info.span;
574 self.qualifs.needs_drop(local, location)
580 self.check_op_spanned(ops::LiveDrop, err_span);
584 // FIXME: Some of these are only caught by `min_const_fn`, but should error here
586 TerminatorKind::Abort
587 | TerminatorKind::Assert { .. }
588 | TerminatorKind::FalseEdges { .. }
589 | TerminatorKind::FalseUnwind { .. }
590 | TerminatorKind::GeneratorDrop
591 | TerminatorKind::Goto { .. }
592 | TerminatorKind::Resume
593 | TerminatorKind::Return
594 | TerminatorKind::SwitchInt { .. }
595 | TerminatorKind::Unreachable
596 | TerminatorKind::Yield { .. } => {}
601 fn error_min_const_fn_violation(tcx: TyCtxt<'_>, span: Span, msg: Cow<'_, str>) {
602 struct_span_err!(tcx.sess, span, E0723, "{}", msg)
604 "see issue #57563 <https://github.com/rust-lang/rust/issues/57563> \
605 for more information",
607 .help("add `#![feature(const_fn)]` to the crate attributes to enable")
611 fn check_short_circuiting_in_const_local(ccx: &ConstCx<'_, 'tcx>) {
614 if body.control_flow_destroyed.is_empty() {
618 let mut locals = body.vars_iter();
619 if let Some(local) = locals.next() {
620 let span = body.local_decls[local].source_info.span;
621 let mut error = ccx.tcx.sess.struct_span_err(
624 "new features like let bindings are not permitted in {}s \
625 which also use short circuiting operators",
629 for (span, kind) in body.control_flow_destroyed.iter() {
633 "use of {} here does not actually short circuit due to \
634 the const evaluator presently not being able to do control flow. \
635 See issue #49146 <https://github.com/rust-lang/rust/issues/49146> \
636 for more information.",
641 for local in locals {
642 let span = body.local_decls[local].source_info.span;
643 error.span_note(span, "more locals are defined here");
649 fn check_return_ty_is_sync(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, hir_id: HirId) {
650 let ty = body.return_ty();
651 tcx.infer_ctxt().enter(|infcx| {
652 let cause = traits::ObligationCause::new(body.span, hir_id, traits::SharedStatic);
653 let mut fulfillment_cx = traits::FulfillmentContext::new();
654 let sync_def_id = tcx.require_lang_item(lang_items::SyncTraitLangItem, Some(body.span));
655 fulfillment_cx.register_bound(&infcx, ty::ParamEnv::empty(), ty, sync_def_id, cause);
656 if let Err(err) = fulfillment_cx.select_all_or_error(&infcx) {
657 infcx.report_fulfillment_errors(&err, None, false);
662 fn place_as_reborrow(
666 ) -> Option<&'a [PlaceElem<'tcx>]> {
667 place.projection.split_last().and_then(|(outermost, inner)| {
668 if outermost != &ProjectionElem::Deref {
672 // A borrow of a `static` also looks like `&(*_1)` in the MIR, but `_1` is a `const`
673 // that points to the allocation for the static. Don't treat these as reborrows.
674 if body.local_decls[place.local].is_ref_to_static() {
678 // Ensure the type being derefed is a reference and not a raw pointer.
680 // This is sufficient to prevent an access to a `static mut` from being marked as a
681 // reborrow, even if the check above were to disappear.
682 let inner_ty = Place::ty_from(place.local, inner, body, tcx).ty;
683 match inner_ty.kind {
684 ty::Ref(..) => Some(inner),