1 // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! This pass type-checks the MIR to ensure it is not broken.
12 #![allow(unreachable_code)]
14 use rustc::infer::{self, InferCtxt, InferOk};
15 use rustc::traits::{self, Reveal};
16 use rustc::ty::fold::TypeFoldable;
17 use rustc::ty::{self, Ty, TyCtxt, TypeVariants};
19 use rustc::mir::tcx::LvalueTy;
20 use rustc::mir::transform::{MirPass, MirSource, Pass};
21 use rustc::mir::visit::Visitor;
24 use syntax_pos::{Span, DUMMY_SP};
26 use rustc_data_structures::indexed_vec::Idx;
28 macro_rules! span_mirbug {
29 ($context:expr, $elem:expr, $($message:tt)*) => ({
30 $context.tcx().sess.span_warn(
32 &format!("broken MIR ({:?}): {}", $elem, format!($($message)*))
37 macro_rules! span_mirbug_and_err {
38 ($context:expr, $elem:expr, $($message:tt)*) => ({
40 $context.tcx().sess.span_warn(
42 &format!("broken MIR ({:?}): {:?}", $elem, format!($($message)*))
49 enum FieldAccessError {
50 OutOfRange { field_count: usize }
53 /// Verifies that MIR types are sane to not crash further checks.
55 /// The sanitize_XYZ methods here take an MIR object and compute its
56 /// type, calling `span_mirbug` and returning an error type if there
58 struct TypeVerifier<'a, 'b: 'a, 'gcx: 'b+'tcx, 'tcx: 'b> {
59 cx: &'a mut TypeChecker<'b, 'gcx, 'tcx>,
65 impl<'a, 'b, 'gcx, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'gcx, 'tcx> {
66 fn visit_span(&mut self, span: &Span) {
67 if *span != DUMMY_SP {
68 self.last_span = *span;
72 fn visit_lvalue(&mut self,
73 lvalue: &Lvalue<'tcx>,
74 _context: visit::LvalueContext,
76 self.sanitize_lvalue(lvalue, location);
79 fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
80 self.super_constant(constant, location);
81 self.sanitize_type(constant, constant.ty);
84 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
85 self.super_rvalue(rvalue, location);
86 let rval_ty = rvalue.ty(self.mir, self.tcx());
87 self.sanitize_type(rvalue, rval_ty);
90 fn visit_mir(&mut self, mir: &Mir<'tcx>) {
91 self.sanitize_type(&"return type", mir.return_ty);
92 for local_decl in &mir.local_decls {
93 self.sanitize_type(local_decl, local_decl.ty);
95 if self.errors_reported {
102 impl<'a, 'b, 'gcx, 'tcx> TypeVerifier<'a, 'b, 'gcx, 'tcx> {
103 fn new(cx: &'a mut TypeChecker<'b, 'gcx, 'tcx>, mir: &'a Mir<'tcx>) -> Self {
108 errors_reported: false
112 fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
116 fn sanitize_type(&mut self, parent: &fmt::Debug, ty: Ty<'tcx>) -> Ty<'tcx> {
117 if ty.needs_infer() || ty.has_escaping_regions() || ty.references_error() {
118 span_mirbug_and_err!(self, parent, "bad type {:?}", ty)
124 fn sanitize_lvalue(&mut self, lvalue: &Lvalue<'tcx>, location: Location) -> LvalueTy<'tcx> {
125 debug!("sanitize_lvalue: {:?}", lvalue);
127 Lvalue::Local(index) => LvalueTy::Ty { ty: self.mir.local_decls[index].ty },
128 Lvalue::Static(def_id) =>
129 LvalueTy::Ty { ty: self.tcx().item_type(def_id) },
130 Lvalue::Projection(ref proj) => {
131 let base_ty = self.sanitize_lvalue(&proj.base, location);
132 if let LvalueTy::Ty { ty } = base_ty {
133 if ty.references_error() {
134 assert!(self.errors_reported);
135 return LvalueTy::Ty { ty: self.tcx().types.err };
138 self.sanitize_projection(base_ty, &proj.elem, lvalue, location)
143 fn sanitize_projection(&mut self,
144 base: LvalueTy<'tcx>,
145 pi: &LvalueElem<'tcx>,
146 lvalue: &Lvalue<'tcx>,
149 debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, lvalue);
150 let tcx = self.tcx();
151 let base_ty = base.to_ty(tcx);
152 let span = self.last_span;
154 ProjectionElem::Deref => {
155 let deref_ty = base_ty.builtin_deref(true, ty::LvaluePreference::NoPreference);
157 ty: deref_ty.map(|t| t.ty).unwrap_or_else(|| {
158 span_mirbug_and_err!(
159 self, lvalue, "deref of non-pointer {:?}", base_ty)
163 ProjectionElem::Index(ref i) => {
164 self.visit_operand(i, location);
165 let index_ty = i.ty(self.mir, tcx);
166 if index_ty != tcx.types.usize {
168 ty: span_mirbug_and_err!(self, i, "index by non-usize {:?}", i)
172 ty: base_ty.builtin_index().unwrap_or_else(|| {
173 span_mirbug_and_err!(
174 self, lvalue, "index of non-array {:?}", base_ty)
179 ProjectionElem::ConstantIndex { .. } => {
180 // consider verifying in-bounds
182 ty: base_ty.builtin_index().unwrap_or_else(|| {
183 span_mirbug_and_err!(
184 self, lvalue, "index of non-array {:?}", base_ty)
188 ProjectionElem::Subslice { from, to } => {
190 ty: match base_ty.sty {
191 ty::TyArray(inner, size) => {
192 let min_size = (from as usize) + (to as usize);
193 if let Some(rest_size) = size.checked_sub(min_size) {
194 tcx.mk_array(inner, rest_size)
196 span_mirbug_and_err!(
197 self, lvalue, "taking too-small slice of {:?}", base_ty)
200 ty::TySlice(..) => base_ty,
202 span_mirbug_and_err!(
203 self, lvalue, "slice of non-array {:?}", base_ty)
208 ProjectionElem::Downcast(adt_def1, index) =>
210 ty::TyAdt(adt_def, substs) if adt_def.is_enum() && adt_def == adt_def1 => {
211 if index >= adt_def.variants.len() {
213 ty: span_mirbug_and_err!(
216 "cast to variant #{:?} but enum only has {:?}",
218 adt_def.variants.len())
229 ty: span_mirbug_and_err!(
230 self, lvalue, "can't downcast {:?} as {:?}",
234 ProjectionElem::Field(field, fty) => {
235 let fty = self.sanitize_type(lvalue, fty);
236 match self.field_ty(lvalue, base, field) {
238 if let Err(terr) = self.cx.eq_types(span, ty, fty) {
240 self, lvalue, "bad field access ({:?}: {:?}): {:?}",
244 Err(FieldAccessError::OutOfRange { field_count }) => {
246 self, lvalue, "accessed field #{} but variant only has {}",
247 field.index(), field_count)
250 LvalueTy::Ty { ty: fty }
255 fn error(&mut self) -> Ty<'tcx> {
256 self.errors_reported = true;
260 fn field_ty(&mut self,
262 base_ty: LvalueTy<'tcx>,
264 -> Result<Ty<'tcx>, FieldAccessError>
266 let tcx = self.tcx();
268 let (variant, substs) = match base_ty {
269 LvalueTy::Downcast { adt_def, substs, variant_index } => {
270 (&adt_def.variants[variant_index], substs)
272 LvalueTy::Ty { ty } => match ty.sty {
273 ty::TyAdt(adt_def, substs) if adt_def.is_univariant() => {
274 (&adt_def.variants[0], substs)
276 ty::TyClosure(def_id, substs) => {
277 return match substs.upvar_tys(def_id, tcx).nth(field.index()) {
279 None => Err(FieldAccessError::OutOfRange {
280 field_count: substs.upvar_tys(def_id, tcx).count()
284 ty::TyTuple(tys, _) => {
285 return match tys.get(field.index()) {
287 None => Err(FieldAccessError::OutOfRange {
288 field_count: tys.len()
292 _ => return Ok(span_mirbug_and_err!(
293 self, parent, "can't project out of {:?}", base_ty))
297 if let Some(field) = variant.fields.get(field.index()) {
298 Ok(self.cx.normalize(&field.ty(tcx, substs)))
300 Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
305 pub struct TypeChecker<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
306 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
307 fulfillment_cx: traits::FulfillmentContext<'tcx>,
309 body_id: ast::NodeId,
312 impl<'a, 'gcx, 'tcx> TypeChecker<'a, 'gcx, 'tcx> {
313 fn new(infcx: &'a InferCtxt<'a, 'gcx, 'tcx>, body_id: ast::NodeId) -> Self {
316 fulfillment_cx: traits::FulfillmentContext::new(),
322 fn misc(&self, span: Span) -> traits::ObligationCause<'tcx> {
323 traits::ObligationCause::misc(span, self.body_id)
326 pub fn register_infer_ok_obligations<T>(&mut self, infer_ok: InferOk<'tcx, T>) -> T {
327 for obligation in infer_ok.obligations {
328 self.fulfillment_cx.register_predicate_obligation(self.infcx, obligation);
333 fn sub_types(&mut self, sup: Ty<'tcx>, sub: Ty<'tcx>)
334 -> infer::UnitResult<'tcx>
336 self.infcx.sub_types(false, &self.misc(self.last_span), sup, sub)
337 .map(|ok| self.register_infer_ok_obligations(ok))
340 fn eq_types(&mut self, span: Span, a: Ty<'tcx>, b: Ty<'tcx>)
341 -> infer::UnitResult<'tcx>
343 self.infcx.eq_types(false, &self.misc(span), a, b)
344 .map(|ok| self.register_infer_ok_obligations(ok))
347 fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
351 fn check_stmt(&mut self, mir: &Mir<'tcx>, stmt: &Statement<'tcx>) {
352 debug!("check_stmt: {:?}", stmt);
353 let tcx = self.tcx();
355 StatementKind::Assign(ref lv, ref rv) => {
356 let lv_ty = lv.ty(mir, tcx).to_ty(tcx);
357 let rv_ty = rv.ty(mir, tcx);
358 if let Err(terr) = self.sub_types(rv_ty, lv_ty) {
359 span_mirbug!(self, stmt, "bad assignment ({:?} = {:?}): {:?}",
363 StatementKind::SetDiscriminant{ ref lvalue, variant_index } => {
364 let lvalue_type = lvalue.ty(mir, tcx).to_ty(tcx);
365 let adt = match lvalue_type.sty {
366 TypeVariants::TyAdt(adt, _) if adt.is_enum() => adt,
368 span_bug!(stmt.source_info.span,
369 "bad set discriminant ({:?} = {:?}): lhs is not an enum",
374 if variant_index >= adt.variants.len() {
375 span_bug!(stmt.source_info.span,
376 "bad set discriminant ({:?} = {:?}): value of of range",
381 StatementKind::StorageLive(ref lv) |
382 StatementKind::StorageDead(ref lv) => {
384 Lvalue::Local(_) => {}
386 span_mirbug!(self, stmt, "bad lvalue: expected local");
390 StatementKind::InlineAsm { .. } |
391 StatementKind::Nop => {}
395 fn check_terminator(&mut self,
397 term: &Terminator<'tcx>) {
398 debug!("check_terminator: {:?}", term);
399 let tcx = self.tcx();
401 TerminatorKind::Goto { .. } |
402 TerminatorKind::Resume |
403 TerminatorKind::Return |
404 TerminatorKind::Unreachable |
405 TerminatorKind::Drop { .. } => {
406 // no checks needed for these
410 TerminatorKind::DropAndReplace {
415 let lv_ty = location.ty(mir, tcx).to_ty(tcx);
416 let rv_ty = value.ty(mir, tcx);
417 if let Err(terr) = self.sub_types(rv_ty, lv_ty) {
418 span_mirbug!(self, term, "bad DropAndReplace ({:?} = {:?}): {:?}",
422 TerminatorKind::SwitchInt { ref discr, switch_ty, .. } => {
423 let discr_ty = discr.ty(mir, tcx);
424 if let Err(terr) = self.sub_types(discr_ty, switch_ty) {
425 span_mirbug!(self, term, "bad SwitchInt ({:?} on {:?}): {:?}",
426 switch_ty, discr_ty, terr);
428 if !switch_ty.is_integral() && !switch_ty.is_char() &&
431 span_mirbug!(self, term, "bad SwitchInt discr ty {:?}",switch_ty);
433 // FIXME: check the values
435 TerminatorKind::Call { ref func, ref args, ref destination, .. } => {
436 let func_ty = func.ty(mir, tcx);
437 debug!("check_terminator: call, func_ty={:?}", func_ty);
438 let sig = match func_ty.sty {
439 ty::TyFnDef(.., sig) | ty::TyFnPtr(sig) => sig,
441 span_mirbug!(self, term, "call to non-function {:?}", func_ty);
445 let sig = tcx.erase_late_bound_regions(&sig);
446 let sig = self.normalize(&sig);
447 self.check_call_dest(mir, term, &sig, destination);
449 if self.is_box_free(func) {
450 self.check_box_free_inputs(mir, term, &sig, args);
452 self.check_call_inputs(mir, term, &sig, args);
455 TerminatorKind::Assert { ref cond, ref msg, .. } => {
456 let cond_ty = cond.ty(mir, tcx);
457 if cond_ty != tcx.types.bool {
458 span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
461 if let AssertMessage::BoundsCheck { ref len, ref index } = *msg {
462 if len.ty(mir, tcx) != tcx.types.usize {
463 span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
465 if index.ty(mir, tcx) != tcx.types.usize {
466 span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
473 fn check_call_dest(&mut self,
475 term: &Terminator<'tcx>,
476 sig: &ty::FnSig<'tcx>,
477 destination: &Option<(Lvalue<'tcx>, BasicBlock)>) {
478 let tcx = self.tcx();
480 Some((ref dest, _)) => {
481 let dest_ty = dest.ty(mir, tcx).to_ty(tcx);
482 if let Err(terr) = self.sub_types(sig.output(), dest_ty) {
483 span_mirbug!(self, term,
484 "call dest mismatch ({:?} <- {:?}): {:?}",
485 dest_ty, sig.output(), terr);
489 // FIXME(canndrew): This is_never should probably be an is_uninhabited
490 if !sig.output().is_never() {
491 span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
497 fn check_call_inputs(&mut self,
499 term: &Terminator<'tcx>,
500 sig: &ty::FnSig<'tcx>,
501 args: &[Operand<'tcx>])
503 debug!("check_call_inputs({:?}, {:?})", sig, args);
504 if args.len() < sig.inputs().len() ||
505 (args.len() > sig.inputs().len() && !sig.variadic) {
506 span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
508 for (n, (fn_arg, op_arg)) in sig.inputs().iter().zip(args).enumerate() {
509 let op_arg_ty = op_arg.ty(mir, self.tcx());
510 if let Err(terr) = self.sub_types(op_arg_ty, fn_arg) {
511 span_mirbug!(self, term, "bad arg #{:?} ({:?} <- {:?}): {:?}",
512 n, fn_arg, op_arg_ty, terr);
517 fn is_box_free(&self, operand: &Operand<'tcx>) -> bool {
519 &Operand::Constant(Constant {
520 literal: Literal::Item { def_id, .. }, ..
522 Some(def_id) == self.tcx().lang_items.box_free_fn()
528 fn check_box_free_inputs(&mut self,
530 term: &Terminator<'tcx>,
531 sig: &ty::FnSig<'tcx>,
532 args: &[Operand<'tcx>])
534 debug!("check_box_free_inputs");
536 // box_free takes a Box as a pointer. Allow for that.
538 if sig.inputs().len() != 1 {
539 span_mirbug!(self, term, "box_free should take 1 argument");
543 let pointee_ty = match sig.inputs()[0].sty {
544 ty::TyRawPtr(mt) => mt.ty,
546 span_mirbug!(self, term, "box_free should take a raw ptr");
552 span_mirbug!(self, term, "box_free called with wrong # of args");
556 let ty = args[0].ty(mir, self.tcx());
557 let arg_ty = match ty.sty {
558 ty::TyRawPtr(mt) => mt.ty,
559 ty::TyAdt(def, _) if def.is_box() => ty.boxed_ty(),
561 span_mirbug!(self, term, "box_free called with bad arg ty");
566 if let Err(terr) = self.sub_types(arg_ty, pointee_ty) {
567 span_mirbug!(self, term, "bad box_free arg ({:?} <- {:?}): {:?}",
568 pointee_ty, arg_ty, terr);
572 fn check_iscleanup(&mut self, mir: &Mir<'tcx>, block: &BasicBlockData<'tcx>)
574 let is_cleanup = block.is_cleanup;
575 self.last_span = block.terminator().source_info.span;
576 match block.terminator().kind {
577 TerminatorKind::Goto { target } =>
578 self.assert_iscleanup(mir, block, target, is_cleanup),
579 TerminatorKind::SwitchInt { ref targets, .. } => {
580 for target in targets {
581 self.assert_iscleanup(mir, block, *target, is_cleanup);
584 TerminatorKind::Resume => {
586 span_mirbug!(self, block, "resume on non-cleanup block!")
589 TerminatorKind::Return => {
591 span_mirbug!(self, block, "return on cleanup block")
594 TerminatorKind::Unreachable => {}
595 TerminatorKind::Drop { target, unwind, .. } |
596 TerminatorKind::DropAndReplace { target, unwind, .. } |
597 TerminatorKind::Assert { target, cleanup: unwind, .. } => {
598 self.assert_iscleanup(mir, block, target, is_cleanup);
599 if let Some(unwind) = unwind {
601 span_mirbug!(self, block, "unwind on cleanup block")
603 self.assert_iscleanup(mir, block, unwind, true);
606 TerminatorKind::Call { ref destination, cleanup, .. } => {
607 if let &Some((_, target)) = destination {
608 self.assert_iscleanup(mir, block, target, is_cleanup);
610 if let Some(cleanup) = cleanup {
612 span_mirbug!(self, block, "cleanup on cleanup block")
614 self.assert_iscleanup(mir, block, cleanup, true);
620 fn assert_iscleanup(&mut self,
626 if mir[bb].is_cleanup != iscleanuppad {
627 span_mirbug!(self, ctxt, "cleanuppad mismatch: {:?} should be {:?}",
632 fn typeck_mir(&mut self, mir: &Mir<'tcx>) {
633 self.last_span = mir.span;
634 debug!("run_on_mir: {:?}", mir.span);
635 for block in mir.basic_blocks() {
636 for stmt in &block.statements {
637 if stmt.source_info.span != DUMMY_SP {
638 self.last_span = stmt.source_info.span;
640 self.check_stmt(mir, stmt);
643 self.check_terminator(mir, block.terminator());
644 self.check_iscleanup(mir, block);
649 fn normalize<T>(&mut self, value: &T) -> T
650 where T: fmt::Debug + TypeFoldable<'tcx>
652 let mut selcx = traits::SelectionContext::new(self.infcx);
653 let cause = traits::ObligationCause::misc(self.last_span, ast::CRATE_NODE_ID);
654 let traits::Normalized { value, obligations } =
655 traits::normalize(&mut selcx, cause, value);
657 debug!("normalize: value={:?} obligations={:?}",
661 let mut fulfill_cx = &mut self.fulfillment_cx;
662 for obligation in obligations {
663 fulfill_cx.register_predicate_obligation(self.infcx, obligation);
669 fn verify_obligations(&mut self, mir: &Mir<'tcx>) {
670 self.last_span = mir.span;
671 if let Err(e) = self.fulfillment_cx.select_all_or_error(self.infcx) {
672 span_mirbug!(self, "", "errors selecting obligation: {:?}",
678 pub struct TypeckMir;
681 pub fn new() -> Self {
686 impl<'tcx> MirPass<'tcx> for TypeckMir {
687 fn run_pass<'a>(&mut self, tcx: TyCtxt<'a, 'tcx, 'tcx>,
688 src: MirSource, mir: &mut Mir<'tcx>) {
689 debug!("run_pass: {}", tcx.node_path_str(src.item_id()));
691 if tcx.sess.err_count() > 0 {
692 // compiling a broken program can obviously result in a
693 // broken MIR, so try not to report duplicate errors.
696 let param_env = ty::ParameterEnvironment::for_item(tcx, src.item_id());
697 tcx.infer_ctxt(param_env, Reveal::UserFacing).enter(|infcx| {
698 let mut checker = TypeChecker::new(&infcx, src.item_id());
700 let mut verifier = TypeVerifier::new(&mut checker, mir);
701 verifier.visit_mir(mir);
702 if verifier.errors_reported {
703 // don't do further checks to avoid ICEs
707 checker.typeck_mir(mir);
708 checker.verify_obligations(mir);
713 impl Pass for TypeckMir {