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