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