]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/type_check.rs
Make Rvalue::ty infallible
[rust.git] / src / librustc_mir / transform / type_check.rs
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.
4 //
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.
10
11 //! This pass type-checks the MIR to ensure it is not broken.
12 #![allow(unreachable_code)]
13
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};
18 use rustc::mir::*;
19 use rustc::mir::tcx::LvalueTy;
20 use rustc::mir::transform::{MirPass, MirSource, Pass};
21 use rustc::mir::visit::Visitor;
22 use std::fmt;
23 use syntax::ast;
24 use syntax_pos::{Span, DUMMY_SP};
25
26 use rustc_data_structures::indexed_vec::Idx;
27
28 macro_rules! span_mirbug {
29     ($context:expr, $elem:expr, $($message:tt)*) => ({
30         $context.tcx().sess.span_warn(
31             $context.last_span,
32             &format!("broken MIR ({:?}): {}", $elem, format!($($message)*))
33         )
34     })
35 }
36
37 macro_rules! span_mirbug_and_err {
38     ($context:expr, $elem:expr, $($message:tt)*) => ({
39         {
40             $context.tcx().sess.span_warn(
41                 $context.last_span,
42                 &format!("broken MIR ({:?}): {:?}", $elem, format!($($message)*))
43             );
44             $context.error()
45         }
46     })
47 }
48
49 enum FieldAccessError {
50     OutOfRange { field_count: usize }
51 }
52
53 /// Verifies that MIR types are sane to not crash further checks.
54 ///
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
57 /// is a problem.
58 struct TypeVerifier<'a, 'b: 'a, 'gcx: 'b+'tcx, 'tcx: 'b> {
59     cx: &'a mut TypeChecker<'b, 'gcx, 'tcx>,
60     mir: &'a Mir<'tcx>,
61     last_span: Span,
62     errors_reported: bool
63 }
64
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;
69         }
70     }
71
72     fn visit_lvalue(&mut self,
73                     lvalue: &Lvalue<'tcx>,
74                     _context: visit::LvalueContext,
75                     location: Location) {
76         self.sanitize_lvalue(lvalue, location);
77     }
78
79     fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
80         self.super_constant(constant, location);
81         self.sanitize_type(constant, constant.ty);
82     }
83
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);
88     }
89
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);
94         }
95         if self.errors_reported {
96             return;
97         }
98         self.super_mir(mir);
99     }
100 }
101
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 {
104         TypeVerifier {
105             cx: cx,
106             mir: mir,
107             last_span: mir.span,
108             errors_reported: false
109         }
110     }
111
112     fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
113         self.cx.infcx.tcx
114     }
115
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)
119         } else {
120             ty
121         }
122     }
123
124     fn sanitize_lvalue(&mut self, lvalue: &Lvalue<'tcx>, location: Location) -> LvalueTy<'tcx> {
125         debug!("sanitize_lvalue: {:?}", lvalue);
126         match *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 };
136                     }
137                 }
138                 self.sanitize_projection(base_ty, &proj.elem, lvalue, location)
139             }
140         }
141     }
142
143     fn sanitize_projection(&mut self,
144                            base: LvalueTy<'tcx>,
145                            pi: &LvalueElem<'tcx>,
146                            lvalue: &Lvalue<'tcx>,
147                            location: Location)
148                            -> LvalueTy<'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;
153         match *pi {
154             ProjectionElem::Deref => {
155                 let deref_ty = base_ty.builtin_deref(true, ty::LvaluePreference::NoPreference);
156                 LvalueTy::Ty {
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)
160                     })
161                 }
162             }
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 {
167                     LvalueTy::Ty {
168                         ty: span_mirbug_and_err!(self, i, "index by non-usize {:?}", i)
169                     }
170                 } else {
171                     LvalueTy::Ty {
172                         ty: base_ty.builtin_index().unwrap_or_else(|| {
173                             span_mirbug_and_err!(
174                                 self, lvalue, "index of non-array {:?}", base_ty)
175                         })
176                     }
177                 }
178             }
179             ProjectionElem::ConstantIndex { .. } => {
180                 // consider verifying in-bounds
181                 LvalueTy::Ty {
182                     ty: base_ty.builtin_index().unwrap_or_else(|| {
183                         span_mirbug_and_err!(
184                             self, lvalue, "index of non-array {:?}", base_ty)
185                     })
186                 }
187             }
188             ProjectionElem::Subslice { from, to } => {
189                 LvalueTy::Ty {
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)
195                             } else {
196                                 span_mirbug_and_err!(
197                                     self, lvalue, "taking too-small slice of {:?}", base_ty)
198                             }
199                         }
200                         ty::TySlice(..) => base_ty,
201                         _ => {
202                             span_mirbug_and_err!(
203                                 self, lvalue, "slice of non-array {:?}", base_ty)
204                         }
205                     }
206                 }
207             }
208             ProjectionElem::Downcast(adt_def1, index) =>
209                 match base_ty.sty {
210                     ty::TyAdt(adt_def, substs) if adt_def.is_enum() && adt_def == adt_def1 => {
211                         if index >= adt_def.variants.len() {
212                             LvalueTy::Ty {
213                                 ty: span_mirbug_and_err!(
214                                     self,
215                                     lvalue,
216                                     "cast to variant #{:?} but enum only has {:?}",
217                                     index,
218                                     adt_def.variants.len())
219                             }
220                         } else {
221                             LvalueTy::Downcast {
222                                 adt_def: adt_def,
223                                 substs: substs,
224                                 variant_index: index
225                             }
226                         }
227                     }
228                     _ => LvalueTy::Ty {
229                         ty: span_mirbug_and_err!(
230                             self, lvalue, "can't downcast {:?} as {:?}",
231                             base_ty, adt_def1)
232                     }
233                 },
234             ProjectionElem::Field(field, fty) => {
235                 let fty = self.sanitize_type(lvalue, fty);
236                 match self.field_ty(lvalue, base, field) {
237                     Ok(ty) => {
238                         if let Err(terr) = self.cx.eq_types(span, ty, fty) {
239                             span_mirbug!(
240                                 self, lvalue, "bad field access ({:?}: {:?}): {:?}",
241                                 ty, fty, terr);
242                         }
243                     }
244                     Err(FieldAccessError::OutOfRange { field_count }) => {
245                         span_mirbug!(
246                             self, lvalue, "accessed field #{} but variant only has {}",
247                             field.index(), field_count)
248                     }
249                 }
250                 LvalueTy::Ty { ty: fty }
251             }
252         }
253     }
254
255     fn error(&mut self) -> Ty<'tcx> {
256         self.errors_reported = true;
257         self.tcx().types.err
258     }
259
260     fn field_ty(&mut self,
261                 parent: &fmt::Debug,
262                 base_ty: LvalueTy<'tcx>,
263                 field: Field)
264                 -> Result<Ty<'tcx>, FieldAccessError>
265     {
266         let tcx = self.tcx();
267
268         let (variant, substs) = match base_ty {
269             LvalueTy::Downcast { adt_def, substs, variant_index } => {
270                 (&adt_def.variants[variant_index], substs)
271             }
272             LvalueTy::Ty { ty } => match ty.sty {
273                 ty::TyAdt(adt_def, substs) if adt_def.is_univariant() => {
274                         (&adt_def.variants[0], substs)
275                     }
276                 ty::TyClosure(def_id, substs) => {
277                     return match substs.upvar_tys(def_id, tcx).nth(field.index()) {
278                         Some(ty) => Ok(ty),
279                         None => Err(FieldAccessError::OutOfRange {
280                             field_count: substs.upvar_tys(def_id, tcx).count()
281                         })
282                     }
283                 }
284                 ty::TyTuple(tys, _) => {
285                     return match tys.get(field.index()) {
286                         Some(&ty) => Ok(ty),
287                         None => Err(FieldAccessError::OutOfRange {
288                             field_count: tys.len()
289                         })
290                     }
291                 }
292                 _ => return Ok(span_mirbug_and_err!(
293                     self, parent, "can't project out of {:?}", base_ty))
294             }
295         };
296
297         if let Some(field) = variant.fields.get(field.index()) {
298             Ok(self.cx.normalize(&field.ty(tcx, substs)))
299         } else {
300             Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
301         }
302     }
303 }
304
305 pub struct TypeChecker<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
306     infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
307     fulfillment_cx: traits::FulfillmentContext<'tcx>,
308     last_span: Span,
309     body_id: ast::NodeId,
310 }
311
312 impl<'a, 'gcx, 'tcx> TypeChecker<'a, 'gcx, 'tcx> {
313     fn new(infcx: &'a InferCtxt<'a, 'gcx, 'tcx>, body_id: ast::NodeId) -> Self {
314         TypeChecker {
315             infcx: infcx,
316             fulfillment_cx: traits::FulfillmentContext::new(),
317             last_span: DUMMY_SP,
318             body_id: body_id,
319         }
320     }
321
322     fn misc(&self, span: Span) -> traits::ObligationCause<'tcx> {
323         traits::ObligationCause::misc(span, self.body_id)
324     }
325
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);
329         }
330         infer_ok.value
331     }
332
333     fn sub_types(&mut self, sup: Ty<'tcx>, sub: Ty<'tcx>)
334                  -> infer::UnitResult<'tcx>
335     {
336         self.infcx.sub_types(false, &self.misc(self.last_span), sup, sub)
337             .map(|ok| self.register_infer_ok_obligations(ok))
338     }
339
340     fn eq_types(&mut self, span: Span, a: Ty<'tcx>, b: Ty<'tcx>)
341                 -> infer::UnitResult<'tcx>
342     {
343         self.infcx.eq_types(false, &self.misc(span), a, b)
344             .map(|ok| self.register_infer_ok_obligations(ok))
345     }
346
347     fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
348         self.infcx.tcx
349     }
350
351     fn check_stmt(&mut self, mir: &Mir<'tcx>, stmt: &Statement<'tcx>) {
352         debug!("check_stmt: {:?}", stmt);
353         let tcx = self.tcx();
354         match stmt.kind {
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 ({:?} = {:?}): {:?}",
360                                  lv_ty, rv_ty, terr);
361                 }
362             }
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,
367                     _ => {
368                         span_bug!(stmt.source_info.span,
369                                   "bad set discriminant ({:?} = {:?}): lhs is not an enum",
370                                   lvalue,
371                                   variant_index);
372                     }
373                 };
374                 if variant_index >= adt.variants.len() {
375                      span_bug!(stmt.source_info.span,
376                                "bad set discriminant ({:?} = {:?}): value of of range",
377                                lvalue,
378                                variant_index);
379                 };
380             }
381             StatementKind::StorageLive(ref lv) |
382             StatementKind::StorageDead(ref lv) => {
383                 match *lv {
384                     Lvalue::Local(_) => {}
385                     _ => {
386                         span_mirbug!(self, stmt, "bad lvalue: expected local");
387                     }
388                 }
389             }
390             StatementKind::InlineAsm { .. } |
391             StatementKind::Nop => {}
392         }
393     }
394
395     fn check_terminator(&mut self,
396                         mir: &Mir<'tcx>,
397                         term: &Terminator<'tcx>) {
398         debug!("check_terminator: {:?}", term);
399         let tcx = self.tcx();
400         match term.kind {
401             TerminatorKind::Goto { .. } |
402             TerminatorKind::Resume |
403             TerminatorKind::Return |
404             TerminatorKind::Unreachable |
405             TerminatorKind::Drop { .. } => {
406                 // no checks needed for these
407             }
408
409
410             TerminatorKind::DropAndReplace {
411                 ref location,
412                 ref value,
413                 ..
414             } => {
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 ({:?} = {:?}): {:?}",
419                                  lv_ty, rv_ty, terr);
420                 }
421             }
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);
427                 }
428                 if !switch_ty.is_integral() && !switch_ty.is_char() &&
429                     !switch_ty.is_bool()
430                 {
431                     span_mirbug!(self, term, "bad SwitchInt discr ty {:?}",switch_ty);
432                 }
433                 // FIXME: check the values
434             }
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,
440                     _ => {
441                         span_mirbug!(self, term, "call to non-function {:?}", func_ty);
442                         return;
443                     }
444                 };
445                 let sig = tcx.erase_late_bound_regions(&sig);
446                 let sig = self.normalize(&sig);
447                 self.check_call_dest(mir, term, &sig, destination);
448
449                 if self.is_box_free(func) {
450                     self.check_box_free_inputs(mir, term, &sig, args);
451                 } else {
452                     self.check_call_inputs(mir, term, &sig, args);
453                 }
454             }
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);
459                 }
460
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)
464                     }
465                     if index.ty(mir, tcx) != tcx.types.usize {
466                         span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
467                     }
468                 }
469             }
470         }
471     }
472
473     fn check_call_dest(&mut self,
474                        mir: &Mir<'tcx>,
475                        term: &Terminator<'tcx>,
476                        sig: &ty::FnSig<'tcx>,
477                        destination: &Option<(Lvalue<'tcx>, BasicBlock)>) {
478         let tcx = self.tcx();
479         match *destination {
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);
486                 }
487             },
488             None => {
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);
492                 }
493             },
494         }
495     }
496
497     fn check_call_inputs(&mut self,
498                          mir: &Mir<'tcx>,
499                          term: &Terminator<'tcx>,
500                          sig: &ty::FnSig<'tcx>,
501                          args: &[Operand<'tcx>])
502     {
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);
507         }
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);
513             }
514         }
515     }
516
517     fn is_box_free(&self, operand: &Operand<'tcx>) -> bool {
518         match operand {
519             &Operand::Constant(Constant {
520                 literal: Literal::Item { def_id, .. }, ..
521             }) => {
522                 Some(def_id) == self.tcx().lang_items.box_free_fn()
523             }
524             _ => false,
525         }
526     }
527
528     fn check_box_free_inputs(&mut self,
529                              mir: &Mir<'tcx>,
530                              term: &Terminator<'tcx>,
531                              sig: &ty::FnSig<'tcx>,
532                              args: &[Operand<'tcx>])
533     {
534         debug!("check_box_free_inputs");
535
536         // box_free takes a Box as a pointer. Allow for that.
537
538         if sig.inputs().len() != 1 {
539             span_mirbug!(self, term, "box_free should take 1 argument");
540             return;
541         }
542
543         let pointee_ty = match sig.inputs()[0].sty {
544             ty::TyRawPtr(mt) => mt.ty,
545             _ => {
546                 span_mirbug!(self, term, "box_free should take a raw ptr");
547                 return;
548             }
549         };
550
551         if args.len() != 1 {
552             span_mirbug!(self, term, "box_free called with wrong # of args");
553             return;
554         }
555
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(),
560             _ => {
561                 span_mirbug!(self, term, "box_free called with bad arg ty");
562                 return;
563             }
564         };
565
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);
569         }
570     }
571
572     fn check_iscleanup(&mut self, mir: &Mir<'tcx>, block: &BasicBlockData<'tcx>)
573     {
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);
582                 }
583             }
584             TerminatorKind::Resume => {
585                 if !is_cleanup {
586                     span_mirbug!(self, block, "resume on non-cleanup block!")
587                 }
588             }
589             TerminatorKind::Return => {
590                 if is_cleanup {
591                     span_mirbug!(self, block, "return on cleanup block")
592                 }
593             }
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 {
600                     if is_cleanup {
601                         span_mirbug!(self, block, "unwind on cleanup block")
602                     }
603                     self.assert_iscleanup(mir, block, unwind, true);
604                 }
605             }
606             TerminatorKind::Call { ref destination, cleanup, .. } => {
607                 if let &Some((_, target)) = destination {
608                     self.assert_iscleanup(mir, block, target, is_cleanup);
609                 }
610                 if let Some(cleanup) = cleanup {
611                     if is_cleanup {
612                         span_mirbug!(self, block, "cleanup on cleanup block")
613                     }
614                     self.assert_iscleanup(mir, block, cleanup, true);
615                 }
616             }
617         }
618     }
619
620     fn assert_iscleanup(&mut self,
621                         mir: &Mir<'tcx>,
622                         ctxt: &fmt::Debug,
623                         bb: BasicBlock,
624                         iscleanuppad: bool)
625     {
626         if mir[bb].is_cleanup != iscleanuppad {
627             span_mirbug!(self, ctxt, "cleanuppad mismatch: {:?} should be {:?}",
628                          bb, iscleanuppad);
629         }
630     }
631
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;
639                 }
640                 self.check_stmt(mir, stmt);
641             }
642
643             self.check_terminator(mir, block.terminator());
644             self.check_iscleanup(mir, block);
645         }
646     }
647
648
649     fn normalize<T>(&mut self, value: &T) -> T
650         where T: fmt::Debug + TypeFoldable<'tcx>
651     {
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);
656
657         debug!("normalize: value={:?} obligations={:?}",
658                value,
659                obligations);
660
661         let mut fulfill_cx = &mut self.fulfillment_cx;
662         for obligation in obligations {
663             fulfill_cx.register_predicate_obligation(self.infcx, obligation);
664         }
665
666         value
667     }
668
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: {:?}",
673                          e);
674         }
675     }
676 }
677
678 pub struct TypeckMir;
679
680 impl TypeckMir {
681     pub fn new() -> Self {
682         TypeckMir
683     }
684 }
685
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()));
690
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.
694             return;
695         }
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());
699             {
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
704                     return;
705                 }
706             }
707             checker.typeck_mir(mir);
708             checker.verify_obligations(mir);
709         });
710     }
711 }
712
713 impl Pass for TypeckMir {
714 }