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