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