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