]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/type_check.rs
[WIP] Move MIR towards a single kind of local
[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::repr::*;
19 use rustc::mir::tcx::LvalueTy;
20 use rustc::mir::transform::{MirPass, MirSource, Pass};
21 use rustc::mir::visit::{self, 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         if let Some(ty) = rvalue.ty(self.mir, self.tcx()) {
87             self.sanitize_type(rvalue, ty);
88         }
89     }
90
91     fn visit_mir(&mut self, mir: &Mir<'tcx>) {
92         self.sanitize_type(&"return type", mir.return_ty);
93         for local_decl in &mir.local_decls {
94             self.sanitize_type(local_decl, local_decl.ty);
95         }
96         if self.errors_reported {
97             return;
98         }
99         self.super_mir(mir);
100     }
101 }
102
103 impl<'a, 'b, 'gcx, 'tcx> TypeVerifier<'a, 'b, 'gcx, 'tcx> {
104     fn new(cx: &'a mut TypeChecker<'b, 'gcx, 'tcx>, mir: &'a Mir<'tcx>) -> Self {
105         TypeVerifier {
106             cx: cx,
107             mir: mir,
108             last_span: mir.span,
109             errors_reported: false
110         }
111     }
112
113     fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
114         self.cx.infcx.tcx
115     }
116
117     fn sanitize_type(&mut self, parent: &fmt::Debug, ty: Ty<'tcx>) -> Ty<'tcx> {
118         if ty.needs_infer() || ty.has_escaping_regions() || ty.references_error() {
119             span_mirbug_and_err!(self, parent, "bad type {:?}", ty)
120         } else {
121             ty
122         }
123     }
124
125     fn sanitize_lvalue(&mut self, lvalue: &Lvalue<'tcx>, location: Location) -> LvalueTy<'tcx> {
126         debug!("sanitize_lvalue: {:?}", lvalue);
127         match *lvalue {
128             Lvalue::Local(index) => LvalueTy::Ty { ty: self.mir.local_decls[index].ty },
129             Lvalue::Static(def_id) =>
130                 LvalueTy::Ty { ty: self.tcx().lookup_item_type(def_id).ty },
131             Lvalue::Projection(ref proj) => {
132                 let base_ty = self.sanitize_lvalue(&proj.base, location);
133                 if let LvalueTy::Ty { ty } = base_ty {
134                     if ty.references_error() {
135                         assert!(self.errors_reported);
136                         return LvalueTy::Ty { ty: self.tcx().types.err };
137                     }
138                 }
139                 self.sanitize_projection(base_ty, &proj.elem, lvalue, location)
140             }
141         }
142     }
143
144     fn sanitize_projection(&mut self,
145                            base: LvalueTy<'tcx>,
146                            pi: &LvalueElem<'tcx>,
147                            lvalue: &Lvalue<'tcx>,
148                            location: Location)
149                            -> LvalueTy<'tcx> {
150         debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, lvalue);
151         let tcx = self.tcx();
152         let base_ty = base.to_ty(tcx);
153         let span = self.last_span;
154         match *pi {
155             ProjectionElem::Deref => {
156                 let deref_ty = base_ty.builtin_deref(true, ty::LvaluePreference::NoPreference);
157                 LvalueTy::Ty {
158                     ty: deref_ty.map(|t| t.ty).unwrap_or_else(|| {
159                         span_mirbug_and_err!(
160                             self, lvalue, "deref of non-pointer {:?}", base_ty)
161                     })
162                 }
163             }
164             ProjectionElem::Index(ref i) => {
165                 self.visit_operand(i, location);
166                 let index_ty = i.ty(self.mir, tcx);
167                 if index_ty != tcx.types.usize {
168                     LvalueTy::Ty {
169                         ty: span_mirbug_and_err!(self, i, "index by non-usize {:?}", i)
170                     }
171                 } else {
172                     LvalueTy::Ty {
173                         ty: base_ty.builtin_index().unwrap_or_else(|| {
174                             span_mirbug_and_err!(
175                                 self, lvalue, "index of non-array {:?}", base_ty)
176                         })
177                     }
178                 }
179             }
180             ProjectionElem::ConstantIndex { .. } => {
181                 // consider verifying in-bounds
182                 LvalueTy::Ty {
183                     ty: base_ty.builtin_index().unwrap_or_else(|| {
184                         span_mirbug_and_err!(
185                             self, lvalue, "index of non-array {:?}", base_ty)
186                     })
187                 }
188             }
189             ProjectionElem::Subslice { from, to } => {
190                 LvalueTy::Ty {
191                     ty: match base_ty.sty {
192                         ty::TyArray(inner, size) => {
193                             let min_size = (from as usize) + (to as usize);
194                             if let Some(rest_size) = size.checked_sub(min_size) {
195                                 tcx.mk_array(inner, rest_size)
196                             } else {
197                                 span_mirbug_and_err!(
198                                     self, lvalue, "taking too-small slice of {:?}", base_ty)
199                             }
200                         }
201                         ty::TySlice(..) => base_ty,
202                         _ => {
203                             span_mirbug_and_err!(
204                                 self, lvalue, "slice of non-array {:?}", base_ty)
205                         }
206                     }
207                 }
208             }
209             ProjectionElem::Downcast(adt_def1, index) =>
210                 match base_ty.sty {
211                     ty::TyAdt(adt_def, substs) if adt_def.is_enum() && adt_def == adt_def1 => {
212                         if index >= adt_def.variants.len() {
213                             LvalueTy::Ty {
214                                 ty: span_mirbug_and_err!(
215                                     self,
216                                     lvalue,
217                                     "cast to variant #{:?} but enum only has {:?}",
218                                     index,
219                                     adt_def.variants.len())
220                             }
221                         } else {
222                             LvalueTy::Downcast {
223                                 adt_def: adt_def,
224                                 substs: substs,
225                                 variant_index: index
226                             }
227                         }
228                     }
229                     _ => LvalueTy::Ty {
230                         ty: span_mirbug_and_err!(
231                             self, lvalue, "can't downcast {:?} as {:?}",
232                             base_ty, adt_def1)
233                     }
234                 },
235             ProjectionElem::Field(field, fty) => {
236                 let fty = self.sanitize_type(lvalue, fty);
237                 match self.field_ty(lvalue, base, field) {
238                     Ok(ty) => {
239                         if let Err(terr) = self.cx.eq_types(span, ty, fty) {
240                             span_mirbug!(
241                                 self, lvalue, "bad field access ({:?}: {:?}): {:?}",
242                                 ty, fty, terr);
243                         }
244                     }
245                     Err(FieldAccessError::OutOfRange { field_count }) => {
246                         span_mirbug!(
247                             self, lvalue, "accessed field #{} but variant only has {}",
248                             field.index(), field_count)
249                     }
250                 }
251                 LvalueTy::Ty { ty: fty }
252             }
253         }
254     }
255
256     fn error(&mut self) -> Ty<'tcx> {
257         self.errors_reported = true;
258         self.tcx().types.err
259     }
260
261     fn field_ty(&mut self,
262                 parent: &fmt::Debug,
263                 base_ty: LvalueTy<'tcx>,
264                 field: Field)
265                 -> Result<Ty<'tcx>, FieldAccessError>
266     {
267         let tcx = self.tcx();
268
269         let (variant, substs) = match base_ty {
270             LvalueTy::Downcast { adt_def, substs, variant_index } => {
271                 (&adt_def.variants[variant_index], substs)
272             }
273             LvalueTy::Ty { ty } => match ty.sty {
274                 ty::TyAdt(adt_def, substs) if adt_def.is_univariant() => {
275                         (&adt_def.variants[0], substs)
276                     }
277                 ty::TyTuple(tys) | ty::TyClosure(_, ty::ClosureSubsts {
278                     upvar_tys: tys, ..
279                 }) => {
280                     return match tys.get(field.index()) {
281                         Some(&ty) => Ok(ty),
282                         None => Err(FieldAccessError::OutOfRange {
283                             field_count: tys.len()
284                         })
285                     }
286                 }
287                 _ => return Ok(span_mirbug_and_err!(
288                     self, parent, "can't project out of {:?}", base_ty))
289             }
290         };
291
292         if let Some(field) = variant.fields.get(field.index()) {
293             Ok(self.cx.normalize(&field.ty(tcx, substs)))
294         } else {
295             Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
296         }
297     }
298 }
299
300 pub struct TypeChecker<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
301     infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
302     fulfillment_cx: traits::FulfillmentContext<'tcx>,
303     last_span: Span
304 }
305
306 impl<'a, 'gcx, 'tcx> TypeChecker<'a, 'gcx, 'tcx> {
307     fn new(infcx: &'a InferCtxt<'a, 'gcx, 'tcx>) -> Self {
308         TypeChecker {
309             infcx: infcx,
310             fulfillment_cx: traits::FulfillmentContext::new(),
311             last_span: DUMMY_SP
312         }
313     }
314
315     fn sub_types(&self, span: Span, sup: Ty<'tcx>, sub: Ty<'tcx>)
316                  -> infer::UnitResult<'tcx>
317     {
318         self.infcx.sub_types(false, infer::TypeOrigin::Misc(span), sup, sub)
319             // FIXME(#32730) propagate obligations
320             .map(|InferOk { obligations, .. }| assert!(obligations.is_empty()))
321     }
322
323     fn eq_types(&self, span: Span, a: Ty<'tcx>, b: Ty<'tcx>)
324                 -> infer::UnitResult<'tcx>
325     {
326         self.infcx.eq_types(false, infer::TypeOrigin::Misc(span), a, b)
327             // FIXME(#32730) propagate obligations
328             .map(|InferOk { obligations, .. }| assert!(obligations.is_empty()))
329     }
330
331     fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
332         self.infcx.tcx
333     }
334
335     fn check_stmt(&mut self, mir: &Mir<'tcx>, stmt: &Statement<'tcx>) {
336         debug!("check_stmt: {:?}", stmt);
337         let tcx = self.tcx();
338         match stmt.kind {
339             StatementKind::Assign(ref lv, ref rv) => {
340                 let lv_ty = lv.ty(mir, tcx).to_ty(tcx);
341                 let rv_ty = rv.ty(mir, tcx);
342                 if let Some(rv_ty) = rv_ty {
343                     if let Err(terr) = self.sub_types(self.last_span, rv_ty, lv_ty) {
344                         span_mirbug!(self, stmt, "bad assignment ({:?} = {:?}): {:?}",
345                                      lv_ty, rv_ty, terr);
346                     }
347                 // FIXME: rvalue with undeterminable type - e.g. inline
348                 // asm.
349                 }
350             }
351             StatementKind::SetDiscriminant{ ref lvalue, variant_index } => {
352                 let lvalue_type = lvalue.ty(mir, tcx).to_ty(tcx);
353                 let adt = match lvalue_type.sty {
354                     TypeVariants::TyAdt(adt, _) if adt.is_enum() => adt,
355                     _ => {
356                         span_bug!(stmt.source_info.span,
357                                   "bad set discriminant ({:?} = {:?}): lhs is not an enum",
358                                   lvalue,
359                                   variant_index);
360                     }
361                 };
362                 if variant_index >= adt.variants.len() {
363                      span_bug!(stmt.source_info.span,
364                                "bad set discriminant ({:?} = {:?}): value of of range",
365                                lvalue,
366                                variant_index);
367                 };
368             }
369             StatementKind::StorageLive(ref lv) |
370             StatementKind::StorageDead(ref lv) => {
371                 match *lv {
372                     Lvalue::Local(_) => {}
373                     _ => {
374                         span_mirbug!(self, stmt, "bad lvalue: expected local");
375                     }
376                 }
377             }
378             StatementKind::Nop => {}
379         }
380     }
381
382     fn check_terminator(&mut self,
383                         mir: &Mir<'tcx>,
384                         term: &Terminator<'tcx>) {
385         debug!("check_terminator: {:?}", term);
386         let tcx = self.tcx();
387         match term.kind {
388             TerminatorKind::Goto { .. } |
389             TerminatorKind::Resume |
390             TerminatorKind::Return |
391             TerminatorKind::Unreachable |
392             TerminatorKind::Drop { .. } => {
393                 // no checks needed for these
394             }
395
396
397             TerminatorKind::DropAndReplace {
398                 ref location,
399                 ref value,
400                 ..
401             } => {
402                 let lv_ty = location.ty(mir, tcx).to_ty(tcx);
403                 let rv_ty = value.ty(mir, tcx);
404                 if let Err(terr) = self.sub_types(self.last_span, rv_ty, lv_ty) {
405                     span_mirbug!(self, term, "bad DropAndReplace ({:?} = {:?}): {:?}",
406                                  lv_ty, rv_ty, terr);
407                 }
408             }
409
410             TerminatorKind::If { ref cond, .. } => {
411                 let cond_ty = cond.ty(mir, tcx);
412                 match cond_ty.sty {
413                     ty::TyBool => {}
414                     _ => {
415                         span_mirbug!(self, term, "bad If ({:?}, not bool", cond_ty);
416                     }
417                 }
418             }
419             TerminatorKind::SwitchInt { ref discr, switch_ty, .. } => {
420                 let discr_ty = discr.ty(mir, tcx).to_ty(tcx);
421                 if let Err(terr) = self.sub_types(self.last_span, discr_ty, switch_ty) {
422                     span_mirbug!(self, term, "bad SwitchInt ({:?} on {:?}): {:?}",
423                                  switch_ty, discr_ty, terr);
424                 }
425                 if !switch_ty.is_integral() && !switch_ty.is_char() &&
426                     !switch_ty.is_bool()
427                 {
428                     span_mirbug!(self, term, "bad SwitchInt discr ty {:?}",switch_ty);
429                 }
430                 // FIXME: check the values
431             }
432             TerminatorKind::Switch { ref discr, adt_def, ref targets } => {
433                 let discr_ty = discr.ty(mir, tcx).to_ty(tcx);
434                 match discr_ty.sty {
435                     ty::TyAdt(def, _) if def.is_enum() &&
436                                          def == adt_def &&
437                                          adt_def.variants.len() == targets.len()
438                       => {},
439                     _ => {
440                         span_mirbug!(self, term, "bad Switch ({:?} on {:?})",
441                                      adt_def, discr_ty);
442                     }
443                 }
444             }
445             TerminatorKind::Call { ref func, ref args, ref destination, .. } => {
446                 let func_ty = func.ty(mir, tcx);
447                 debug!("check_terminator: call, func_ty={:?}", func_ty);
448                 let func_ty = match func_ty.sty {
449                     ty::TyFnDef(.., func_ty) | ty::TyFnPtr(func_ty) => func_ty,
450                     _ => {
451                         span_mirbug!(self, term, "call to non-function {:?}", func_ty);
452                         return;
453                     }
454                 };
455                 let sig = tcx.erase_late_bound_regions(&func_ty.sig);
456                 let sig = self.normalize(&sig);
457                 self.check_call_dest(mir, term, &sig, destination);
458
459                 if self.is_box_free(func) {
460                     self.check_box_free_inputs(mir, term, &sig, args);
461                 } else {
462                     self.check_call_inputs(mir, term, &sig, args);
463                 }
464             }
465             TerminatorKind::Assert { ref cond, ref msg, .. } => {
466                 let cond_ty = cond.ty(mir, tcx);
467                 if cond_ty != tcx.types.bool {
468                     span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
469                 }
470
471                 if let AssertMessage::BoundsCheck { ref len, ref index } = *msg {
472                     if len.ty(mir, tcx) != tcx.types.usize {
473                         span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
474                     }
475                     if index.ty(mir, tcx) != tcx.types.usize {
476                         span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
477                     }
478                 }
479             }
480         }
481     }
482
483     fn check_call_dest(&self,
484                        mir: &Mir<'tcx>,
485                        term: &Terminator<'tcx>,
486                        sig: &ty::FnSig<'tcx>,
487                        destination: &Option<(Lvalue<'tcx>, BasicBlock)>) {
488         let tcx = self.tcx();
489         match *destination {
490             Some((ref dest, _)) => {
491                 let dest_ty = dest.ty(mir, tcx).to_ty(tcx);
492                 if let Err(terr) = self.sub_types(self.last_span, sig.output, dest_ty) {
493                     span_mirbug!(self, term,
494                                  "call dest mismatch ({:?} <- {:?}): {:?}",
495                                  dest_ty, sig.output, terr);
496                 }
497             },
498             None => {
499                 // FIXME(canndrew): This is_never should probably be an is_uninhabited
500                 if !sig.output.is_never() {
501                     span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
502                 }
503             },
504         }
505     }
506
507     fn check_call_inputs(&self,
508                          mir: &Mir<'tcx>,
509                          term: &Terminator<'tcx>,
510                          sig: &ty::FnSig<'tcx>,
511                          args: &[Operand<'tcx>])
512     {
513         debug!("check_call_inputs({:?}, {:?})", sig, args);
514         if args.len() < sig.inputs.len() ||
515            (args.len() > sig.inputs.len() && !sig.variadic) {
516             span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
517         }
518         for (n, (fn_arg, op_arg)) in sig.inputs.iter().zip(args).enumerate() {
519             let op_arg_ty = op_arg.ty(mir, self.tcx());
520             if let Err(terr) = self.sub_types(self.last_span, op_arg_ty, fn_arg) {
521                 span_mirbug!(self, term, "bad arg #{:?} ({:?} <- {:?}): {:?}",
522                              n, fn_arg, op_arg_ty, terr);
523             }
524         }
525     }
526
527     fn is_box_free(&self, operand: &Operand<'tcx>) -> bool {
528         match operand {
529             &Operand::Constant(Constant {
530                 literal: Literal::Item { def_id, .. }, ..
531             }) => {
532                 Some(def_id) == self.tcx().lang_items.box_free_fn()
533             }
534             _ => false,
535         }
536     }
537
538     fn check_box_free_inputs(&self,
539                              mir: &Mir<'tcx>,
540                              term: &Terminator<'tcx>,
541                              sig: &ty::FnSig<'tcx>,
542                              args: &[Operand<'tcx>])
543     {
544         debug!("check_box_free_inputs");
545
546         // box_free takes a Box as a pointer. Allow for that.
547
548         if sig.inputs.len() != 1 {
549             span_mirbug!(self, term, "box_free should take 1 argument");
550             return;
551         }
552
553         let pointee_ty = match sig.inputs[0].sty {
554             ty::TyRawPtr(mt) => mt.ty,
555             _ => {
556                 span_mirbug!(self, term, "box_free should take a raw ptr");
557                 return;
558             }
559         };
560
561         if args.len() != 1 {
562             span_mirbug!(self, term, "box_free called with wrong # of args");
563             return;
564         }
565
566         let arg_ty = match args[0].ty(mir, self.tcx()).sty {
567             ty::TyRawPtr(mt) => mt.ty,
568             ty::TyBox(ty) => ty,
569             _ => {
570                 span_mirbug!(self, term, "box_free called with bad arg ty");
571                 return;
572             }
573         };
574
575         if let Err(terr) = self.sub_types(self.last_span, arg_ty, pointee_ty) {
576             span_mirbug!(self, term, "bad box_free arg ({:?} <- {:?}): {:?}",
577                          pointee_ty, arg_ty, terr);
578         }
579     }
580
581     fn check_iscleanup(&mut self, mir: &Mir<'tcx>, block: &BasicBlockData<'tcx>)
582     {
583         let is_cleanup = block.is_cleanup;
584         self.last_span = block.terminator().source_info.span;
585         match block.terminator().kind {
586             TerminatorKind::Goto { target } =>
587                 self.assert_iscleanup(mir, block, target, is_cleanup),
588             TerminatorKind::If { targets: (on_true, on_false), .. } => {
589                 self.assert_iscleanup(mir, block, on_true, is_cleanup);
590                 self.assert_iscleanup(mir, block, on_false, is_cleanup);
591             }
592             TerminatorKind::Switch { ref targets, .. } |
593             TerminatorKind::SwitchInt { ref targets, .. } => {
594                 for target in targets {
595                     self.assert_iscleanup(mir, block, *target, is_cleanup);
596                 }
597             }
598             TerminatorKind::Resume => {
599                 if !is_cleanup {
600                     span_mirbug!(self, block, "resume on non-cleanup block!")
601                 }
602             }
603             TerminatorKind::Return => {
604                 if is_cleanup {
605                     span_mirbug!(self, block, "return on cleanup block")
606                 }
607             }
608             TerminatorKind::Unreachable => {}
609             TerminatorKind::Drop { target, unwind, .. } |
610             TerminatorKind::DropAndReplace { target, unwind, .. } |
611             TerminatorKind::Assert { target, cleanup: unwind, .. } => {
612                 self.assert_iscleanup(mir, block, target, is_cleanup);
613                 if let Some(unwind) = unwind {
614                     if is_cleanup {
615                         span_mirbug!(self, block, "unwind on cleanup block")
616                     }
617                     self.assert_iscleanup(mir, block, unwind, true);
618                 }
619             }
620             TerminatorKind::Call { ref destination, cleanup, .. } => {
621                 if let &Some((_, target)) = destination {
622                     self.assert_iscleanup(mir, block, target, is_cleanup);
623                 }
624                 if let Some(cleanup) = cleanup {
625                     if is_cleanup {
626                         span_mirbug!(self, block, "cleanup on cleanup block")
627                     }
628                     self.assert_iscleanup(mir, block, cleanup, true);
629                 }
630             }
631         }
632     }
633
634     fn assert_iscleanup(&mut self,
635                         mir: &Mir<'tcx>,
636                         ctxt: &fmt::Debug,
637                         bb: BasicBlock,
638                         iscleanuppad: bool)
639     {
640         if mir[bb].is_cleanup != iscleanuppad {
641             span_mirbug!(self, ctxt, "cleanuppad mismatch: {:?} should be {:?}",
642                          bb, iscleanuppad);
643         }
644     }
645
646     fn typeck_mir(&mut self, mir: &Mir<'tcx>) {
647         self.last_span = mir.span;
648         debug!("run_on_mir: {:?}", mir.span);
649         for block in mir.basic_blocks() {
650             for stmt in &block.statements {
651                 if stmt.source_info.span != DUMMY_SP {
652                     self.last_span = stmt.source_info.span;
653                 }
654                 self.check_stmt(mir, stmt);
655             }
656
657             self.check_terminator(mir, block.terminator());
658             self.check_iscleanup(mir, block);
659         }
660     }
661
662
663     fn normalize<T>(&mut self, value: &T) -> T
664         where T: fmt::Debug + TypeFoldable<'tcx>
665     {
666         let mut selcx = traits::SelectionContext::new(self.infcx);
667         let cause = traits::ObligationCause::misc(self.last_span, ast::CRATE_NODE_ID);
668         let traits::Normalized { value, obligations } =
669             traits::normalize(&mut selcx, cause, value);
670
671         debug!("normalize: value={:?} obligations={:?}",
672                value,
673                obligations);
674
675         let mut fulfill_cx = &mut self.fulfillment_cx;
676         for obligation in obligations {
677             fulfill_cx.register_predicate_obligation(self.infcx, obligation);
678         }
679
680         value
681     }
682
683     fn verify_obligations(&mut self, mir: &Mir<'tcx>) {
684         self.last_span = mir.span;
685         if let Err(e) = self.fulfillment_cx.select_all_or_error(self.infcx) {
686             span_mirbug!(self, "", "errors selecting obligation: {:?}",
687                          e);
688         }
689     }
690 }
691
692 pub struct TypeckMir;
693
694 impl TypeckMir {
695     pub fn new() -> Self {
696         TypeckMir
697     }
698 }
699
700 impl<'tcx> MirPass<'tcx> for TypeckMir {
701     fn run_pass<'a>(&mut self, tcx: TyCtxt<'a, 'tcx, 'tcx>,
702                     src: MirSource, mir: &mut Mir<'tcx>) {
703         debug!("run_pass: {}", tcx.node_path_str(src.item_id()));
704
705         if tcx.sess.err_count() > 0 {
706             // compiling a broken program can obviously result in a
707             // broken MIR, so try not to report duplicate errors.
708             return;
709         }
710         let param_env = ty::ParameterEnvironment::for_item(tcx, src.item_id());
711         tcx.infer_ctxt(None, Some(param_env), Reveal::NotSpecializable).enter(|infcx| {
712             let mut checker = TypeChecker::new(&infcx);
713             {
714                 let mut verifier = TypeVerifier::new(&mut checker, mir);
715                 verifier.visit_mir(mir);
716                 if verifier.errors_reported {
717                     // don't do further checks to avoid ICEs
718                     return;
719                 }
720             }
721             checker.typeck_mir(mir);
722             checker.verify_obligations(mir);
723         });
724     }
725 }
726
727 impl Pass for TypeckMir {
728 }