1 //! Validates the MIR to ensure that invariants are upheld.
3 use super::{MirPass, MirSource};
4 use rustc_middle::mir::visit::Visitor;
7 AggregateKind, BasicBlock, Body, BorrowKind, Location, MirPhase, Operand, Rvalue,
8 Statement, StatementKind, Terminator, TerminatorKind,
12 relate::{Relate, RelateResult, TypeRelation},
17 #[derive(Copy, Clone, Debug)]
23 pub struct Validator {
24 /// Describes at which point in the pipeline this validation is happening.
26 /// The phase for which we are upholding the dialect. If the given phase forbids a specific
27 /// element, this validator will now emit errors if that specific element is encountered.
28 /// Note that phases that change the dialect cause all *following* phases to check the
29 /// invariants of the new dialect. A phase that changes dialects never checks the new invariants
31 pub mir_phase: MirPhase,
34 impl<'tcx> MirPass<'tcx> for Validator {
35 fn run_pass(&self, tcx: TyCtxt<'tcx>, source: MirSource<'tcx>, body: &mut Body<'tcx>) {
36 let param_env = tcx.param_env(source.def_id());
37 let mir_phase = self.mir_phase;
38 TypeChecker { when: &self.when, source, body, tcx, param_env, mir_phase }.visit_body(body);
42 /// Returns whether the two types are equal up to lifetimes.
43 /// All lifetimes, including higher-ranked ones, get ignored for this comparison.
44 /// (This is unlike the `erasing_regions` methods, which keep higher-ranked lifetimes for soundness reasons.)
46 /// The point of this function is to approximate "equal up to subtyping". However,
47 /// the approximation is incorrect as variance is ignored.
48 pub fn equal_up_to_regions(
50 param_env: ParamEnv<'tcx>,
59 struct LifetimeIgnoreRelation<'tcx> {
61 param_env: ty::ParamEnv<'tcx>,
64 impl TypeRelation<'tcx> for LifetimeIgnoreRelation<'tcx> {
65 fn tcx(&self) -> TyCtxt<'tcx> {
69 fn param_env(&self) -> ty::ParamEnv<'tcx> {
73 fn tag(&self) -> &'static str {
74 "librustc_mir::transform::validate"
77 fn a_is_expected(&self) -> bool {
81 fn relate_with_variance<T: Relate<'tcx>>(
86 ) -> RelateResult<'tcx, T> {
87 // Ignore variance, require types to be exactly the same.
91 fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
96 ty::relate::super_relate_tys(self, a, b)
102 _b: ty::Region<'tcx>,
103 ) -> RelateResult<'tcx, ty::Region<'tcx>> {
110 a: &'tcx ty::Const<'tcx>,
111 b: &'tcx ty::Const<'tcx>,
112 ) -> RelateResult<'tcx, &'tcx ty::Const<'tcx>> {
113 ty::relate::super_relate_consts(self, a, b)
120 ) -> RelateResult<'tcx, ty::Binder<T>>
124 self.relate(a.skip_binder(), b.skip_binder())?;
129 // Instantiate and run relation.
130 let mut relator: LifetimeIgnoreRelation<'tcx> = LifetimeIgnoreRelation { tcx: tcx, param_env };
131 relator.relate(src, dest).is_ok()
134 struct TypeChecker<'a, 'tcx> {
136 source: MirSource<'tcx>,
137 body: &'a Body<'tcx>,
139 param_env: ParamEnv<'tcx>,
143 impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
144 fn fail(&self, location: Location, msg: impl AsRef<str>) {
145 let span = self.body.source_info(location).span;
146 // We use `delay_span_bug` as we might see broken MIR when other errors have already
148 self.tcx.sess.diagnostic().delay_span_bug(
151 "broken MIR in {:?} ({}) at {:?}:\n{}",
152 self.source.instance,
160 fn check_edge(&self, location: Location, bb: BasicBlock, edge_kind: EdgeKind) {
161 if let Some(bb) = self.body.basic_blocks().get(bb) {
162 let src = self.body.basic_blocks().get(location.block).unwrap();
163 match (src.is_cleanup, bb.is_cleanup, edge_kind) {
164 // Non-cleanup blocks can jump to non-cleanup blocks along non-unwind edges
165 (false, false, EdgeKind::Normal)
166 // Non-cleanup blocks can jump to cleanup blocks along unwind edges
167 | (false, true, EdgeKind::Unwind)
168 // Cleanup blocks can jump to cleanup blocks along non-unwind edges
169 | (true, true, EdgeKind::Normal) => {}
170 // All other jumps are invalid
175 "{:?} edge to {:?} violates unwind invariants (cleanup {:?} -> {:?})",
185 self.fail(location, format!("encountered jump to invalid basic block {:?}", bb))
189 /// Check if src can be assigned into dest.
190 /// This is not precise, it will accept some incorrect assignments.
191 fn mir_assign_valid_types(&self, src: Ty<'tcx>, dest: Ty<'tcx>) -> bool {
192 // Fast path before we normalize.
194 // Equal types, all is good.
197 // Normalize projections and things like that.
198 // FIXME: We need to reveal_all, as some optimizations change types in ways
199 // that require unfolding opaque types.
200 let param_env = self.param_env.with_reveal_all_normalized(self.tcx);
201 let src = self.tcx.normalize_erasing_regions(param_env, src);
202 let dest = self.tcx.normalize_erasing_regions(param_env, dest);
204 // Type-changing assignments can happen when subtyping is used. While
205 // all normal lifetimes are erased, higher-ranked types with their
206 // late-bound lifetimes are still around and can lead to type
207 // differences. So we compare ignoring lifetimes.
208 equal_up_to_regions(self.tcx, param_env, src, dest)
212 impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
213 fn visit_operand(&mut self, operand: &Operand<'tcx>, location: Location) {
214 // `Operand::Copy` is only supposed to be used with `Copy` types.
215 if let Operand::Copy(place) = operand {
216 let ty = place.ty(&self.body.local_decls, self.tcx).ty;
217 let span = self.body.source_info(location).span;
219 if !ty.is_copy_modulo_regions(self.tcx.at(span), self.param_env) {
220 self.fail(location, format!("`Operand::Copy` with non-`Copy` type {}", ty));
224 self.super_operand(operand, location);
227 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
228 match &statement.kind {
229 StatementKind::Assign(box (dest, rvalue)) => {
230 // LHS and RHS of the assignment must have the same type.
231 let left_ty = dest.ty(&self.body.local_decls, self.tcx).ty;
232 let right_ty = rvalue.ty(&self.body.local_decls, self.tcx);
233 if !self.mir_assign_valid_types(right_ty, left_ty) {
237 "encountered `{:?}` with incompatible types:\n\
238 left-hand side has type: {}\n\
239 right-hand side has type: {}",
240 statement.kind, left_ty, right_ty,
245 // The sides of an assignment must not alias. Currently this just checks whether the places
247 Rvalue::Use(Operand::Copy(src) | Operand::Move(src)) => {
251 "encountered `Assign` statement with overlapping memory",
255 // The deaggregator currently does not deaggreagate arrays.
256 // So for now, we ignore them here.
257 Rvalue::Aggregate(box AggregateKind::Array { .. }, _) => {}
258 // All other aggregates must be gone after some phases.
259 Rvalue::Aggregate(box kind, _) => {
260 if self.mir_phase > MirPhase::DropLowering
261 && !matches!(kind, AggregateKind::Generator(..))
263 // Generators persist until the state machine transformation, but all
264 // other aggregates must have been lowered.
267 format!("{:?} have been lowered to field assignments", rvalue),
269 } else if self.mir_phase > MirPhase::GeneratorLowering {
270 // No more aggregates after drop and generator lowering.
273 format!("{:?} have been lowered to field assignments", rvalue),
277 Rvalue::Ref(_, BorrowKind::Shallow, _) => {
278 if self.mir_phase > MirPhase::DropLowering {
281 "`Assign` statement with a `Shallow` borrow should have been removed after drop lowering phase",
288 StatementKind::AscribeUserType(..) => {
289 if self.mir_phase > MirPhase::DropLowering {
292 "`AscribeUserType` should have been removed after drop lowering phase",
296 StatementKind::FakeRead(..) => {
297 if self.mir_phase > MirPhase::DropLowering {
300 "`FakeRead` should have been removed after drop lowering phase",
308 fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
309 match &terminator.kind {
310 TerminatorKind::Goto { target } => {
311 self.check_edge(location, *target, EdgeKind::Normal);
313 TerminatorKind::SwitchInt { targets, values, switch_ty, discr } => {
314 let ty = discr.ty(&self.body.local_decls, self.tcx);
315 if ty != *switch_ty {
319 "encountered `SwitchInt` terminator with type mismatch: {:?} != {:?}",
324 if targets.len() != values.len() + 1 {
328 "encountered `SwitchInt` terminator with {} values, but {} targets (should be values+1)",
334 for target in targets {
335 self.check_edge(location, *target, EdgeKind::Normal);
338 TerminatorKind::Drop { target, unwind, .. } => {
339 self.check_edge(location, *target, EdgeKind::Normal);
340 if let Some(unwind) = unwind {
341 self.check_edge(location, *unwind, EdgeKind::Unwind);
344 TerminatorKind::DropAndReplace { target, unwind, .. } => {
345 if self.mir_phase > MirPhase::DropLowering {
348 "`DropAndReplace` is not permitted to exist after drop elaboration",
351 self.check_edge(location, *target, EdgeKind::Normal);
352 if let Some(unwind) = unwind {
353 self.check_edge(location, *unwind, EdgeKind::Unwind);
356 TerminatorKind::Call { func, destination, cleanup, .. } => {
357 let func_ty = func.ty(&self.body.local_decls, self.tcx);
358 match func_ty.kind() {
359 ty::FnPtr(..) | ty::FnDef(..) => {}
362 format!("encountered non-callable type {} in `Call` terminator", func_ty),
365 if let Some((_, target)) = destination {
366 self.check_edge(location, *target, EdgeKind::Normal);
368 if let Some(cleanup) = cleanup {
369 self.check_edge(location, *cleanup, EdgeKind::Unwind);
372 TerminatorKind::Assert { cond, target, cleanup, .. } => {
373 let cond_ty = cond.ty(&self.body.local_decls, self.tcx);
374 if cond_ty != self.tcx.types.bool {
378 "encountered non-boolean condition of type {} in `Assert` terminator",
383 self.check_edge(location, *target, EdgeKind::Normal);
384 if let Some(cleanup) = cleanup {
385 self.check_edge(location, *cleanup, EdgeKind::Unwind);
388 TerminatorKind::Yield { resume, drop, .. } => {
389 if self.mir_phase > MirPhase::GeneratorLowering {
390 self.fail(location, "`Yield` should have been replaced by generator lowering");
392 self.check_edge(location, *resume, EdgeKind::Normal);
393 if let Some(drop) = drop {
394 self.check_edge(location, *drop, EdgeKind::Normal);
397 TerminatorKind::FalseEdge { real_target, imaginary_target } => {
398 self.check_edge(location, *real_target, EdgeKind::Normal);
399 self.check_edge(location, *imaginary_target, EdgeKind::Normal);
401 TerminatorKind::FalseUnwind { real_target, unwind } => {
402 self.check_edge(location, *real_target, EdgeKind::Normal);
403 if let Some(unwind) = unwind {
404 self.check_edge(location, *unwind, EdgeKind::Unwind);
407 TerminatorKind::InlineAsm { destination, .. } => {
408 if let Some(destination) = destination {
409 self.check_edge(location, *destination, EdgeKind::Normal);
412 // Nothing to validate for these.
413 TerminatorKind::Resume
414 | TerminatorKind::Abort
415 | TerminatorKind::Return
416 | TerminatorKind::Unreachable
417 | TerminatorKind::GeneratorDrop => {}