1 //! Validates the MIR to ensure that invariants are upheld.
3 use crate::dataflow::impls::MaybeStorageLive;
4 use crate::dataflow::{Analysis, ResultsCursor};
5 use crate::util::storage::AlwaysLiveLocals;
7 use super::{MirPass, MirSource};
8 use rustc_middle::mir::visit::{PlaceContext, Visitor};
9 use rustc_middle::mir::{
10 AggregateKind, BasicBlock, Body, BorrowKind, Local, Location, MirPhase, Operand, Rvalue,
11 Statement, StatementKind, Terminator, TerminatorKind, VarDebugInfo,
13 use rustc_middle::ty::relate::{Relate, RelateResult, TypeRelation};
14 use rustc_middle::ty::{self, ParamEnv, Ty, TyCtxt};
16 #[derive(Copy, Clone, Debug)]
22 pub struct Validator {
23 /// Describes at which point in the pipeline this validation is happening.
25 /// The phase for which we are upholding the dialect. If the given phase forbids a specific
26 /// element, this validator will now emit errors if that specific element is encountered.
27 /// Note that phases that change the dialect cause all *following* phases to check the
28 /// invariants of the new dialect. A phase that changes dialects never checks the new invariants
30 pub mir_phase: MirPhase,
33 impl<'tcx> MirPass<'tcx> for Validator {
34 fn run_pass(&self, tcx: TyCtxt<'tcx>, source: MirSource<'tcx>, body: &mut Body<'tcx>) {
35 let def_id = source.def_id();
36 let param_env = tcx.param_env(def_id);
37 let mir_phase = self.mir_phase;
39 let always_live_locals = AlwaysLiveLocals::new(body);
40 let storage_liveness = MaybeStorageLive::new(always_live_locals)
41 .into_engine(tcx, body, def_id)
42 .iterate_to_fixpoint()
43 .into_results_cursor(body);
45 TypeChecker { when: &self.when, source, body, tcx, param_env, mir_phase, storage_liveness }
50 /// Returns whether the two types are equal up to lifetimes.
51 /// All lifetimes, including higher-ranked ones, get ignored for this comparison.
52 /// (This is unlike the `erasing_regions` methods, which keep higher-ranked lifetimes for soundness reasons.)
54 /// The point of this function is to approximate "equal up to subtyping". However,
55 /// the approximation is incorrect as variance is ignored.
56 pub fn equal_up_to_regions(
58 param_env: ParamEnv<'tcx>,
67 struct LifetimeIgnoreRelation<'tcx> {
69 param_env: ty::ParamEnv<'tcx>,
72 impl TypeRelation<'tcx> for LifetimeIgnoreRelation<'tcx> {
73 fn tcx(&self) -> TyCtxt<'tcx> {
77 fn param_env(&self) -> ty::ParamEnv<'tcx> {
81 fn tag(&self) -> &'static str {
82 "librustc_mir::transform::validate"
85 fn a_is_expected(&self) -> bool {
89 fn relate_with_variance<T: Relate<'tcx>>(
94 ) -> RelateResult<'tcx, T> {
95 // Ignore variance, require types to be exactly the same.
99 fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
104 ty::relate::super_relate_tys(self, a, b)
110 _b: ty::Region<'tcx>,
111 ) -> RelateResult<'tcx, ty::Region<'tcx>> {
118 a: &'tcx ty::Const<'tcx>,
119 b: &'tcx ty::Const<'tcx>,
120 ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>> {
121 ty::relate::super_relate_consts(self, a, b)
128 ) -> RelateResult<'tcx, ty::Binder<T>>
132 self.relate(a.skip_binder(), b.skip_binder())?;
137 // Instantiate and run relation.
138 let mut relator: LifetimeIgnoreRelation<'tcx> = LifetimeIgnoreRelation { tcx: tcx, param_env };
139 relator.relate(src, dest).is_ok()
142 struct TypeChecker<'a, 'tcx> {
144 source: MirSource<'tcx>,
145 body: &'a Body<'tcx>,
147 param_env: ParamEnv<'tcx>,
149 storage_liveness: ResultsCursor<'a, 'tcx, MaybeStorageLive>,
152 impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
153 fn fail(&self, location: Location, msg: impl AsRef<str>) {
154 let span = self.body.source_info(location).span;
155 // We use `delay_span_bug` as we might see broken MIR when other errors have already
157 self.tcx.sess.diagnostic().delay_span_bug(
160 "broken MIR in {:?} ({}) at {:?}:\n{}",
161 self.source.instance,
169 fn check_edge(&self, location: Location, bb: BasicBlock, edge_kind: EdgeKind) {
170 if let Some(bb) = self.body.basic_blocks().get(bb) {
171 let src = self.body.basic_blocks().get(location.block).unwrap();
172 match (src.is_cleanup, bb.is_cleanup, edge_kind) {
173 // Non-cleanup blocks can jump to non-cleanup blocks along non-unwind edges
174 (false, false, EdgeKind::Normal)
175 // Non-cleanup blocks can jump to cleanup blocks along unwind edges
176 | (false, true, EdgeKind::Unwind)
177 // Cleanup blocks can jump to cleanup blocks along non-unwind edges
178 | (true, true, EdgeKind::Normal) => {}
179 // All other jumps are invalid
184 "{:?} edge to {:?} violates unwind invariants (cleanup {:?} -> {:?})",
194 self.fail(location, format!("encountered jump to invalid basic block {:?}", bb))
198 /// Check if src can be assigned into dest.
199 /// This is not precise, it will accept some incorrect assignments.
200 fn mir_assign_valid_types(&self, src: Ty<'tcx>, dest: Ty<'tcx>) -> bool {
201 // Fast path before we normalize.
203 // Equal types, all is good.
206 // Normalize projections and things like that.
207 // FIXME: We need to reveal_all, as some optimizations change types in ways
208 // that require unfolding opaque types.
209 let param_env = self.param_env.with_reveal_all_normalized(self.tcx);
210 let src = self.tcx.normalize_erasing_regions(param_env, src);
211 let dest = self.tcx.normalize_erasing_regions(param_env, dest);
213 // Type-changing assignments can happen when subtyping is used. While
214 // all normal lifetimes are erased, higher-ranked types with their
215 // late-bound lifetimes are still around and can lead to type
216 // differences. So we compare ignoring lifetimes.
217 equal_up_to_regions(self.tcx, param_env, src, dest)
221 impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
222 fn visit_local(&mut self, local: &Local, context: PlaceContext, location: Location) {
223 if context.is_use() {
224 // Uses of locals must occur while the local's storage is allocated.
225 self.storage_liveness.seek_after_primary_effect(location);
226 let locals_with_storage = self.storage_liveness.get();
227 if !locals_with_storage.contains(*local) {
228 self.fail(location, format!("use of local {:?}, which has no storage here", local));
233 fn visit_var_debug_info(&mut self, _var_debug_info: &VarDebugInfo<'tcx>) {
234 // Debuginfo can contain field projections, which count as a use of the base local. Skip
235 // debuginfo so that we avoid the storage liveness assertion in that case.
238 fn visit_operand(&mut self, operand: &Operand<'tcx>, location: Location) {
239 // `Operand::Copy` is only supposed to be used with `Copy` types.
240 if let Operand::Copy(place) = operand {
241 let ty = place.ty(&self.body.local_decls, self.tcx).ty;
242 let span = self.body.source_info(location).span;
244 if !ty.is_copy_modulo_regions(self.tcx.at(span), self.param_env) {
245 self.fail(location, format!("`Operand::Copy` with non-`Copy` type {}", ty));
249 self.super_operand(operand, location);
252 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
253 match &statement.kind {
254 StatementKind::Assign(box (dest, rvalue)) => {
255 // LHS and RHS of the assignment must have the same type.
256 let left_ty = dest.ty(&self.body.local_decls, self.tcx).ty;
257 let right_ty = rvalue.ty(&self.body.local_decls, self.tcx);
258 if !self.mir_assign_valid_types(right_ty, left_ty) {
262 "encountered `{:?}` with incompatible types:\n\
263 left-hand side has type: {}\n\
264 right-hand side has type: {}",
265 statement.kind, left_ty, right_ty,
270 // The sides of an assignment must not alias. Currently this just checks whether the places
272 Rvalue::Use(Operand::Copy(src) | Operand::Move(src)) => {
276 "encountered `Assign` statement with overlapping memory",
280 // The deaggregator currently does not deaggreagate arrays.
281 // So for now, we ignore them here.
282 Rvalue::Aggregate(box AggregateKind::Array { .. }, _) => {}
283 // All other aggregates must be gone after some phases.
284 Rvalue::Aggregate(box kind, _) => {
285 if self.mir_phase > MirPhase::DropLowering
286 && !matches!(kind, AggregateKind::Generator(..))
288 // Generators persist until the state machine transformation, but all
289 // other aggregates must have been lowered.
292 format!("{:?} have been lowered to field assignments", rvalue),
294 } else if self.mir_phase > MirPhase::GeneratorLowering {
295 // No more aggregates after drop and generator lowering.
298 format!("{:?} have been lowered to field assignments", rvalue),
302 Rvalue::Ref(_, BorrowKind::Shallow, _) => {
303 if self.mir_phase > MirPhase::DropLowering {
306 "`Assign` statement with a `Shallow` borrow should have been removed after drop lowering phase",
313 StatementKind::AscribeUserType(..) => {
314 if self.mir_phase > MirPhase::DropLowering {
317 "`AscribeUserType` should have been removed after drop lowering phase",
321 StatementKind::FakeRead(..) => {
322 if self.mir_phase > MirPhase::DropLowering {
325 "`FakeRead` should have been removed after drop lowering phase",
333 fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
334 match &terminator.kind {
335 TerminatorKind::Goto { target } => {
336 self.check_edge(location, *target, EdgeKind::Normal);
338 TerminatorKind::SwitchInt { targets, values, switch_ty, discr } => {
339 let ty = discr.ty(&self.body.local_decls, self.tcx);
340 if ty != *switch_ty {
344 "encountered `SwitchInt` terminator with type mismatch: {:?} != {:?}",
349 if targets.len() != values.len() + 1 {
353 "encountered `SwitchInt` terminator with {} values, but {} targets (should be values+1)",
359 for target in targets {
360 self.check_edge(location, *target, EdgeKind::Normal);
363 TerminatorKind::Drop { target, unwind, .. } => {
364 self.check_edge(location, *target, EdgeKind::Normal);
365 if let Some(unwind) = unwind {
366 self.check_edge(location, *unwind, EdgeKind::Unwind);
369 TerminatorKind::DropAndReplace { target, unwind, .. } => {
370 if self.mir_phase > MirPhase::DropLowering {
373 "`DropAndReplace` is not permitted to exist after drop elaboration",
376 self.check_edge(location, *target, EdgeKind::Normal);
377 if let Some(unwind) = unwind {
378 self.check_edge(location, *unwind, EdgeKind::Unwind);
381 TerminatorKind::Call { func, destination, cleanup, .. } => {
382 let func_ty = func.ty(&self.body.local_decls, self.tcx);
383 match func_ty.kind() {
384 ty::FnPtr(..) | ty::FnDef(..) => {}
387 format!("encountered non-callable type {} in `Call` terminator", func_ty),
390 if let Some((_, target)) = destination {
391 self.check_edge(location, *target, EdgeKind::Normal);
393 if let Some(cleanup) = cleanup {
394 self.check_edge(location, *cleanup, EdgeKind::Unwind);
397 TerminatorKind::Assert { cond, target, cleanup, .. } => {
398 let cond_ty = cond.ty(&self.body.local_decls, self.tcx);
399 if cond_ty != self.tcx.types.bool {
403 "encountered non-boolean condition of type {} in `Assert` terminator",
408 self.check_edge(location, *target, EdgeKind::Normal);
409 if let Some(cleanup) = cleanup {
410 self.check_edge(location, *cleanup, EdgeKind::Unwind);
413 TerminatorKind::Yield { resume, drop, .. } => {
414 if self.mir_phase > MirPhase::GeneratorLowering {
415 self.fail(location, "`Yield` should have been replaced by generator lowering");
417 self.check_edge(location, *resume, EdgeKind::Normal);
418 if let Some(drop) = drop {
419 self.check_edge(location, *drop, EdgeKind::Normal);
422 TerminatorKind::FalseEdge { real_target, imaginary_target } => {
423 self.check_edge(location, *real_target, EdgeKind::Normal);
424 self.check_edge(location, *imaginary_target, EdgeKind::Normal);
426 TerminatorKind::FalseUnwind { real_target, unwind } => {
427 self.check_edge(location, *real_target, EdgeKind::Normal);
428 if let Some(unwind) = unwind {
429 self.check_edge(location, *unwind, EdgeKind::Unwind);
432 TerminatorKind::InlineAsm { destination, .. } => {
433 if let Some(destination) = destination {
434 self.check_edge(location, *destination, EdgeKind::Normal);
437 // Nothing to validate for these.
438 TerminatorKind::Resume
439 | TerminatorKind::Abort
440 | TerminatorKind::Return
441 | TerminatorKind::Unreachable
442 | TerminatorKind::GeneratorDrop => {}