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