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