]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/borrow_check/nll/type_check/mod.rs
Auto merge of #54993 - TimNN:pda-tdl, r=eddyb
[rust.git] / src / librustc_mir / borrow_check / nll / type_check / mod.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 borrow_check::borrow_set::BorrowSet;
15 use borrow_check::location::LocationTable;
16 use borrow_check::nll::constraints::{ConstraintSet, OutlivesConstraint};
17 use borrow_check::nll::facts::AllFacts;
18 use borrow_check::nll::region_infer::values::LivenessValues;
19 use borrow_check::nll::region_infer::values::PlaceholderIndex;
20 use borrow_check::nll::region_infer::values::PlaceholderIndices;
21 use borrow_check::nll::region_infer::values::RegionValueElements;
22 use borrow_check::nll::region_infer::{ClosureRegionRequirementsExt, TypeTest};
23 use borrow_check::nll::renumber;
24 use borrow_check::nll::type_check::free_region_relations::{
25     CreateResult, UniversalRegionRelations,
26 };
27 use borrow_check::nll::universal_regions::{DefiningTy, UniversalRegions};
28 use borrow_check::nll::ToRegionVid;
29 use dataflow::move_paths::MoveData;
30 use dataflow::FlowAtLocation;
31 use dataflow::MaybeInitializedPlaces;
32 use either::Either;
33 use rustc::hir;
34 use rustc::hir::def_id::DefId;
35 use rustc::infer::canonical::QueryRegionConstraint;
36 use rustc::infer::outlives::env::RegionBoundPairs;
37 use rustc::infer::{InferCtxt, InferOk, LateBoundRegionConversionTime, NLLRegionVariableOrigin};
38 use rustc::mir::interpret::EvalErrorKind::BoundsCheck;
39 use rustc::mir::tcx::PlaceTy;
40 use rustc::mir::visit::{PlaceContext, Visitor, MutatingUseContext, NonMutatingUseContext};
41 use rustc::mir::*;
42 use rustc::traits::query::type_op;
43 use rustc::traits::query::type_op::custom::CustomTypeOp;
44 use rustc::traits::query::{Fallible, NoSolution};
45 use rustc::traits::{ObligationCause, PredicateObligations};
46 use rustc::ty::fold::TypeFoldable;
47 use rustc::ty::subst::{Subst, Substs, UnpackedKind};
48 use rustc::ty::{self, RegionVid, ToPolyTraitRef, Ty, TyCtxt, TyKind};
49 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
50 use rustc_data_structures::indexed_vec::IndexVec;
51 use std::rc::Rc;
52 use std::{fmt, iter};
53 use syntax_pos::{Span, DUMMY_SP};
54 use transform::{MirPass, MirSource};
55
56 macro_rules! span_mirbug {
57     ($context:expr, $elem:expr, $($message:tt)*) => ({
58         $crate::borrow_check::nll::type_check::mirbug(
59             $context.tcx(),
60             $context.last_span,
61             &format!(
62                 "broken MIR in {:?} ({:?}): {}",
63                 $context.mir_def_id,
64                 $elem,
65                 format_args!($($message)*),
66             ),
67         )
68     })
69 }
70
71 macro_rules! span_mirbug_and_err {
72     ($context:expr, $elem:expr, $($message:tt)*) => ({
73         {
74             span_mirbug!($context, $elem, $($message)*);
75             $context.error()
76         }
77     })
78 }
79
80 mod constraint_conversion;
81 pub mod free_region_relations;
82 mod input_output;
83 crate mod liveness;
84 mod relate_tys;
85
86 /// Type checks the given `mir` in the context of the inference
87 /// context `infcx`. Returns any region constraints that have yet to
88 /// be proven. This result is includes liveness constraints that
89 /// ensure that regions appearing in the types of all local variables
90 /// are live at all points where that local variable may later be
91 /// used.
92 ///
93 /// This phase of type-check ought to be infallible -- this is because
94 /// the original, HIR-based type-check succeeded. So if any errors
95 /// occur here, we will get a `bug!` reported.
96 ///
97 /// # Parameters
98 ///
99 /// - `infcx` -- inference context to use
100 /// - `param_env` -- parameter environment to use for trait solving
101 /// - `mir` -- MIR to type-check
102 /// - `mir_def_id` -- DefId from which the MIR is derived (must be local)
103 /// - `region_bound_pairs` -- the implied outlives obligations between type parameters
104 ///   and lifetimes (e.g., `&'a T` implies `T: 'a`)
105 /// - `implicit_region_bound` -- a region which all generic parameters are assumed
106 ///   to outlive; should represent the fn body
107 /// - `input_tys` -- fully liberated, but **not** normalized, expected types of the arguments;
108 ///   the types of the input parameters found in the MIR itself will be equated with these
109 /// - `output_ty` -- fully liberated, but **not** normalized, expected return type;
110 ///   the type for the RETURN_PLACE will be equated with this
111 /// - `liveness` -- results of a liveness computation on the MIR; used to create liveness
112 ///   constraints for the regions in the types of variables
113 /// - `flow_inits` -- results of a maybe-init dataflow analysis
114 /// - `move_data` -- move-data constructed when performing the maybe-init dataflow analysiss
115 pub(crate) fn type_check<'gcx, 'tcx>(
116     infcx: &InferCtxt<'_, 'gcx, 'tcx>,
117     param_env: ty::ParamEnv<'gcx>,
118     mir: &Mir<'tcx>,
119     mir_def_id: DefId,
120     universal_regions: &Rc<UniversalRegions<'tcx>>,
121     location_table: &LocationTable,
122     borrow_set: &BorrowSet<'tcx>,
123     all_facts: &mut Option<AllFacts>,
124     flow_inits: &mut FlowAtLocation<MaybeInitializedPlaces<'_, 'gcx, 'tcx>>,
125     move_data: &MoveData<'tcx>,
126     elements: &Rc<RegionValueElements>,
127 ) -> MirTypeckResults<'tcx> {
128     let implicit_region_bound = infcx.tcx.mk_region(ty::ReVar(universal_regions.fr_fn_body));
129     let mut constraints = MirTypeckRegionConstraints {
130         placeholder_indices: PlaceholderIndices::default(),
131         placeholder_index_to_region: IndexVec::default(),
132         liveness_constraints: LivenessValues::new(elements),
133         outlives_constraints: ConstraintSet::default(),
134         closure_bounds_mapping: Default::default(),
135         type_tests: Vec::default(),
136     };
137
138     let CreateResult {
139         universal_region_relations,
140         region_bound_pairs,
141         normalized_inputs_and_output,
142     } = free_region_relations::create(
143         infcx,
144         param_env,
145         Some(implicit_region_bound),
146         universal_regions,
147         &mut constraints,
148     );
149
150     let mut borrowck_context = BorrowCheckContext {
151         universal_regions,
152         location_table,
153         borrow_set,
154         all_facts,
155         constraints: &mut constraints,
156     };
157
158     type_check_internal(
159         infcx,
160         mir_def_id,
161         param_env,
162         mir,
163         &region_bound_pairs,
164         Some(implicit_region_bound),
165         Some(&mut borrowck_context),
166         Some(&universal_region_relations),
167         |cx| {
168             cx.equate_inputs_and_outputs(mir, universal_regions, &normalized_inputs_and_output);
169             liveness::generate(cx, mir, elements, flow_inits, move_data, location_table);
170
171             cx.borrowck_context
172                 .as_mut()
173                 .map(|bcx| translate_outlives_facts(bcx));
174         },
175     );
176
177     MirTypeckResults {
178         constraints,
179         universal_region_relations,
180     }
181 }
182
183 fn type_check_internal<'a, 'gcx, 'tcx, R>(
184     infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
185     mir_def_id: DefId,
186     param_env: ty::ParamEnv<'gcx>,
187     mir: &'a Mir<'tcx>,
188     region_bound_pairs: &'a RegionBoundPairs<'tcx>,
189     implicit_region_bound: Option<ty::Region<'tcx>>,
190     borrowck_context: Option<&'a mut BorrowCheckContext<'a, 'tcx>>,
191     universal_region_relations: Option<&'a UniversalRegionRelations<'tcx>>,
192     mut extra: impl FnMut(&mut TypeChecker<'a, 'gcx, 'tcx>) -> R,
193 ) -> R where {
194     let mut checker = TypeChecker::new(
195         infcx,
196         mir,
197         mir_def_id,
198         param_env,
199         region_bound_pairs,
200         implicit_region_bound,
201         borrowck_context,
202         universal_region_relations,
203     );
204     let errors_reported = {
205         let mut verifier = TypeVerifier::new(&mut checker, mir);
206         verifier.visit_mir(mir);
207         verifier.errors_reported
208     };
209
210     if !errors_reported {
211         // if verifier failed, don't do further checks to avoid ICEs
212         checker.typeck_mir(mir);
213     }
214
215     extra(&mut checker)
216 }
217
218 fn translate_outlives_facts(cx: &mut BorrowCheckContext) {
219     if let Some(facts) = cx.all_facts {
220         let location_table = cx.location_table;
221         facts
222             .outlives
223             .extend(cx.constraints.outlives_constraints.iter().flat_map(
224                 |constraint: &OutlivesConstraint| {
225                     if let Some(from_location) = constraint.locations.from_location() {
226                         Either::Left(iter::once((
227                             constraint.sup,
228                             constraint.sub,
229                             location_table.mid_index(from_location),
230                         )))
231                     } else {
232                         Either::Right(
233                             location_table
234                                 .all_points()
235                                 .map(move |location| (constraint.sup, constraint.sub, location)),
236                         )
237                     }
238                 },
239             ));
240     }
241 }
242
243 fn mirbug(tcx: TyCtxt, span: Span, msg: &str) {
244     // We sometimes see MIR failures (notably predicate failures) due to
245     // the fact that we check rvalue sized predicates here. So use `delay_span_bug`
246     // to avoid reporting bugs in those cases.
247     tcx.sess.diagnostic().delay_span_bug(span, msg);
248 }
249
250 enum FieldAccessError {
251     OutOfRange { field_count: usize },
252 }
253
254 /// Verifies that MIR types are sane to not crash further checks.
255 ///
256 /// The sanitize_XYZ methods here take an MIR object and compute its
257 /// type, calling `span_mirbug` and returning an error type if there
258 /// is a problem.
259 struct TypeVerifier<'a, 'b: 'a, 'gcx: 'tcx, 'tcx: 'b> {
260     cx: &'a mut TypeChecker<'b, 'gcx, 'tcx>,
261     mir: &'a Mir<'tcx>,
262     last_span: Span,
263     mir_def_id: DefId,
264     errors_reported: bool,
265 }
266
267 impl<'a, 'b, 'gcx, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'gcx, 'tcx> {
268     fn visit_span(&mut self, span: &Span) {
269         if !span.is_dummy() {
270             self.last_span = *span;
271         }
272     }
273
274     fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
275         self.sanitize_place(place, location, context);
276     }
277
278     fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
279         self.super_constant(constant, location);
280         self.sanitize_constant(constant, location);
281         self.sanitize_type(constant, constant.ty);
282
283         if let Some(user_ty) = constant.user_ty {
284             if let Err(terr) = self.cx.relate_type_and_user_type(
285                 constant.ty,
286                 ty::Variance::Invariant,
287                 &UserTypeProjection { base: user_ty, projs: vec![], },
288                 location.to_locations(),
289                 ConstraintCategory::Boring,
290             ) {
291                 span_mirbug!(
292                     self,
293                     constant,
294                     "bad constant user type {:?} vs {:?}: {:?}",
295                     user_ty,
296                     constant.ty,
297                     terr,
298                 );
299             }
300         }
301     }
302
303     fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
304         self.super_rvalue(rvalue, location);
305         let rval_ty = rvalue.ty(self.mir, self.tcx());
306         self.sanitize_type(rvalue, rval_ty);
307     }
308
309     fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) {
310         self.super_local_decl(local, local_decl);
311         self.sanitize_type(local_decl, local_decl.ty);
312
313         for (user_ty, span) in local_decl.user_ty.projections_and_spans() {
314             if let Err(terr) = self.cx.relate_type_and_user_type(
315                 local_decl.ty,
316                 ty::Variance::Invariant,
317                 user_ty,
318                 Locations::All(*span),
319                 ConstraintCategory::TypeAnnotation,
320             ) {
321                 span_mirbug!(
322                     self,
323                     local,
324                     "bad user type on variable {:?}: {:?} != {:?} ({:?})",
325                     local,
326                     local_decl.ty,
327                     local_decl.user_ty,
328                     terr,
329                 );
330             }
331         }
332     }
333
334     fn visit_mir(&mut self, mir: &Mir<'tcx>) {
335         self.sanitize_type(&"return type", mir.return_ty());
336         for local_decl in &mir.local_decls {
337             self.sanitize_type(local_decl, local_decl.ty);
338         }
339         if self.errors_reported {
340             return;
341         }
342         self.super_mir(mir);
343     }
344 }
345
346 impl<'a, 'b, 'gcx, 'tcx> TypeVerifier<'a, 'b, 'gcx, 'tcx> {
347     fn new(cx: &'a mut TypeChecker<'b, 'gcx, 'tcx>, mir: &'a Mir<'tcx>) -> Self {
348         TypeVerifier {
349             mir,
350             mir_def_id: cx.mir_def_id,
351             cx,
352             last_span: mir.span,
353             errors_reported: false,
354         }
355     }
356
357     fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
358         self.cx.infcx.tcx
359     }
360
361     fn sanitize_type(&mut self, parent: &dyn fmt::Debug, ty: Ty<'tcx>) -> Ty<'tcx> {
362         if ty.has_escaping_bound_vars() || ty.references_error() {
363             span_mirbug_and_err!(self, parent, "bad type {:?}", ty)
364         } else {
365             ty
366         }
367     }
368
369     /// Checks that the constant's `ty` field matches up with what
370     /// would be expected from its literal.
371     fn sanitize_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
372         debug!(
373             "sanitize_constant(constant={:?}, location={:?})",
374             constant, location
375         );
376
377         // FIXME(#46702) -- We need some way to get the predicates
378         // associated with the "pre-evaluated" form of the
379         // constant. For example, consider that the constant
380         // may have associated constant projections (`<Foo as
381         // Trait<'a, 'b>>::SOME_CONST`) that impose
382         // constraints on `'a` and `'b`. These constraints
383         // would be lost if we just look at the normalized
384         // value.
385         if let ty::FnDef(def_id, substs) = constant.literal.ty.sty {
386             let tcx = self.tcx();
387             let type_checker = &mut self.cx;
388
389             // FIXME -- For now, use the substitutions from
390             // `value.ty` rather than `value.val`. The
391             // renumberer will rewrite them to independent
392             // sets of regions; in principle, we ought to
393             // derive the type of the `value.val` from "first
394             // principles" and equate with value.ty, but as we
395             // are transitioning to the miri-based system, we
396             // don't have a handy function for that, so for
397             // now we just ignore `value.val` regions.
398
399             let instantiated_predicates = tcx.predicates_of(def_id).instantiate(tcx, substs);
400             type_checker.normalize_and_prove_instantiated_predicates(
401                 instantiated_predicates,
402                 location.to_locations(),
403             );
404         }
405
406         debug!("sanitize_constant: expected_ty={:?}", constant.literal.ty);
407
408         if let Err(terr) = self.cx.eq_types(
409             constant.literal.ty,
410             constant.ty,
411             location.to_locations(),
412             ConstraintCategory::Boring,
413         ) {
414             span_mirbug!(
415                 self,
416                 constant,
417                 "constant {:?} should have type {:?} but has {:?} ({:?})",
418                 constant,
419                 constant.literal.ty,
420                 constant.ty,
421                 terr,
422             );
423         }
424     }
425
426     /// Checks that the types internal to the `place` match up with
427     /// what would be expected.
428     fn sanitize_place(
429         &mut self,
430         place: &Place<'tcx>,
431         location: Location,
432         context: PlaceContext,
433     ) -> PlaceTy<'tcx> {
434         debug!("sanitize_place: {:?}", place);
435         let place_ty = match *place {
436             Place::Local(index) => PlaceTy::Ty {
437                 ty: self.mir.local_decls[index].ty,
438             },
439             Place::Promoted(box (_index, sty)) => {
440                 let sty = self.sanitize_type(place, sty);
441                 // FIXME -- promoted MIR return types reference
442                 // various "free regions" (e.g., scopes and things)
443                 // that they ought not to do. We have to figure out
444                 // how best to handle that -- probably we want treat
445                 // promoted MIR much like closures, renumbering all
446                 // their free regions and propagating constraints
447                 // upwards. We have the same acyclic guarantees, so
448                 // that should be possible. But for now, ignore them.
449                 //
450                 // let promoted_mir = &self.mir.promoted[index];
451                 // promoted_mir.return_ty()
452                 PlaceTy::Ty { ty: sty }
453             }
454             Place::Static(box Static { def_id, ty: sty }) => {
455                 let sty = self.sanitize_type(place, sty);
456                 let ty = self.tcx().type_of(def_id);
457                 let ty = self.cx.normalize(ty, location);
458                 if let Err(terr) =
459                     self.cx
460                         .eq_types(ty, sty, location.to_locations(), ConstraintCategory::Boring)
461                 {
462                     span_mirbug!(
463                         self,
464                         place,
465                         "bad static type ({:?}: {:?}): {:?}",
466                         ty,
467                         sty,
468                         terr
469                     );
470                 }
471                 PlaceTy::Ty { ty: sty }
472             }
473             Place::Projection(ref proj) => {
474                 let base_context = if context.is_mutating_use() {
475                     PlaceContext::MutatingUse(MutatingUseContext::Projection)
476                 } else {
477                     PlaceContext::NonMutatingUse(NonMutatingUseContext::Projection)
478                 };
479                 let base_ty = self.sanitize_place(&proj.base, location, base_context);
480                 if let PlaceTy::Ty { ty } = base_ty {
481                     if ty.references_error() {
482                         assert!(self.errors_reported);
483                         return PlaceTy::Ty {
484                             ty: self.tcx().types.err,
485                         };
486                     }
487                 }
488                 self.sanitize_projection(base_ty, &proj.elem, place, location)
489             }
490         };
491         if let PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) = context {
492             let tcx = self.tcx();
493             let trait_ref = ty::TraitRef {
494                 def_id: tcx.lang_items().copy_trait().unwrap(),
495                 substs: tcx.mk_substs_trait(place_ty.to_ty(tcx), &[]),
496             };
497
498             // In order to have a Copy operand, the type T of the value must be Copy. Note that we
499             // prove that T: Copy, rather than using the type_moves_by_default test. This is
500             // important because type_moves_by_default ignores the resulting region obligations and
501             // assumes they pass. This can result in bounds from Copy impls being unsoundly ignored
502             // (e.g., #29149). Note that we decide to use Copy before knowing whether the bounds
503             // fully apply: in effect, the rule is that if a value of some type could implement
504             // Copy, then it must.
505             self.cx.prove_trait_ref(
506                 trait_ref,
507                 location.to_locations(),
508                 ConstraintCategory::CopyBound,
509             );
510         }
511         place_ty
512     }
513
514     fn sanitize_projection(
515         &mut self,
516         base: PlaceTy<'tcx>,
517         pi: &PlaceElem<'tcx>,
518         place: &Place<'tcx>,
519         location: Location,
520     ) -> PlaceTy<'tcx> {
521         debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, place);
522         let tcx = self.tcx();
523         let base_ty = base.to_ty(tcx);
524         match *pi {
525             ProjectionElem::Deref => {
526                 let deref_ty = base_ty.builtin_deref(true);
527                 PlaceTy::Ty {
528                     ty: deref_ty.map(|t| t.ty).unwrap_or_else(|| {
529                         span_mirbug_and_err!(self, place, "deref of non-pointer {:?}", base_ty)
530                     }),
531                 }
532             }
533             ProjectionElem::Index(i) => {
534                 let index_ty = Place::Local(i).ty(self.mir, tcx).to_ty(tcx);
535                 if index_ty != tcx.types.usize {
536                     PlaceTy::Ty {
537                         ty: span_mirbug_and_err!(self, i, "index by non-usize {:?}", i),
538                     }
539                 } else {
540                     PlaceTy::Ty {
541                         ty: base_ty.builtin_index().unwrap_or_else(|| {
542                             span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
543                         }),
544                     }
545                 }
546             }
547             ProjectionElem::ConstantIndex { .. } => {
548                 // consider verifying in-bounds
549                 PlaceTy::Ty {
550                     ty: base_ty.builtin_index().unwrap_or_else(|| {
551                         span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
552                     }),
553                 }
554             }
555             ProjectionElem::Subslice { from, to } => PlaceTy::Ty {
556                 ty: match base_ty.sty {
557                     ty::Array(inner, size) => {
558                         let size = size.unwrap_usize(tcx);
559                         let min_size = (from as u64) + (to as u64);
560                         if let Some(rest_size) = size.checked_sub(min_size) {
561                             tcx.mk_array(inner, rest_size)
562                         } else {
563                             span_mirbug_and_err!(
564                                 self,
565                                 place,
566                                 "taking too-small slice of {:?}",
567                                 base_ty
568                             )
569                         }
570                     }
571                     ty::Slice(..) => base_ty,
572                     _ => span_mirbug_and_err!(self, place, "slice of non-array {:?}", base_ty),
573                 },
574             },
575             ProjectionElem::Downcast(adt_def1, index) => match base_ty.sty {
576                 ty::Adt(adt_def, substs) if adt_def.is_enum() && adt_def == adt_def1 => {
577                     if index >= adt_def.variants.len() {
578                         PlaceTy::Ty {
579                             ty: span_mirbug_and_err!(
580                                 self,
581                                 place,
582                                 "cast to variant #{:?} but enum only has {:?}",
583                                 index,
584                                 adt_def.variants.len()
585                             ),
586                         }
587                     } else {
588                         PlaceTy::Downcast {
589                             adt_def,
590                             substs,
591                             variant_index: index,
592                         }
593                     }
594                 }
595                 _ => PlaceTy::Ty {
596                     ty: span_mirbug_and_err!(
597                         self,
598                         place,
599                         "can't downcast {:?} as {:?}",
600                         base_ty,
601                         adt_def1
602                     ),
603                 },
604             },
605             ProjectionElem::Field(field, fty) => {
606                 let fty = self.sanitize_type(place, fty);
607                 match self.field_ty(place, base, field, location) {
608                     Ok(ty) => if let Err(terr) = self.cx.eq_types(
609                         ty,
610                         fty,
611                         location.to_locations(),
612                         ConstraintCategory::Boring,
613                     ) {
614                         span_mirbug!(
615                             self,
616                             place,
617                             "bad field access ({:?}: {:?}): {:?}",
618                             ty,
619                             fty,
620                             terr
621                         );
622                     },
623                     Err(FieldAccessError::OutOfRange { field_count }) => span_mirbug!(
624                         self,
625                         place,
626                         "accessed field #{} but variant only has {}",
627                         field.index(),
628                         field_count
629                     ),
630                 }
631                 PlaceTy::Ty { ty: fty }
632             }
633         }
634     }
635
636     fn error(&mut self) -> Ty<'tcx> {
637         self.errors_reported = true;
638         self.tcx().types.err
639     }
640
641     fn field_ty(
642         &mut self,
643         parent: &dyn fmt::Debug,
644         base_ty: PlaceTy<'tcx>,
645         field: Field,
646         location: Location,
647     ) -> Result<Ty<'tcx>, FieldAccessError> {
648         let tcx = self.tcx();
649
650         let (variant, substs) = match base_ty {
651             PlaceTy::Downcast {
652                 adt_def,
653                 substs,
654                 variant_index,
655             } => (&adt_def.variants[variant_index], substs),
656             PlaceTy::Ty { ty } => match ty.sty {
657                 ty::Adt(adt_def, substs) if !adt_def.is_enum() => (&adt_def.variants[0], substs),
658                 ty::Closure(def_id, substs) => {
659                     return match substs.upvar_tys(def_id, tcx).nth(field.index()) {
660                         Some(ty) => Ok(ty),
661                         None => Err(FieldAccessError::OutOfRange {
662                             field_count: substs.upvar_tys(def_id, tcx).count(),
663                         }),
664                     }
665                 }
666                 ty::Generator(def_id, substs, _) => {
667                     // Try pre-transform fields first (upvars and current state)
668                     if let Some(ty) = substs.pre_transforms_tys(def_id, tcx).nth(field.index()) {
669                         return Ok(ty);
670                     }
671
672                     // Then try `field_tys` which contains all the fields, but it
673                     // requires the final optimized MIR.
674                     return match substs.field_tys(def_id, tcx).nth(field.index()) {
675                         Some(ty) => Ok(ty),
676                         None => Err(FieldAccessError::OutOfRange {
677                             field_count: substs.field_tys(def_id, tcx).count(),
678                         }),
679                     };
680                 }
681                 ty::Tuple(tys) => {
682                     return match tys.get(field.index()) {
683                         Some(&ty) => Ok(ty),
684                         None => Err(FieldAccessError::OutOfRange {
685                             field_count: tys.len(),
686                         }),
687                     }
688                 }
689                 _ => {
690                     return Ok(span_mirbug_and_err!(
691                         self,
692                         parent,
693                         "can't project out of {:?}",
694                         base_ty
695                     ))
696                 }
697             },
698         };
699
700         if let Some(field) = variant.fields.get(field.index()) {
701             Ok(self.cx.normalize(&field.ty(tcx, substs), location))
702         } else {
703             Err(FieldAccessError::OutOfRange {
704                 field_count: variant.fields.len(),
705             })
706         }
707     }
708 }
709
710 /// The MIR type checker. Visits the MIR and enforces all the
711 /// constraints needed for it to be valid and well-typed. Along the
712 /// way, it accrues region constraints -- these can later be used by
713 /// NLL region checking.
714 struct TypeChecker<'a, 'gcx: 'tcx, 'tcx: 'a> {
715     infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
716     param_env: ty::ParamEnv<'gcx>,
717     last_span: Span,
718     mir: &'a Mir<'tcx>,
719     mir_def_id: DefId,
720     region_bound_pairs: &'a RegionBoundPairs<'tcx>,
721     implicit_region_bound: Option<ty::Region<'tcx>>,
722     reported_errors: FxHashSet<(Ty<'tcx>, Span)>,
723     borrowck_context: Option<&'a mut BorrowCheckContext<'a, 'tcx>>,
724     universal_region_relations: Option<&'a UniversalRegionRelations<'tcx>>,
725 }
726
727 struct BorrowCheckContext<'a, 'tcx: 'a> {
728     universal_regions: &'a UniversalRegions<'tcx>,
729     location_table: &'a LocationTable,
730     all_facts: &'a mut Option<AllFacts>,
731     borrow_set: &'a BorrowSet<'tcx>,
732     constraints: &'a mut MirTypeckRegionConstraints<'tcx>,
733 }
734
735 crate struct MirTypeckResults<'tcx> {
736     crate constraints: MirTypeckRegionConstraints<'tcx>,
737     crate universal_region_relations: Rc<UniversalRegionRelations<'tcx>>,
738 }
739
740 /// A collection of region constraints that must be satisfied for the
741 /// program to be considered well-typed.
742 crate struct MirTypeckRegionConstraints<'tcx> {
743     /// Maps from a `ty::Placeholder` to the corresponding
744     /// `PlaceholderIndex` bit that we will use for it.
745     ///
746     /// To keep everything in sync, do not insert this set
747     /// directly. Instead, use the `placeholder_region` helper.
748     crate placeholder_indices: PlaceholderIndices,
749
750     /// Each time we add a placeholder to `placeholder_indices`, we
751     /// also create a corresponding "representative" region vid for
752     /// that wraps it. This vector tracks those. This way, when we
753     /// convert the same `ty::RePlaceholder(p)` twice, we can map to
754     /// the same underlying `RegionVid`.
755     crate placeholder_index_to_region: IndexVec<PlaceholderIndex, ty::Region<'tcx>>,
756
757     /// In general, the type-checker is not responsible for enforcing
758     /// liveness constraints; this job falls to the region inferencer,
759     /// which performs a liveness analysis. However, in some limited
760     /// cases, the MIR type-checker creates temporary regions that do
761     /// not otherwise appear in the MIR -- in particular, the
762     /// late-bound regions that it instantiates at call-sites -- and
763     /// hence it must report on their liveness constraints.
764     crate liveness_constraints: LivenessValues<RegionVid>,
765
766     crate outlives_constraints: ConstraintSet,
767
768     crate closure_bounds_mapping:
769         FxHashMap<Location, FxHashMap<(RegionVid, RegionVid), (ConstraintCategory, Span)>>,
770
771     crate type_tests: Vec<TypeTest<'tcx>>,
772 }
773
774 impl MirTypeckRegionConstraints<'tcx> {
775     fn placeholder_region(
776         &mut self,
777         infcx: &InferCtxt<'_, '_, 'tcx>,
778         placeholder: ty::Placeholder,
779     ) -> ty::Region<'tcx> {
780         let placeholder_index = self.placeholder_indices.insert(placeholder);
781         match self.placeholder_index_to_region.get(placeholder_index) {
782             Some(&v) => v,
783             None => {
784                 let origin = NLLRegionVariableOrigin::Placeholder(placeholder);
785                 let region = infcx.next_nll_region_var_in_universe(origin, placeholder.universe);
786                 self.placeholder_index_to_region.push(region);
787                 region
788             }
789         }
790     }
791 }
792
793 /// The `Locations` type summarizes *where* region constraints are
794 /// required to hold. Normally, this is at a particular point which
795 /// created the obligation, but for constraints that the user gave, we
796 /// want the constraint to hold at all points.
797 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
798 pub enum Locations {
799     /// Indicates that a type constraint should always be true. This
800     /// is particularly important in the new borrowck analysis for
801     /// things like the type of the return slot. Consider this
802     /// example:
803     ///
804     /// ```
805     /// fn foo<'a>(x: &'a u32) -> &'a u32 {
806     ///     let y = 22;
807     ///     return &y; // error
808     /// }
809     /// ```
810     ///
811     /// Here, we wind up with the signature from the return type being
812     /// something like `&'1 u32` where `'1` is a universal region. But
813     /// the type of the return slot `_0` is something like `&'2 u32`
814     /// where `'2` is an existential region variable. The type checker
815     /// requires that `&'2 u32 = &'1 u32` -- but at what point? In the
816     /// older NLL analysis, we required this only at the entry point
817     /// to the function. By the nature of the constraints, this wound
818     /// up propagating to all points reachable from start (because
819     /// `'1` -- as a universal region -- is live everywhere).  In the
820     /// newer analysis, though, this doesn't work: `_0` is considered
821     /// dead at the start (it has no usable value) and hence this type
822     /// equality is basically a no-op. Then, later on, when we do `_0
823     /// = &'3 y`, that region `'3` never winds up related to the
824     /// universal region `'1` and hence no error occurs. Therefore, we
825     /// use Locations::All instead, which ensures that the `'1` and
826     /// `'2` are equal everything. We also use this for other
827     /// user-given type annotations; e.g., if the user wrote `let mut
828     /// x: &'static u32 = ...`, we would ensure that all values
829     /// assigned to `x` are of `'static` lifetime.
830     ///
831     /// The span points to the place the constraint arose. For example,
832     /// it points to the type in a user-given type annotation. If
833     /// there's no sensible span then it's DUMMY_SP.
834     All(Span),
835
836     /// An outlives constraint that only has to hold at a single location,
837     /// usually it represents a point where references flow from one spot to
838     /// another (e.g., `x = y`)
839     Single(Location),
840 }
841
842 impl Locations {
843     pub fn from_location(&self) -> Option<Location> {
844         match self {
845             Locations::All(_) => None,
846             Locations::Single(from_location) => Some(*from_location),
847         }
848     }
849
850     /// Gets a span representing the location.
851     pub fn span(&self, mir: &Mir<'_>) -> Span {
852         match self {
853             Locations::All(span) => *span,
854             Locations::Single(l) => mir.source_info(*l).span,
855         }
856     }
857 }
858
859 impl<'a, 'gcx, 'tcx> TypeChecker<'a, 'gcx, 'tcx> {
860     fn new(
861         infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
862         mir: &'a Mir<'tcx>,
863         mir_def_id: DefId,
864         param_env: ty::ParamEnv<'gcx>,
865         region_bound_pairs: &'a RegionBoundPairs<'tcx>,
866         implicit_region_bound: Option<ty::Region<'tcx>>,
867         borrowck_context: Option<&'a mut BorrowCheckContext<'a, 'tcx>>,
868         universal_region_relations: Option<&'a UniversalRegionRelations<'tcx>>,
869     ) -> Self {
870         TypeChecker {
871             infcx,
872             last_span: DUMMY_SP,
873             mir,
874             mir_def_id,
875             param_env,
876             region_bound_pairs,
877             implicit_region_bound,
878             borrowck_context,
879             reported_errors: Default::default(),
880             universal_region_relations,
881         }
882     }
883
884     /// Given some operation `op` that manipulates types, proves
885     /// predicates, or otherwise uses the inference context, executes
886     /// `op` and then executes all the further obligations that `op`
887     /// returns. This will yield a set of outlives constraints amongst
888     /// regions which are extracted and stored as having occurred at
889     /// `locations`.
890     ///
891     /// **Any `rustc::infer` operations that might generate region
892     /// constraints should occur within this method so that those
893     /// constraints can be properly localized!**
894     fn fully_perform_op<R>(
895         &mut self,
896         locations: Locations,
897         category: ConstraintCategory,
898         op: impl type_op::TypeOp<'gcx, 'tcx, Output = R>,
899     ) -> Fallible<R> {
900         let (r, opt_data) = op.fully_perform(self.infcx)?;
901
902         if let Some(data) = &opt_data {
903             self.push_region_constraints(locations, category, data);
904         }
905
906         Ok(r)
907     }
908
909     fn push_region_constraints(
910         &mut self,
911         locations: Locations,
912         category: ConstraintCategory,
913         data: &[QueryRegionConstraint<'tcx>],
914     ) {
915         debug!(
916             "push_region_constraints: constraints generated at {:?} are {:#?}",
917             locations, data
918         );
919
920         if let Some(ref mut borrowck_context) = self.borrowck_context {
921             constraint_conversion::ConstraintConversion::new(
922                 self.infcx,
923                 borrowck_context.universal_regions,
924                 self.region_bound_pairs,
925                 self.implicit_region_bound,
926                 self.param_env,
927                 locations,
928                 category,
929                 &mut borrowck_context.constraints,
930             ).convert_all(&data);
931         }
932     }
933
934     /// Convenient wrapper around `relate_tys::relate_types` -- see
935     /// that fn for docs.
936     fn relate_types(
937         &mut self,
938         a: Ty<'tcx>,
939         v: ty::Variance,
940         b: Ty<'tcx>,
941         locations: Locations,
942         category: ConstraintCategory,
943     ) -> Fallible<()> {
944         relate_tys::relate_types(
945             self.infcx,
946             a,
947             v,
948             b,
949             locations,
950             category,
951             self.borrowck_context.as_mut().map(|x| &mut **x),
952         )
953     }
954
955     fn sub_types(
956         &mut self,
957         sub: Ty<'tcx>,
958         sup: Ty<'tcx>,
959         locations: Locations,
960         category: ConstraintCategory,
961     ) -> Fallible<()> {
962         self.relate_types(sub, ty::Variance::Covariant, sup, locations, category)
963     }
964
965     /// Try to relate `sub <: sup`; if this fails, instantiate opaque
966     /// variables in `sub` with their inferred definitions and try
967     /// again. This is used for opaque types in places (e.g., `let x:
968     /// impl Foo = ..`).
969     fn sub_types_or_anon(
970         &mut self,
971         sub: Ty<'tcx>,
972         sup: Ty<'tcx>,
973         locations: Locations,
974         category: ConstraintCategory,
975     ) -> Fallible<()> {
976         if let Err(terr) = self.sub_types(sub, sup, locations, category) {
977             if let TyKind::Opaque(..) = sup.sty {
978                 // When you have `let x: impl Foo = ...` in a closure,
979                 // the resulting inferend values are stored with the
980                 // def-id of the base function.
981                 let parent_def_id = self.tcx().closure_base_def_id(self.mir_def_id);
982                 return self.eq_opaque_type_and_type(sub, sup, parent_def_id, locations, category);
983             } else {
984                 return Err(terr);
985             }
986         }
987         Ok(())
988     }
989
990     fn eq_types(
991         &mut self,
992         a: Ty<'tcx>,
993         b: Ty<'tcx>,
994         locations: Locations,
995         category: ConstraintCategory,
996     ) -> Fallible<()> {
997         self.relate_types(a, ty::Variance::Invariant, b, locations, category)
998     }
999
1000     fn relate_type_and_user_type(
1001         &mut self,
1002         a: Ty<'tcx>,
1003         v: ty::Variance,
1004         user_ty: &UserTypeProjection<'tcx>,
1005         locations: Locations,
1006         category: ConstraintCategory,
1007     ) -> Fallible<()> {
1008         debug!(
1009             "relate_type_and_user_type(a={:?}, v={:?}, user_ty={:?}, locations={:?})",
1010             a, v, user_ty, locations,
1011         );
1012
1013         match user_ty.base {
1014             UserTypeAnnotation::Ty(canonical_ty) => {
1015                 let (ty, _) = self.infcx
1016                     .instantiate_canonical_with_fresh_inference_vars(DUMMY_SP, &canonical_ty);
1017
1018                 // The `TypeRelating` code assumes that "unresolved inference
1019                 // variables" appear in the "a" side, so flip `Contravariant`
1020                 // ambient variance to get the right relationship.
1021                 let v1 = ty::Contravariant.xform(v);
1022
1023                 let tcx = self.infcx.tcx;
1024                 let ty = self.normalize(ty, locations);
1025
1026                 // We need to follow any provided projetions into the type.
1027                 //
1028                 // if we hit a ty var as we descend, then just skip the
1029                 // attempt to relate the mir local with any type.
1030                 #[derive(Debug)] struct HitTyVar;
1031                 let mut curr_projected_ty: Result<PlaceTy, HitTyVar>;
1032
1033                 curr_projected_ty = Ok(PlaceTy::from_ty(ty));
1034                 for proj in &user_ty.projs {
1035                     let projected_ty = if let Ok(projected_ty) = curr_projected_ty {
1036                         projected_ty
1037                     } else {
1038                         break;
1039                     };
1040                     curr_projected_ty = projected_ty.projection_ty_core(
1041                         tcx, proj, |this, field, &()| {
1042                             if this.to_ty(tcx).is_ty_var() {
1043                                 Err(HitTyVar)
1044                             } else {
1045                                 let ty = this.field_ty(tcx, field);
1046                                 Ok(self.normalize(ty, locations))
1047                             }
1048                         });
1049                 }
1050                 debug!("user_ty base: {:?} freshened: {:?} projs: {:?} yields: {:?}",
1051                        user_ty.base, ty, user_ty.projs, curr_projected_ty);
1052
1053                 if let Ok(projected_ty) = curr_projected_ty {
1054                     let ty = projected_ty.to_ty(tcx);
1055                     self.relate_types(ty, v1, a, locations, category)?;
1056                 }
1057             }
1058             UserTypeAnnotation::TypeOf(def_id, canonical_substs) => {
1059                 let (
1060                     user_substs,
1061                     _,
1062                 ) = self.infcx
1063                     .instantiate_canonical_with_fresh_inference_vars(DUMMY_SP, &canonical_substs);
1064
1065                 let projs = self.infcx.tcx.intern_projs(&user_ty.projs);
1066                 self.fully_perform_op(
1067                     locations,
1068                     category,
1069                     self.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
1070                         a, v, def_id, user_substs, projs,
1071                     )),
1072                 )?;
1073             }
1074         }
1075
1076         Ok(())
1077     }
1078
1079     fn eq_opaque_type_and_type(
1080         &mut self,
1081         revealed_ty: Ty<'tcx>,
1082         anon_ty: Ty<'tcx>,
1083         anon_owner_def_id: DefId,
1084         locations: Locations,
1085         category: ConstraintCategory,
1086     ) -> Fallible<()> {
1087         debug!(
1088             "eq_opaque_type_and_type( \
1089              revealed_ty={:?}, \
1090              anon_ty={:?})",
1091             revealed_ty, anon_ty
1092         );
1093         let infcx = self.infcx;
1094         let tcx = infcx.tcx;
1095         let param_env = self.param_env;
1096         debug!("eq_opaque_type_and_type: mir_def_id={:?}", self.mir_def_id);
1097         let opaque_type_map = self.fully_perform_op(
1098             locations,
1099             category,
1100             CustomTypeOp::new(
1101                 |infcx| {
1102                     let mut obligations = ObligationAccumulator::default();
1103
1104                     let dummy_body_id = ObligationCause::dummy().body_id;
1105                     let (output_ty, opaque_type_map) =
1106                         obligations.add(infcx.instantiate_opaque_types(
1107                             anon_owner_def_id,
1108                             dummy_body_id,
1109                             param_env,
1110                             &anon_ty,
1111                         ));
1112                     debug!(
1113                         "eq_opaque_type_and_type: \
1114                          instantiated output_ty={:?} \
1115                          opaque_type_map={:#?} \
1116                          revealed_ty={:?}",
1117                         output_ty, opaque_type_map, revealed_ty
1118                     );
1119                     obligations.add(infcx
1120                         .at(&ObligationCause::dummy(), param_env)
1121                         .eq(output_ty, revealed_ty)?);
1122
1123                     for (&opaque_def_id, opaque_decl) in &opaque_type_map {
1124                         let opaque_defn_ty = tcx.type_of(opaque_def_id);
1125                         let opaque_defn_ty = opaque_defn_ty.subst(tcx, opaque_decl.substs);
1126                         let opaque_defn_ty = renumber::renumber_regions(infcx, &opaque_defn_ty);
1127                         debug!(
1128                             "eq_opaque_type_and_type: concrete_ty={:?}={:?} opaque_defn_ty={:?}",
1129                             opaque_decl.concrete_ty,
1130                             infcx.resolve_type_vars_if_possible(&opaque_decl.concrete_ty),
1131                             opaque_defn_ty
1132                         );
1133                         obligations.add(infcx
1134                             .at(&ObligationCause::dummy(), param_env)
1135                             .eq(opaque_decl.concrete_ty, opaque_defn_ty)?);
1136                     }
1137
1138                     debug!("eq_opaque_type_and_type: equated");
1139
1140                     Ok(InferOk {
1141                         value: Some(opaque_type_map),
1142                         obligations: obligations.into_vec(),
1143                     })
1144                 },
1145                 || "input_output".to_string(),
1146             ),
1147         )?;
1148
1149         let universal_region_relations = match self.universal_region_relations {
1150             Some(rel) => rel,
1151             None => return Ok(()),
1152         };
1153
1154         // Finally, if we instantiated the anon types successfully, we
1155         // have to solve any bounds (e.g., `-> impl Iterator` needs to
1156         // prove that `T: Iterator` where `T` is the type we
1157         // instantiated it with).
1158         if let Some(opaque_type_map) = opaque_type_map {
1159             for (opaque_def_id, opaque_decl) in opaque_type_map {
1160                 self.fully_perform_op(
1161                     locations,
1162                     ConstraintCategory::OpaqueType,
1163                     CustomTypeOp::new(
1164                         |_cx| {
1165                             infcx.constrain_opaque_type(
1166                                 opaque_def_id,
1167                                 &opaque_decl,
1168                                 universal_region_relations,
1169                             );
1170                             Ok(InferOk {
1171                                 value: (),
1172                                 obligations: vec![],
1173                             })
1174                         },
1175                         || "opaque_type_map".to_string(),
1176                     ),
1177                 )?;
1178             }
1179         }
1180         Ok(())
1181     }
1182
1183     fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
1184         self.infcx.tcx
1185     }
1186
1187     fn check_stmt(&mut self, mir: &Mir<'tcx>, stmt: &Statement<'tcx>, location: Location) {
1188         debug!("check_stmt: {:?}", stmt);
1189         let tcx = self.tcx();
1190         match stmt.kind {
1191             StatementKind::Assign(ref place, ref rv) => {
1192                 // Assignments to temporaries are not "interesting";
1193                 // they are not caused by the user, but rather artifacts
1194                 // of lowering. Assignments to other sorts of places *are* interesting
1195                 // though.
1196                 let category = match *place {
1197                     Place::Local(RETURN_PLACE) => if let Some(BorrowCheckContext {
1198                         universal_regions:
1199                             UniversalRegions {
1200                                 defining_ty: DefiningTy::Const(def_id, _),
1201                                 ..
1202                             },
1203                         ..
1204                     }) = self.borrowck_context
1205                     {
1206                         if tcx.is_static(*def_id).is_some() {
1207                             ConstraintCategory::UseAsStatic
1208                         } else {
1209                             ConstraintCategory::UseAsConst
1210                         }
1211                     } else {
1212                         ConstraintCategory::Return
1213                     },
1214                     Place::Local(l) if !mir.local_decls[l].is_user_variable.is_some() => {
1215                         ConstraintCategory::Boring
1216                     }
1217                     _ => ConstraintCategory::Assignment,
1218                 };
1219
1220                 let place_ty = place.ty(mir, tcx).to_ty(tcx);
1221                 let rv_ty = rv.ty(mir, tcx);
1222                 if let Err(terr) =
1223                     self.sub_types_or_anon(rv_ty, place_ty, location.to_locations(), category)
1224                 {
1225                     span_mirbug!(
1226                         self,
1227                         stmt,
1228                         "bad assignment ({:?} = {:?}): {:?}",
1229                         place_ty,
1230                         rv_ty,
1231                         terr
1232                     );
1233                 }
1234
1235                 if let Some(user_ty) = self.rvalue_user_ty(rv) {
1236                     if let Err(terr) = self.relate_type_and_user_type(
1237                         rv_ty,
1238                         ty::Variance::Invariant,
1239                         &UserTypeProjection { base: user_ty, projs: vec![], },
1240                         location.to_locations(),
1241                         ConstraintCategory::Boring,
1242                     ) {
1243                         span_mirbug!(
1244                             self,
1245                             stmt,
1246                             "bad user type on rvalue ({:?} = {:?}): {:?}",
1247                             user_ty,
1248                             rv_ty,
1249                             terr
1250                         );
1251                     }
1252                 }
1253
1254                 self.check_rvalue(mir, rv, location);
1255                 if !self.tcx().features().unsized_locals {
1256                     let trait_ref = ty::TraitRef {
1257                         def_id: tcx.lang_items().sized_trait().unwrap(),
1258                         substs: tcx.mk_substs_trait(place_ty, &[]),
1259                     };
1260                     self.prove_trait_ref(
1261                         trait_ref,
1262                         location.to_locations(),
1263                         ConstraintCategory::SizedBound,
1264                     );
1265                 }
1266             }
1267             StatementKind::SetDiscriminant {
1268                 ref place,
1269                 variant_index,
1270             } => {
1271                 let place_type = place.ty(mir, tcx).to_ty(tcx);
1272                 let adt = match place_type.sty {
1273                     TyKind::Adt(adt, _) if adt.is_enum() => adt,
1274                     _ => {
1275                         span_bug!(
1276                             stmt.source_info.span,
1277                             "bad set discriminant ({:?} = {:?}): lhs is not an enum",
1278                             place,
1279                             variant_index
1280                         );
1281                     }
1282                 };
1283                 if variant_index >= adt.variants.len() {
1284                     span_bug!(
1285                         stmt.source_info.span,
1286                         "bad set discriminant ({:?} = {:?}): value of of range",
1287                         place,
1288                         variant_index
1289                     );
1290                 };
1291             }
1292             StatementKind::AscribeUserType(ref place, variance, box ref c_ty) => {
1293                 let place_ty = place.ty(mir, tcx).to_ty(tcx);
1294                 if let Err(terr) = self.relate_type_and_user_type(
1295                     place_ty,
1296                     variance,
1297                     c_ty,
1298                     Locations::All(stmt.source_info.span),
1299                     ConstraintCategory::TypeAnnotation,
1300                 ) {
1301                     span_mirbug!(
1302                         self,
1303                         stmt,
1304                         "bad type assert ({:?} <: {:?}): {:?}",
1305                         place_ty,
1306                         c_ty,
1307                         terr
1308                     );
1309                 }
1310             }
1311             StatementKind::FakeRead(..)
1312             | StatementKind::StorageLive(_)
1313             | StatementKind::StorageDead(_)
1314             | StatementKind::InlineAsm { .. }
1315             | StatementKind::EndRegion(_)
1316             | StatementKind::Retag { .. }
1317             | StatementKind::Nop => {}
1318         }
1319     }
1320
1321     fn check_terminator(
1322         &mut self,
1323         mir: &Mir<'tcx>,
1324         term: &Terminator<'tcx>,
1325         term_location: Location,
1326     ) {
1327         debug!("check_terminator: {:?}", term);
1328         let tcx = self.tcx();
1329         match term.kind {
1330             TerminatorKind::Goto { .. }
1331             | TerminatorKind::Resume
1332             | TerminatorKind::Abort
1333             | TerminatorKind::Return
1334             | TerminatorKind::GeneratorDrop
1335             | TerminatorKind::Unreachable
1336             | TerminatorKind::Drop { .. }
1337             | TerminatorKind::FalseEdges { .. }
1338             | TerminatorKind::FalseUnwind { .. } => {
1339                 // no checks needed for these
1340             }
1341
1342             TerminatorKind::DropAndReplace {
1343                 ref location,
1344                 ref value,
1345                 target: _,
1346                 unwind: _,
1347             } => {
1348                 let place_ty = location.ty(mir, tcx).to_ty(tcx);
1349                 let rv_ty = value.ty(mir, tcx);
1350
1351                 let locations = term_location.to_locations();
1352                 if let Err(terr) =
1353                     self.sub_types(rv_ty, place_ty, locations, ConstraintCategory::Assignment)
1354                 {
1355                     span_mirbug!(
1356                         self,
1357                         term,
1358                         "bad DropAndReplace ({:?} = {:?}): {:?}",
1359                         place_ty,
1360                         rv_ty,
1361                         terr
1362                     );
1363                 }
1364             }
1365             TerminatorKind::SwitchInt {
1366                 ref discr,
1367                 switch_ty,
1368                 ..
1369             } => {
1370                 let discr_ty = discr.ty(mir, tcx);
1371                 if let Err(terr) = self.sub_types(
1372                     discr_ty,
1373                     switch_ty,
1374                     term_location.to_locations(),
1375                     ConstraintCategory::Assignment,
1376                 ) {
1377                     span_mirbug!(
1378                         self,
1379                         term,
1380                         "bad SwitchInt ({:?} on {:?}): {:?}",
1381                         switch_ty,
1382                         discr_ty,
1383                         terr
1384                     );
1385                 }
1386                 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
1387                     span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
1388                 }
1389                 // FIXME: check the values
1390             }
1391             TerminatorKind::Call {
1392                 ref func,
1393                 ref args,
1394                 ref destination,
1395                 from_hir_call,
1396                 ..
1397             } => {
1398                 let func_ty = func.ty(mir, tcx);
1399                 debug!("check_terminator: call, func_ty={:?}", func_ty);
1400                 let sig = match func_ty.sty {
1401                     ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx),
1402                     _ => {
1403                         span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1404                         return;
1405                     }
1406                 };
1407                 let (sig, map) = self.infcx.replace_late_bound_regions_with_fresh_var(
1408                     term.source_info.span,
1409                     LateBoundRegionConversionTime::FnCall,
1410                     &sig,
1411                 );
1412                 let sig = self.normalize(sig, term_location);
1413                 self.check_call_dest(mir, term, &sig, destination, term_location);
1414
1415                 self.prove_predicates(
1416                     sig.inputs().iter().map(|ty| ty::Predicate::WellFormed(ty)),
1417                     term_location.to_locations(),
1418                     ConstraintCategory::Boring,
1419                 );
1420
1421                 // The ordinary liveness rules will ensure that all
1422                 // regions in the type of the callee are live here. We
1423                 // then further constrain the late-bound regions that
1424                 // were instantiated at the call site to be live as
1425                 // well. The resulting is that all the input (and
1426                 // output) types in the signature must be live, since
1427                 // all the inputs that fed into it were live.
1428                 for &late_bound_region in map.values() {
1429                     if let Some(ref mut borrowck_context) = self.borrowck_context {
1430                         let region_vid = borrowck_context
1431                             .universal_regions
1432                             .to_region_vid(late_bound_region);
1433                         borrowck_context
1434                             .constraints
1435                             .liveness_constraints
1436                             .add_element(region_vid, term_location);
1437                     }
1438                 }
1439
1440                 self.check_call_inputs(mir, term, &sig, args, term_location, from_hir_call);
1441             }
1442             TerminatorKind::Assert {
1443                 ref cond, ref msg, ..
1444             } => {
1445                 let cond_ty = cond.ty(mir, tcx);
1446                 if cond_ty != tcx.types.bool {
1447                     span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1448                 }
1449
1450                 if let BoundsCheck { ref len, ref index } = *msg {
1451                     if len.ty(mir, tcx) != tcx.types.usize {
1452                         span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1453                     }
1454                     if index.ty(mir, tcx) != tcx.types.usize {
1455                         span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1456                     }
1457                 }
1458             }
1459             TerminatorKind::Yield { ref value, .. } => {
1460                 let value_ty = value.ty(mir, tcx);
1461                 match mir.yield_ty {
1462                     None => span_mirbug!(self, term, "yield in non-generator"),
1463                     Some(ty) => {
1464                         if let Err(terr) = self.sub_types(
1465                             value_ty,
1466                             ty,
1467                             term_location.to_locations(),
1468                             ConstraintCategory::Return,
1469                         ) {
1470                             span_mirbug!(
1471                                 self,
1472                                 term,
1473                                 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1474                                 value_ty,
1475                                 ty,
1476                                 terr
1477                             );
1478                         }
1479                     }
1480                 }
1481             }
1482         }
1483     }
1484
1485     fn check_call_dest(
1486         &mut self,
1487         mir: &Mir<'tcx>,
1488         term: &Terminator<'tcx>,
1489         sig: &ty::FnSig<'tcx>,
1490         destination: &Option<(Place<'tcx>, BasicBlock)>,
1491         term_location: Location,
1492     ) {
1493         let tcx = self.tcx();
1494         match *destination {
1495             Some((ref dest, _target_block)) => {
1496                 let dest_ty = dest.ty(mir, tcx).to_ty(tcx);
1497                 let category = match *dest {
1498                     Place::Local(RETURN_PLACE) => {
1499                         if let Some(BorrowCheckContext {
1500                             universal_regions:
1501                                 UniversalRegions {
1502                                     defining_ty: DefiningTy::Const(def_id, _),
1503                                     ..
1504                                 },
1505                             ..
1506                         }) = self.borrowck_context
1507                         {
1508                             if tcx.is_static(*def_id).is_some() {
1509                                 ConstraintCategory::UseAsStatic
1510                             } else {
1511                                 ConstraintCategory::UseAsConst
1512                             }
1513                         } else {
1514                             ConstraintCategory::Return
1515                         }
1516                     }
1517                     Place::Local(l) if !mir.local_decls[l].is_user_variable.is_some() => {
1518                         ConstraintCategory::Boring
1519                     }
1520                     _ => ConstraintCategory::Assignment,
1521                 };
1522
1523                 let locations = term_location.to_locations();
1524
1525                 if let Err(terr) =
1526                     self.sub_types_or_anon(sig.output(), dest_ty, locations, category)
1527                 {
1528                     span_mirbug!(
1529                         self,
1530                         term,
1531                         "call dest mismatch ({:?} <- {:?}): {:?}",
1532                         dest_ty,
1533                         sig.output(),
1534                         terr
1535                     );
1536                 }
1537
1538                 // When `#![feature(unsized_locals)]` is not enabled,
1539                 // this check is done at `check_local`.
1540                 if self.tcx().features().unsized_locals {
1541                     let span = term.source_info.span;
1542                     self.ensure_place_sized(dest_ty, span);
1543                 }
1544             }
1545             None => {
1546                 // FIXME(canndrew): This is_never should probably be an is_uninhabited
1547                 if !sig.output().is_never() {
1548                     span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1549                 }
1550             }
1551         }
1552     }
1553
1554     fn check_call_inputs(
1555         &mut self,
1556         mir: &Mir<'tcx>,
1557         term: &Terminator<'tcx>,
1558         sig: &ty::FnSig<'tcx>,
1559         args: &[Operand<'tcx>],
1560         term_location: Location,
1561         from_hir_call: bool,
1562     ) {
1563         debug!("check_call_inputs({:?}, {:?})", sig, args);
1564         if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.variadic) {
1565             span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1566         }
1567         for (n, (fn_arg, op_arg)) in sig.inputs().iter().zip(args).enumerate() {
1568             let op_arg_ty = op_arg.ty(mir, self.tcx());
1569             let category = if from_hir_call {
1570                 ConstraintCategory::CallArgument
1571             } else {
1572                 ConstraintCategory::Boring
1573             };
1574             if let Err(terr) =
1575                 self.sub_types(op_arg_ty, fn_arg, term_location.to_locations(), category)
1576             {
1577                 span_mirbug!(
1578                     self,
1579                     term,
1580                     "bad arg #{:?} ({:?} <- {:?}): {:?}",
1581                     n,
1582                     fn_arg,
1583                     op_arg_ty,
1584                     terr
1585                 );
1586             }
1587         }
1588     }
1589
1590     fn check_iscleanup(&mut self, mir: &Mir<'tcx>, block_data: &BasicBlockData<'tcx>) {
1591         let is_cleanup = block_data.is_cleanup;
1592         self.last_span = block_data.terminator().source_info.span;
1593         match block_data.terminator().kind {
1594             TerminatorKind::Goto { target } => {
1595                 self.assert_iscleanup(mir, block_data, target, is_cleanup)
1596             }
1597             TerminatorKind::SwitchInt { ref targets, .. } => for target in targets {
1598                 self.assert_iscleanup(mir, block_data, *target, is_cleanup);
1599             },
1600             TerminatorKind::Resume => if !is_cleanup {
1601                 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1602             },
1603             TerminatorKind::Abort => if !is_cleanup {
1604                 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1605             },
1606             TerminatorKind::Return => if is_cleanup {
1607                 span_mirbug!(self, block_data, "return on cleanup block")
1608             },
1609             TerminatorKind::GeneratorDrop { .. } => if is_cleanup {
1610                 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1611             },
1612             TerminatorKind::Yield { resume, drop, .. } => {
1613                 if is_cleanup {
1614                     span_mirbug!(self, block_data, "yield in cleanup block")
1615                 }
1616                 self.assert_iscleanup(mir, block_data, resume, is_cleanup);
1617                 if let Some(drop) = drop {
1618                     self.assert_iscleanup(mir, block_data, drop, is_cleanup);
1619                 }
1620             }
1621             TerminatorKind::Unreachable => {}
1622             TerminatorKind::Drop { target, unwind, .. }
1623             | TerminatorKind::DropAndReplace { target, unwind, .. }
1624             | TerminatorKind::Assert {
1625                 target,
1626                 cleanup: unwind,
1627                 ..
1628             } => {
1629                 self.assert_iscleanup(mir, block_data, target, is_cleanup);
1630                 if let Some(unwind) = unwind {
1631                     if is_cleanup {
1632                         span_mirbug!(self, block_data, "unwind on cleanup block")
1633                     }
1634                     self.assert_iscleanup(mir, block_data, unwind, true);
1635                 }
1636             }
1637             TerminatorKind::Call {
1638                 ref destination,
1639                 cleanup,
1640                 ..
1641             } => {
1642                 if let &Some((_, target)) = destination {
1643                     self.assert_iscleanup(mir, block_data, target, is_cleanup);
1644                 }
1645                 if let Some(cleanup) = cleanup {
1646                     if is_cleanup {
1647                         span_mirbug!(self, block_data, "cleanup on cleanup block")
1648                     }
1649                     self.assert_iscleanup(mir, block_data, cleanup, true);
1650                 }
1651             }
1652             TerminatorKind::FalseEdges {
1653                 real_target,
1654                 ref imaginary_targets,
1655             } => {
1656                 self.assert_iscleanup(mir, block_data, real_target, is_cleanup);
1657                 for target in imaginary_targets {
1658                     self.assert_iscleanup(mir, block_data, *target, is_cleanup);
1659                 }
1660             }
1661             TerminatorKind::FalseUnwind {
1662                 real_target,
1663                 unwind,
1664             } => {
1665                 self.assert_iscleanup(mir, block_data, real_target, is_cleanup);
1666                 if let Some(unwind) = unwind {
1667                     if is_cleanup {
1668                         span_mirbug!(
1669                             self,
1670                             block_data,
1671                             "cleanup in cleanup block via false unwind"
1672                         );
1673                     }
1674                     self.assert_iscleanup(mir, block_data, unwind, true);
1675                 }
1676             }
1677         }
1678     }
1679
1680     fn assert_iscleanup(
1681         &mut self,
1682         mir: &Mir<'tcx>,
1683         ctxt: &dyn fmt::Debug,
1684         bb: BasicBlock,
1685         iscleanuppad: bool,
1686     ) {
1687         if mir[bb].is_cleanup != iscleanuppad {
1688             span_mirbug!(
1689                 self,
1690                 ctxt,
1691                 "cleanuppad mismatch: {:?} should be {:?}",
1692                 bb,
1693                 iscleanuppad
1694             );
1695         }
1696     }
1697
1698     fn check_local(&mut self, mir: &Mir<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) {
1699         match mir.local_kind(local) {
1700             LocalKind::ReturnPointer | LocalKind::Arg => {
1701                 // return values of normal functions are required to be
1702                 // sized by typeck, but return values of ADT constructors are
1703                 // not because we don't include a `Self: Sized` bounds on them.
1704                 //
1705                 // Unbound parts of arguments were never required to be Sized
1706                 // - maybe we should make that a warning.
1707                 return;
1708             }
1709             LocalKind::Var | LocalKind::Temp => {}
1710         }
1711
1712         // When `#![feature(unsized_locals)]` is enabled, only function calls
1713         // and nullary ops are checked in `check_call_dest`.
1714         if !self.tcx().features().unsized_locals {
1715             let span = local_decl.source_info.span;
1716             let ty = local_decl.ty;
1717             self.ensure_place_sized(ty, span);
1718         }
1719     }
1720
1721     fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
1722         let tcx = self.tcx();
1723
1724         // Erase the regions from `ty` to get a global type.  The
1725         // `Sized` bound in no way depends on precise regions, so this
1726         // shouldn't affect `is_sized`.
1727         let gcx = tcx.global_tcx();
1728         let erased_ty = gcx.lift(&tcx.erase_regions(&ty)).unwrap();
1729         if !erased_ty.is_sized(gcx.at(span), self.param_env) {
1730             // in current MIR construction, all non-control-flow rvalue
1731             // expressions evaluate through `as_temp` or `into` a return
1732             // slot or local, so to find all unsized rvalues it is enough
1733             // to check all temps, return slots and locals.
1734             if let None = self.reported_errors.replace((ty, span)) {
1735                 let mut diag = struct_span_err!(
1736                     self.tcx().sess,
1737                     span,
1738                     E0161,
1739                     "cannot move a value of type {0}: the size of {0} \
1740                      cannot be statically determined",
1741                     ty
1742                 );
1743
1744                 // While this is located in `nll::typeck` this error is not
1745                 // an NLL error, it's a required check to prevent creation
1746                 // of unsized rvalues in certain cases:
1747                 // * operand of a box expression
1748                 // * callee in a call expression
1749                 diag.emit();
1750             }
1751         }
1752     }
1753
1754     fn aggregate_field_ty(
1755         &mut self,
1756         ak: &AggregateKind<'tcx>,
1757         field_index: usize,
1758         location: Location,
1759     ) -> Result<Ty<'tcx>, FieldAccessError> {
1760         let tcx = self.tcx();
1761
1762         match *ak {
1763             AggregateKind::Adt(def, variant_index, substs, _, active_field_index) => {
1764                 let variant = &def.variants[variant_index];
1765                 let adj_field_index = active_field_index.unwrap_or(field_index);
1766                 if let Some(field) = variant.fields.get(adj_field_index) {
1767                     Ok(self.normalize(field.ty(tcx, substs), location))
1768                 } else {
1769                     Err(FieldAccessError::OutOfRange {
1770                         field_count: variant.fields.len(),
1771                     })
1772                 }
1773             }
1774             AggregateKind::Closure(def_id, substs) => {
1775                 match substs.upvar_tys(def_id, tcx).nth(field_index) {
1776                     Some(ty) => Ok(ty),
1777                     None => Err(FieldAccessError::OutOfRange {
1778                         field_count: substs.upvar_tys(def_id, tcx).count(),
1779                     }),
1780                 }
1781             }
1782             AggregateKind::Generator(def_id, substs, _) => {
1783                 // Try pre-transform fields first (upvars and current state)
1784                 if let Some(ty) = substs.pre_transforms_tys(def_id, tcx).nth(field_index) {
1785                     Ok(ty)
1786                 } else {
1787                     // Then try `field_tys` which contains all the fields, but it
1788                     // requires the final optimized MIR.
1789                     match substs.field_tys(def_id, tcx).nth(field_index) {
1790                         Some(ty) => Ok(ty),
1791                         None => Err(FieldAccessError::OutOfRange {
1792                             field_count: substs.field_tys(def_id, tcx).count(),
1793                         }),
1794                     }
1795                 }
1796             }
1797             AggregateKind::Array(ty) => Ok(ty),
1798             AggregateKind::Tuple => {
1799                 unreachable!("This should have been covered in check_rvalues");
1800             }
1801         }
1802     }
1803
1804     fn check_rvalue(&mut self, mir: &Mir<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
1805         let tcx = self.tcx();
1806
1807         match rvalue {
1808             Rvalue::Aggregate(ak, ops) => {
1809                 self.check_aggregate_rvalue(mir, rvalue, ak, ops, location)
1810             }
1811
1812             Rvalue::Repeat(operand, len) => if *len > 1 {
1813                 let operand_ty = operand.ty(mir, tcx);
1814
1815                 let trait_ref = ty::TraitRef {
1816                     def_id: tcx.lang_items().copy_trait().unwrap(),
1817                     substs: tcx.mk_substs_trait(operand_ty, &[]),
1818                 };
1819
1820                 self.prove_trait_ref(
1821                     trait_ref,
1822                     location.to_locations(),
1823                     ConstraintCategory::CopyBound,
1824                 );
1825             },
1826
1827             Rvalue::NullaryOp(_, ty) => {
1828                 // Even with unsized locals cannot box an unsized value.
1829                 if self.tcx().features().unsized_locals {
1830                     let span = mir.source_info(location).span;
1831                     self.ensure_place_sized(ty, span);
1832                 }
1833
1834                 let trait_ref = ty::TraitRef {
1835                     def_id: tcx.lang_items().sized_trait().unwrap(),
1836                     substs: tcx.mk_substs_trait(ty, &[]),
1837                 };
1838
1839                 self.prove_trait_ref(
1840                     trait_ref,
1841                     location.to_locations(),
1842                     ConstraintCategory::SizedBound,
1843                 );
1844             }
1845
1846             Rvalue::Cast(cast_kind, op, ty) => {
1847                 match cast_kind {
1848                     CastKind::ReifyFnPointer => {
1849                         let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
1850
1851                         // The type that we see in the fcx is like
1852                         // `foo::<'a, 'b>`, where `foo` is the path to a
1853                         // function definition. When we extract the
1854                         // signature, it comes from the `fn_sig` query,
1855                         // and hence may contain unnormalized results.
1856                         let fn_sig = self.normalize(fn_sig, location);
1857
1858                         let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
1859
1860                         if let Err(terr) = self.eq_types(
1861                             ty_fn_ptr_from,
1862                             ty,
1863                             location.to_locations(),
1864                             ConstraintCategory::Cast,
1865                         ) {
1866                             span_mirbug!(
1867                                 self,
1868                                 rvalue,
1869                                 "equating {:?} with {:?} yields {:?}",
1870                                 ty_fn_ptr_from,
1871                                 ty,
1872                                 terr
1873                             );
1874                         }
1875                     }
1876
1877                     CastKind::ClosureFnPointer => {
1878                         let sig = match op.ty(mir, tcx).sty {
1879                             ty::Closure(def_id, substs) => {
1880                                 substs.closure_sig_ty(def_id, tcx).fn_sig(tcx)
1881                             }
1882                             _ => bug!(),
1883                         };
1884                         let ty_fn_ptr_from = tcx.coerce_closure_fn_ty(sig);
1885
1886                         if let Err(terr) = self.eq_types(
1887                             ty_fn_ptr_from,
1888                             ty,
1889                             location.to_locations(),
1890                             ConstraintCategory::Cast,
1891                         ) {
1892                             span_mirbug!(
1893                                 self,
1894                                 rvalue,
1895                                 "equating {:?} with {:?} yields {:?}",
1896                                 ty_fn_ptr_from,
1897                                 ty,
1898                                 terr
1899                             );
1900                         }
1901                     }
1902
1903                     CastKind::UnsafeFnPointer => {
1904                         let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
1905
1906                         // The type that we see in the fcx is like
1907                         // `foo::<'a, 'b>`, where `foo` is the path to a
1908                         // function definition. When we extract the
1909                         // signature, it comes from the `fn_sig` query,
1910                         // and hence may contain unnormalized results.
1911                         let fn_sig = self.normalize(fn_sig, location);
1912
1913                         let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
1914
1915                         if let Err(terr) = self.eq_types(
1916                             ty_fn_ptr_from,
1917                             ty,
1918                             location.to_locations(),
1919                             ConstraintCategory::Cast,
1920                         ) {
1921                             span_mirbug!(
1922                                 self,
1923                                 rvalue,
1924                                 "equating {:?} with {:?} yields {:?}",
1925                                 ty_fn_ptr_from,
1926                                 ty,
1927                                 terr
1928                             );
1929                         }
1930                     }
1931
1932                     CastKind::Unsize => {
1933                         let &ty = ty;
1934                         let trait_ref = ty::TraitRef {
1935                             def_id: tcx.lang_items().coerce_unsized_trait().unwrap(),
1936                             substs: tcx.mk_substs_trait(op.ty(mir, tcx), &[ty.into()]),
1937                         };
1938
1939                         self.prove_trait_ref(
1940                             trait_ref,
1941                             location.to_locations(),
1942                             ConstraintCategory::Cast,
1943                         );
1944                     }
1945
1946                     CastKind::Misc => {}
1947                 }
1948             }
1949
1950             Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
1951                 self.add_reborrow_constraint(location, region, borrowed_place);
1952             }
1953
1954             // FIXME: These other cases have to be implemented in future PRs
1955             Rvalue::Use(..)
1956             | Rvalue::Len(..)
1957             | Rvalue::BinaryOp(..)
1958             | Rvalue::CheckedBinaryOp(..)
1959             | Rvalue::UnaryOp(..)
1960             | Rvalue::Discriminant(..) => {}
1961         }
1962     }
1963
1964     /// If this rvalue supports a user-given type annotation, then
1965     /// extract and return it. This represents the final type of the
1966     /// rvalue and will be unified with the inferred type.
1967     fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotation<'tcx>> {
1968         match rvalue {
1969             Rvalue::Use(_)
1970             | Rvalue::Repeat(..)
1971             | Rvalue::Ref(..)
1972             | Rvalue::Len(..)
1973             | Rvalue::Cast(..)
1974             | Rvalue::BinaryOp(..)
1975             | Rvalue::CheckedBinaryOp(..)
1976             | Rvalue::NullaryOp(..)
1977             | Rvalue::UnaryOp(..)
1978             | Rvalue::Discriminant(..) => None,
1979
1980             Rvalue::Aggregate(aggregate, _) => match **aggregate {
1981                 AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
1982                 AggregateKind::Array(_) => None,
1983                 AggregateKind::Tuple => None,
1984                 AggregateKind::Closure(_, _) => None,
1985                 AggregateKind::Generator(_, _, _) => None,
1986             },
1987         }
1988     }
1989
1990     fn check_aggregate_rvalue(
1991         &mut self,
1992         mir: &Mir<'tcx>,
1993         rvalue: &Rvalue<'tcx>,
1994         aggregate_kind: &AggregateKind<'tcx>,
1995         operands: &[Operand<'tcx>],
1996         location: Location,
1997     ) {
1998         let tcx = self.tcx();
1999
2000         self.prove_aggregate_predicates(aggregate_kind, location);
2001
2002         if *aggregate_kind == AggregateKind::Tuple {
2003             // tuple rvalue field type is always the type of the op. Nothing to check here.
2004             return;
2005         }
2006
2007         for (i, operand) in operands.iter().enumerate() {
2008             let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
2009                 Ok(field_ty) => field_ty,
2010                 Err(FieldAccessError::OutOfRange { field_count }) => {
2011                     span_mirbug!(
2012                         self,
2013                         rvalue,
2014                         "accessed field #{} but variant only has {}",
2015                         i,
2016                         field_count
2017                     );
2018                     continue;
2019                 }
2020             };
2021             let operand_ty = operand.ty(mir, tcx);
2022
2023             if let Err(terr) = self.sub_types(
2024                 operand_ty,
2025                 field_ty,
2026                 location.to_locations(),
2027                 ConstraintCategory::Boring,
2028             ) {
2029                 span_mirbug!(
2030                     self,
2031                     rvalue,
2032                     "{:?} is not a subtype of {:?}: {:?}",
2033                     operand_ty,
2034                     field_ty,
2035                     terr
2036                 );
2037             }
2038         }
2039     }
2040
2041     /// Add the constraints that arise from a borrow expression `&'a P` at the location `L`.
2042     ///
2043     /// # Parameters
2044     ///
2045     /// - `location`: the location `L` where the borrow expression occurs
2046     /// - `borrow_region`: the region `'a` associated with the borrow
2047     /// - `borrowed_place`: the place `P` being borrowed
2048     fn add_reborrow_constraint(
2049         &mut self,
2050         location: Location,
2051         borrow_region: ty::Region<'tcx>,
2052         borrowed_place: &Place<'tcx>,
2053     ) {
2054         // These constraints are only meaningful during borrowck:
2055         let BorrowCheckContext {
2056             borrow_set,
2057             location_table,
2058             all_facts,
2059             constraints,
2060             ..
2061         } = match self.borrowck_context {
2062             Some(ref mut borrowck_context) => borrowck_context,
2063             None => return,
2064         };
2065
2066         // In Polonius mode, we also push a `borrow_region` fact
2067         // linking the loan to the region (in some cases, though,
2068         // there is no loan associated with this borrow expression --
2069         // that occurs when we are borrowing an unsafe place, for
2070         // example).
2071         if let Some(all_facts) = all_facts {
2072             if let Some(borrow_index) = borrow_set.location_map.get(&location) {
2073                 let region_vid = borrow_region.to_region_vid();
2074                 all_facts.borrow_region.push((
2075                     region_vid,
2076                     *borrow_index,
2077                     location_table.mid_index(location),
2078                 ));
2079             }
2080         }
2081
2082         // If we are reborrowing the referent of another reference, we
2083         // need to add outlives relationships. In a case like `&mut
2084         // *p`, where the `p` has type `&'b mut Foo`, for example, we
2085         // need to ensure that `'b: 'a`.
2086
2087         let mut borrowed_place = borrowed_place;
2088
2089         debug!(
2090             "add_reborrow_constraint({:?}, {:?}, {:?})",
2091             location, borrow_region, borrowed_place
2092         );
2093         while let Place::Projection(box PlaceProjection { base, elem }) = borrowed_place {
2094             debug!("add_reborrow_constraint - iteration {:?}", borrowed_place);
2095
2096             match *elem {
2097                 ProjectionElem::Deref => {
2098                     let tcx = self.infcx.tcx;
2099                     let base_ty = base.ty(self.mir, tcx).to_ty(tcx);
2100
2101                     debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
2102                     match base_ty.sty {
2103                         ty::Ref(ref_region, _, mutbl) => {
2104                             constraints.outlives_constraints.push(OutlivesConstraint {
2105                                 sup: ref_region.to_region_vid(),
2106                                 sub: borrow_region.to_region_vid(),
2107                                 locations: location.to_locations(),
2108                                 category: ConstraintCategory::Boring,
2109                             });
2110
2111                             match mutbl {
2112                                 hir::Mutability::MutImmutable => {
2113                                     // Immutable reference. We don't need the base
2114                                     // to be valid for the entire lifetime of
2115                                     // the borrow.
2116                                     break;
2117                                 }
2118                                 hir::Mutability::MutMutable => {
2119                                     // Mutable reference. We *do* need the base
2120                                     // to be valid, because after the base becomes
2121                                     // invalid, someone else can use our mutable deref.
2122
2123                                     // This is in order to make the following function
2124                                     // illegal:
2125                                     // ```
2126                                     // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
2127                                     //     &mut *x
2128                                     // }
2129                                     // ```
2130                                     //
2131                                     // As otherwise you could clone `&mut T` using the
2132                                     // following function:
2133                                     // ```
2134                                     // fn bad(x: &mut T) -> (&mut T, &mut T) {
2135                                     //     let my_clone = unsafe_deref(&'a x);
2136                                     //     ENDREGION 'a;
2137                                     //     (my_clone, x)
2138                                     // }
2139                                     // ```
2140                                 }
2141                             }
2142                         }
2143                         ty::RawPtr(..) => {
2144                             // deref of raw pointer, guaranteed to be valid
2145                             break;
2146                         }
2147                         ty::Adt(def, _) if def.is_box() => {
2148                             // deref of `Box`, need the base to be valid - propagate
2149                         }
2150                         _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2151                     }
2152                 }
2153                 ProjectionElem::Field(..)
2154                 | ProjectionElem::Downcast(..)
2155                 | ProjectionElem::Index(..)
2156                 | ProjectionElem::ConstantIndex { .. }
2157                 | ProjectionElem::Subslice { .. } => {
2158                     // other field access
2159                 }
2160             }
2161
2162             // The "propagate" case. We need to check that our base is valid
2163             // for the borrow's lifetime.
2164             borrowed_place = base;
2165         }
2166     }
2167
2168     fn prove_aggregate_predicates(
2169         &mut self,
2170         aggregate_kind: &AggregateKind<'tcx>,
2171         location: Location,
2172     ) {
2173         let tcx = self.tcx();
2174
2175         debug!(
2176             "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2177             aggregate_kind, location
2178         );
2179
2180         let instantiated_predicates = match aggregate_kind {
2181             AggregateKind::Adt(def, _, substs, _, _) => {
2182                 tcx.predicates_of(def.did).instantiate(tcx, substs)
2183             }
2184
2185             // For closures, we have some **extra requirements** we
2186             //
2187             // have to check. In particular, in their upvars and
2188             // signatures, closures often reference various regions
2189             // from the surrounding function -- we call those the
2190             // closure's free regions. When we borrow-check (and hence
2191             // region-check) closures, we may find that the closure
2192             // requires certain relationships between those free
2193             // regions. However, because those free regions refer to
2194             // portions of the CFG of their caller, the closure is not
2195             // in a position to verify those relationships. In that
2196             // case, the requirements get "propagated" to us, and so
2197             // we have to solve them here where we instantiate the
2198             // closure.
2199             //
2200             // Despite the opacity of the previous parapgrah, this is
2201             // actually relatively easy to understand in terms of the
2202             // desugaring. A closure gets desugared to a struct, and
2203             // these extra requirements are basically like where
2204             // clauses on the struct.
2205             AggregateKind::Closure(def_id, ty::ClosureSubsts { substs })
2206             | AggregateKind::Generator(def_id, ty::GeneratorSubsts { substs }, _) => {
2207                 self.prove_closure_bounds(tcx, *def_id, substs, location)
2208             }
2209
2210             AggregateKind::Array(_) | AggregateKind::Tuple => ty::InstantiatedPredicates::empty(),
2211         };
2212
2213         self.normalize_and_prove_instantiated_predicates(
2214             instantiated_predicates,
2215             location.to_locations(),
2216         );
2217     }
2218
2219     fn prove_closure_bounds(
2220         &mut self,
2221         tcx: TyCtxt<'a, 'gcx, 'tcx>,
2222         def_id: DefId,
2223         substs: &'tcx Substs<'tcx>,
2224         location: Location,
2225     ) -> ty::InstantiatedPredicates<'tcx> {
2226         if let Some(closure_region_requirements) = tcx.mir_borrowck(def_id).closure_requirements {
2227             let closure_constraints =
2228                 closure_region_requirements.apply_requirements(tcx, location, def_id, substs);
2229
2230             if let Some(ref mut borrowck_context) = self.borrowck_context {
2231                 let bounds_mapping = closure_constraints
2232                     .iter()
2233                     .enumerate()
2234                     .filter_map(|(idx, constraint)| {
2235                         let ty::OutlivesPredicate(k1, r2) =
2236                             constraint.no_bound_vars().unwrap_or_else(|| {
2237                                 bug!("query_constraint {:?} contained bound vars", constraint,);
2238                             });
2239
2240                         match k1.unpack() {
2241                             UnpackedKind::Lifetime(r1) => {
2242                                 // constraint is r1: r2
2243                                 let r1_vid = borrowck_context.universal_regions.to_region_vid(r1);
2244                                 let r2_vid = borrowck_context.universal_regions.to_region_vid(r2);
2245                                 let outlives_requirements =
2246                                     &closure_region_requirements.outlives_requirements[idx];
2247                                 Some((
2248                                     (r1_vid, r2_vid),
2249                                     (
2250                                         outlives_requirements.category,
2251                                         outlives_requirements.blame_span,
2252                                     ),
2253                                 ))
2254                             }
2255                             UnpackedKind::Type(_) => None,
2256                         }
2257                     })
2258                     .collect();
2259
2260                 let existing = borrowck_context
2261                     .constraints
2262                     .closure_bounds_mapping
2263                     .insert(location, bounds_mapping);
2264                 assert!(
2265                     existing.is_none(),
2266                     "Multiple closures at the same location."
2267                 );
2268             }
2269
2270             self.push_region_constraints(
2271                 location.to_locations(),
2272                 ConstraintCategory::ClosureBounds,
2273                 &closure_constraints,
2274             );
2275         }
2276
2277         tcx.predicates_of(def_id).instantiate(tcx, substs)
2278     }
2279
2280     fn prove_trait_ref(
2281         &mut self,
2282         trait_ref: ty::TraitRef<'tcx>,
2283         locations: Locations,
2284         category: ConstraintCategory,
2285     ) {
2286         self.prove_predicates(
2287             Some(ty::Predicate::Trait(
2288                 trait_ref.to_poly_trait_ref().to_poly_trait_predicate(),
2289             )),
2290             locations,
2291             category,
2292         );
2293     }
2294
2295     fn normalize_and_prove_instantiated_predicates(
2296         &mut self,
2297         instantiated_predicates: ty::InstantiatedPredicates<'tcx>,
2298         locations: Locations,
2299     ) {
2300         for predicate in instantiated_predicates.predicates {
2301             let predicate = self.normalize(predicate, locations);
2302             self.prove_predicate(predicate, locations, ConstraintCategory::Boring);
2303         }
2304     }
2305
2306     fn prove_predicates(
2307         &mut self,
2308         predicates: impl IntoIterator<Item = ty::Predicate<'tcx>>,
2309         locations: Locations,
2310         category: ConstraintCategory,
2311     ) {
2312         for predicate in predicates {
2313             debug!(
2314                 "prove_predicates(predicate={:?}, locations={:?})",
2315                 predicate, locations,
2316             );
2317
2318             self.prove_predicate(predicate, locations, category);
2319         }
2320     }
2321
2322     fn prove_predicate(
2323         &mut self,
2324         predicate: ty::Predicate<'tcx>,
2325         locations: Locations,
2326         category: ConstraintCategory,
2327     ) {
2328         debug!(
2329             "prove_predicate(predicate={:?}, location={:?})",
2330             predicate, locations,
2331         );
2332
2333         let param_env = self.param_env;
2334         self.fully_perform_op(
2335             locations,
2336             category,
2337             param_env.and(type_op::prove_predicate::ProvePredicate::new(predicate)),
2338         ).unwrap_or_else(|NoSolution| {
2339             span_mirbug!(self, NoSolution, "could not prove {:?}", predicate);
2340         })
2341     }
2342
2343     fn typeck_mir(&mut self, mir: &Mir<'tcx>) {
2344         self.last_span = mir.span;
2345         debug!("run_on_mir: {:?}", mir.span);
2346
2347         for (local, local_decl) in mir.local_decls.iter_enumerated() {
2348             self.check_local(mir, local, local_decl);
2349         }
2350
2351         for (block, block_data) in mir.basic_blocks().iter_enumerated() {
2352             let mut location = Location {
2353                 block,
2354                 statement_index: 0,
2355             };
2356             for stmt in &block_data.statements {
2357                 if !stmt.source_info.span.is_dummy() {
2358                     self.last_span = stmt.source_info.span;
2359                 }
2360                 self.check_stmt(mir, stmt, location);
2361                 location.statement_index += 1;
2362             }
2363
2364             self.check_terminator(mir, block_data.terminator(), location);
2365             self.check_iscleanup(mir, block_data);
2366         }
2367     }
2368
2369     fn normalize<T>(&mut self, value: T, location: impl NormalizeLocation) -> T
2370     where
2371         T: type_op::normalize::Normalizable<'gcx, 'tcx> + Copy,
2372     {
2373         debug!("normalize(value={:?}, location={:?})", value, location);
2374         let param_env = self.param_env;
2375         self.fully_perform_op(
2376             location.to_locations(),
2377             ConstraintCategory::Boring,
2378             param_env.and(type_op::normalize::Normalize::new(value)),
2379         ).unwrap_or_else(|NoSolution| {
2380             span_mirbug!(self, NoSolution, "failed to normalize `{:?}`", value);
2381             value
2382         })
2383     }
2384 }
2385
2386 pub struct TypeckMir;
2387
2388 impl MirPass for TypeckMir {
2389     fn run_pass<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, src: MirSource, mir: &mut Mir<'tcx>) {
2390         let def_id = src.def_id;
2391         debug!("run_pass: {:?}", def_id);
2392
2393         // When NLL is enabled, the borrow checker runs the typeck
2394         // itself, so we don't need this MIR pass anymore.
2395         if tcx.use_mir_borrowck() {
2396             return;
2397         }
2398
2399         if tcx.sess.err_count() > 0 {
2400             // compiling a broken program can obviously result in a
2401             // broken MIR, so try not to report duplicate errors.
2402             return;
2403         }
2404
2405         if tcx.is_struct_constructor(def_id) {
2406             // We just assume that the automatically generated struct constructors are
2407             // correct. See the comment in the `mir_borrowck` implementation for an
2408             // explanation why we need this.
2409             return;
2410         }
2411
2412         let param_env = tcx.param_env(def_id);
2413         tcx.infer_ctxt().enter(|infcx| {
2414             type_check_internal(
2415                 &infcx,
2416                 def_id,
2417                 param_env,
2418                 mir,
2419                 &vec![],
2420                 None,
2421                 None,
2422                 None,
2423                 |_| (),
2424             );
2425
2426             // For verification purposes, we just ignore the resulting
2427             // region constraint sets. Not our problem. =)
2428         });
2429     }
2430 }
2431
2432 trait NormalizeLocation: fmt::Debug + Copy {
2433     fn to_locations(self) -> Locations;
2434 }
2435
2436 impl NormalizeLocation for Locations {
2437     fn to_locations(self) -> Locations {
2438         self
2439     }
2440 }
2441
2442 impl NormalizeLocation for Location {
2443     fn to_locations(self) -> Locations {
2444         Locations::Single(self)
2445     }
2446 }
2447
2448 #[derive(Debug, Default)]
2449 struct ObligationAccumulator<'tcx> {
2450     obligations: PredicateObligations<'tcx>,
2451 }
2452
2453 impl<'tcx> ObligationAccumulator<'tcx> {
2454     fn add<T>(&mut self, value: InferOk<'tcx, T>) -> T {
2455         let InferOk { value, obligations } = value;
2456         self.obligations.extend(obligations);
2457         value
2458     }
2459
2460     fn into_vec(self) -> PredicateObligations<'tcx> {
2461         self.obligations
2462     }
2463 }