1 #![deny(rustc::untranslatable_diagnostic)]
2 #![deny(rustc::diagnostic_outside_of_impl)]
3 //! This pass type-checks the MIR to ensure it is not broken.
6 use std::{fmt, iter, mem};
10 use hir::OpaqueTyOrigin;
11 use rustc_data_structures::frozen::Frozen;
12 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
13 use rustc_data_structures::vec_map::VecMap;
15 use rustc_hir::def::DefKind;
16 use rustc_hir::def_id::LocalDefId;
17 use rustc_hir::lang_items::LangItem;
18 use rustc_index::vec::{Idx, IndexVec};
19 use rustc_infer::infer::canonical::QueryRegionConstraints;
20 use rustc_infer::infer::outlives::env::RegionBoundPairs;
21 use rustc_infer::infer::region_constraints::RegionConstraintData;
22 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
23 use rustc_infer::infer::{
24 InferCtxt, InferOk, LateBoundRegion, LateBoundRegionConversionTime, NllRegionVariableOrigin,
26 use rustc_middle::mir::tcx::PlaceTy;
27 use rustc_middle::mir::visit::{NonMutatingUseContext, PlaceContext, Visitor};
28 use rustc_middle::mir::AssertKind;
29 use rustc_middle::mir::*;
30 use rustc_middle::ty::adjustment::PointerCast;
31 use rustc_middle::ty::cast::CastTy;
32 use rustc_middle::ty::subst::{SubstsRef, UserSubsts};
33 use rustc_middle::ty::visit::TypeVisitable;
34 use rustc_middle::ty::{
35 self, Binder, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, Dynamic,
36 OpaqueHiddenType, OpaqueTypeKey, RegionVid, Ty, TyCtxt, UserType, UserTypeAnnotationIndex,
38 use rustc_span::def_id::CRATE_DEF_ID;
39 use rustc_span::{Span, DUMMY_SP};
40 use rustc_target::abi::VariantIdx;
41 use rustc_trait_selection::traits::query::type_op;
42 use rustc_trait_selection::traits::query::type_op::custom::scrape_region_constraints;
43 use rustc_trait_selection::traits::query::type_op::custom::CustomTypeOp;
44 use rustc_trait_selection::traits::query::type_op::{TypeOp, TypeOpOutput};
45 use rustc_trait_selection::traits::query::Fallible;
46 use rustc_trait_selection::traits::PredicateObligation;
48 use rustc_mir_dataflow::impls::MaybeInitializedPlaces;
49 use rustc_mir_dataflow::move_paths::MoveData;
50 use rustc_mir_dataflow::ResultsCursor;
52 use crate::session_diagnostics::MoveUnsized;
54 borrow_set::BorrowSet,
55 constraints::{OutlivesConstraint, OutlivesConstraintSet},
56 diagnostics::UniverseInfo,
58 location::LocationTable,
59 member_constraints::MemberConstraintSet,
62 region_infer::values::{
63 LivenessValues, PlaceholderIndex, PlaceholderIndices, RegionValueElements,
65 region_infer::TypeTest,
66 type_check::free_region_relations::{CreateResult, UniversalRegionRelations},
67 universal_regions::{DefiningTy, UniversalRegions},
71 macro_rules! span_mirbug {
72 ($context:expr, $elem:expr, $($message:tt)*) => ({
73 $crate::type_check::mirbug(
77 "broken MIR in {:?} ({:?}): {}",
78 $context.body().source.def_id(),
80 format_args!($($message)*),
86 macro_rules! span_mirbug_and_err {
87 ($context:expr, $elem:expr, $($message:tt)*) => ({
89 span_mirbug!($context, $elem, $($message)*);
96 mod constraint_conversion;
97 pub mod free_region_relations;
99 pub(crate) mod liveness;
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
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.
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>,
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>],
140 ) -> MirTypeckResults<'tcx> {
141 let implicit_region_bound = infcx.tcx.mk_region(ty::ReVar(universal_regions.fr_fn_body));
142 let mut constraints = MirTypeckRegionConstraints {
143 placeholder_indices: PlaceholderIndices::default(),
144 placeholder_index_to_region: IndexVec::default(),
145 liveness_constraints: LivenessValues::new(elements.clone()),
146 outlives_constraints: OutlivesConstraintSet::default(),
147 member_constraints: MemberConstraintSet::default(),
148 type_tests: Vec::default(),
149 universe_causes: FxHashMap::default(),
153 universal_region_relations,
155 normalized_inputs_and_output,
156 } = free_region_relations::create(
159 implicit_region_bound,
164 debug!(?normalized_inputs_and_output);
166 for u in ty::UniverseIndex::ROOT..=infcx.universe() {
167 constraints.universe_causes.insert(u, UniverseInfo::other());
170 let mut borrowck_context = BorrowCheckContext {
175 constraints: &mut constraints,
179 let mut checker = TypeChecker::new(
184 implicit_region_bound,
185 &mut borrowck_context,
188 let errors_reported = {
189 let mut verifier = TypeVerifier::new(&mut checker, promoted);
190 verifier.visit_body(&body);
191 verifier.errors_reported
194 if !errors_reported {
195 // if verifier failed, don't do further checks to avoid ICEs
196 checker.typeck_mir(body);
199 checker.equate_inputs_and_outputs(&body, universal_regions, &normalized_inputs_and_output);
210 translate_outlives_facts(&mut checker);
211 let opaque_type_values = infcx.inner.borrow_mut().opaque_type_storage.take_opaque_types();
213 let opaque_type_values = opaque_type_values
215 .map(|(opaque_type_key, decl)| {
218 Locations::All(body.span),
219 ConstraintCategory::OpaqueType,
222 infcx.register_member_constraints(
226 decl.hidden_type.span,
228 Ok(InferOk { value: (), obligations: vec![] })
230 || "opaque_type_map".to_string(),
234 let mut hidden_type = infcx.resolve_vars_if_possible(decl.hidden_type);
235 trace!("finalized opaque type {:?} to {:#?}", opaque_type_key, hidden_type.ty.kind());
236 if hidden_type.has_non_region_infer() {
237 let reported = infcx.tcx.sess.delay_span_bug(
238 decl.hidden_type.span,
239 &format!("could not resolve {:#?}", hidden_type.ty.kind()),
241 hidden_type.ty = infcx.tcx.ty_error_with_guaranteed(reported);
244 (opaque_type_key, (hidden_type, decl.origin))
248 MirTypeckResults { constraints, universal_region_relations, opaque_type_values }
251 fn translate_outlives_facts(typeck: &mut TypeChecker<'_, '_>) {
252 let cx = &mut typeck.borrowck_context;
253 if let Some(facts) = cx.all_facts {
254 let _prof_timer = typeck.infcx.tcx.prof.generic_activity("polonius_fact_generation");
255 let location_table = cx.location_table;
256 facts.subset_base.extend(cx.constraints.outlives_constraints.outlives().iter().flat_map(
257 |constraint: &OutlivesConstraint<'_>| {
258 if let Some(from_location) = constraint.locations.from_location() {
259 Either::Left(iter::once((
262 location_table.mid_index(from_location),
268 .map(move |location| (constraint.sup, constraint.sub, location)),
277 fn mirbug(tcx: TyCtxt<'_>, span: Span, msg: &str) {
278 // We sometimes see MIR failures (notably predicate failures) due to
279 // the fact that we check rvalue sized predicates here. So use `delay_span_bug`
280 // to avoid reporting bugs in those cases.
281 tcx.sess.diagnostic().delay_span_bug(span, msg);
284 enum FieldAccessError {
285 OutOfRange { field_count: usize },
288 /// Verifies that MIR types are sane to not crash further checks.
290 /// The sanitize_XYZ methods here take an MIR object and compute its
291 /// type, calling `span_mirbug` and returning an error type if there
293 struct TypeVerifier<'a, 'b, 'tcx> {
294 cx: &'a mut TypeChecker<'b, 'tcx>,
295 promoted: &'b IndexVec<Promoted, Body<'tcx>>,
297 errors_reported: bool,
300 impl<'a, 'b, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'tcx> {
301 fn visit_span(&mut self, span: Span) {
302 if !span.is_dummy() {
303 self.last_span = span;
307 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
308 self.sanitize_place(place, location, context);
311 fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
312 debug!(?constant, ?location, "visit_constant");
314 self.super_constant(constant, location);
315 let ty = self.sanitize_type(constant, constant.literal.ty());
317 self.cx.infcx.tcx.for_each_free_region(&ty, |live_region| {
318 let live_region_vid =
319 self.cx.borrowck_context.universal_regions.to_region_vid(live_region);
323 .liveness_constraints
324 .add_element(live_region_vid, location);
327 // HACK(compiler-errors): Constants that are gathered into Body.required_consts
328 // have their locations erased...
329 let locations = if location != Location::START {
330 location.to_locations()
332 Locations::All(constant.span)
335 if let Some(annotation_index) = constant.user_ty {
336 if let Err(terr) = self.cx.relate_type_and_user_type(
337 constant.literal.ty(),
338 ty::Variance::Invariant,
339 &UserTypeProjection { base: annotation_index, projs: vec![] },
341 ConstraintCategory::Boring,
343 let annotation = &self.cx.user_type_annotations[annotation_index];
347 "bad constant user type {:?} vs {:?}: {:?}",
349 constant.literal.ty(),
354 let tcx = self.tcx();
355 let maybe_uneval = match constant.literal {
356 ConstantKind::Ty(ct) => match ct.kind() {
357 ty::ConstKind::Unevaluated(_) => {
358 bug!("should not encounter unevaluated ConstantKind::Ty here, got {:?}", ct)
362 ConstantKind::Unevaluated(uv, _) => Some(uv),
366 if let Some(uv) = maybe_uneval {
367 if let Some(promoted) = uv.promoted {
368 let check_err = |verifier: &mut TypeVerifier<'a, 'b, 'tcx>,
369 promoted: &Body<'tcx>,
373 verifier.cx.eq_types(ty, san_ty, locations, ConstraintCategory::Boring)
378 "bad promoted type ({:?}: {:?}): {:?}",
386 if !self.errors_reported {
387 let promoted_body = &self.promoted[promoted];
388 self.sanitize_promoted(promoted_body, location);
390 let promoted_ty = promoted_body.return_ty();
391 check_err(self, promoted_body, ty, promoted_ty);
394 if let Err(terr) = self.cx.fully_perform_op(
396 ConstraintCategory::Boring,
397 self.cx.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
398 constant.literal.ty(),
400 UserSubsts { substs: uv.substs, user_self_ty: None },
406 "bad constant type {:?} ({:?})",
412 } else if let Some(static_def_id) = constant.check_static_ptr(tcx) {
413 let unnormalized_ty = tcx.type_of(static_def_id);
414 let normalized_ty = self.cx.normalize(unnormalized_ty, locations);
415 let literal_ty = constant.literal.ty().builtin_deref(true).unwrap().ty;
417 if let Err(terr) = self.cx.eq_types(
421 ConstraintCategory::Boring,
423 span_mirbug!(self, constant, "bad static type {:?} ({:?})", constant, terr);
427 if let ty::FnDef(def_id, substs) = *constant.literal.ty().kind() {
428 // const_trait_impl: use a non-const param env when checking that a FnDef type is well formed.
429 // this is because the well-formedness of the function does not need to be proved to have `const`
430 // impls for trait bounds.
431 let instantiated_predicates = tcx.predicates_of(def_id).instantiate(tcx, substs);
432 let prev = self.cx.param_env;
433 self.cx.param_env = prev.without_const();
434 self.cx.normalize_and_prove_instantiated_predicates(
436 instantiated_predicates,
439 self.cx.param_env = prev;
444 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
445 self.super_rvalue(rvalue, location);
446 let rval_ty = rvalue.ty(self.body(), self.tcx());
447 self.sanitize_type(rvalue, rval_ty);
450 fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) {
451 self.super_local_decl(local, local_decl);
452 self.sanitize_type(local_decl, local_decl.ty);
454 if let Some(user_ty) = &local_decl.user_ty {
455 for (user_ty, span) in user_ty.projections_and_spans() {
456 let ty = if !local_decl.is_nonref_binding() {
457 // If we have a binding of the form `let ref x: T = ..`
458 // then remove the outermost reference so we can check the
459 // type annotation for the remaining type.
460 if let ty::Ref(_, rty, _) = local_decl.ty.kind() {
463 bug!("{:?} with ref binding has wrong type {}", local, local_decl.ty);
469 if let Err(terr) = self.cx.relate_type_and_user_type(
471 ty::Variance::Invariant,
473 Locations::All(*span),
474 ConstraintCategory::TypeAnnotation,
479 "bad user type on variable {:?}: {:?} != {:?} ({:?})",
490 fn visit_body(&mut self, body: &Body<'tcx>) {
491 self.sanitize_type(&"return type", body.return_ty());
492 for local_decl in &body.local_decls {
493 self.sanitize_type(local_decl, local_decl.ty);
495 if self.errors_reported {
498 self.super_body(body);
502 impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> {
504 cx: &'a mut TypeChecker<'b, 'tcx>,
505 promoted: &'b IndexVec<Promoted, Body<'tcx>>,
507 TypeVerifier { promoted, last_span: cx.body.span, cx, errors_reported: false }
510 fn body(&self) -> &Body<'tcx> {
514 fn tcx(&self) -> TyCtxt<'tcx> {
518 fn sanitize_type(&mut self, parent: &dyn fmt::Debug, ty: Ty<'tcx>) -> Ty<'tcx> {
519 if ty.has_escaping_bound_vars() || ty.references_error() {
520 span_mirbug_and_err!(self, parent, "bad type {:?}", ty)
526 /// Checks that the types internal to the `place` match up with
527 /// what would be expected.
532 context: PlaceContext,
534 debug!("sanitize_place: {:?}", place);
536 let mut place_ty = PlaceTy::from_ty(self.body().local_decls[place.local].ty);
538 for elem in place.projection.iter() {
539 if place_ty.variant_index.is_none() {
540 if place_ty.ty.references_error() {
541 assert!(self.errors_reported);
542 return PlaceTy::from_ty(self.tcx().ty_error());
545 place_ty = self.sanitize_projection(place_ty, elem, place, location);
548 if let PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) = context {
549 let tcx = self.tcx();
550 let trait_ref = tcx.at(self.last_span).mk_trait_ref(LangItem::Copy, [place_ty.ty]);
552 // To have a `Copy` operand, the type `T` of the
553 // value must be `Copy`. Note that we prove that `T: Copy`,
554 // rather than using the `is_copy_modulo_regions`
555 // test. This is important because
556 // `is_copy_modulo_regions` ignores the resulting region
557 // obligations and assumes they pass. This can result in
558 // bounds from `Copy` impls being unsoundly ignored (e.g.,
559 // #29149). Note that we decide to use `Copy` before knowing
560 // whether the bounds fully apply: in effect, the rule is
561 // that if a value of some type could implement `Copy`, then
563 self.cx.prove_trait_ref(
565 location.to_locations(),
566 ConstraintCategory::CopyBound,
573 fn sanitize_promoted(&mut self, promoted_body: &'b Body<'tcx>, location: Location) {
574 // Determine the constraints from the promoted MIR by running the type
575 // checker on the promoted MIR, then transfer the constraints back to
576 // the main MIR, changing the locations to the provided location.
578 let parent_body = mem::replace(&mut self.cx.body, promoted_body);
580 // Use new sets of constraints and closure bounds so that we can
581 // modify their locations.
582 let all_facts = &mut None;
583 let mut constraints = Default::default();
584 let mut liveness_constraints =
585 LivenessValues::new(Rc::new(RegionValueElements::new(&promoted_body)));
586 // Don't try to add borrow_region facts for the promoted MIR
588 let mut swap_constraints = |this: &mut Self| {
589 mem::swap(this.cx.borrowck_context.all_facts, all_facts);
591 &mut this.cx.borrowck_context.constraints.outlives_constraints,
595 &mut this.cx.borrowck_context.constraints.liveness_constraints,
596 &mut liveness_constraints,
600 swap_constraints(self);
602 self.visit_body(&promoted_body);
604 if !self.errors_reported {
605 // if verifier failed, don't do further checks to avoid ICEs
606 self.cx.typeck_mir(promoted_body);
609 self.cx.body = parent_body;
610 // Merge the outlives constraints back in, at the given location.
611 swap_constraints(self);
613 let locations = location.to_locations();
614 for constraint in constraints.outlives().iter() {
615 let mut constraint = *constraint;
616 constraint.locations = locations;
617 if let ConstraintCategory::Return(_)
618 | ConstraintCategory::UseAsConst
619 | ConstraintCategory::UseAsStatic = constraint.category
621 // "Returning" from a promoted is an assignment to a
622 // temporary from the user's point of view.
623 constraint.category = ConstraintCategory::Boring;
625 self.cx.borrowck_context.constraints.outlives_constraints.push(constraint)
627 for region in liveness_constraints.rows() {
628 // If the region is live at at least one location in the promoted MIR,
629 // then add a liveness constraint to the main MIR for this region
630 // at the location provided as an argument to this method
631 if liveness_constraints.get_elements(region).next().is_some() {
635 .liveness_constraints
636 .add_element(region, location);
641 fn sanitize_projection(
648 debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, place);
649 let tcx = self.tcx();
650 let base_ty = base.ty;
652 ProjectionElem::Deref => {
653 let deref_ty = base_ty.builtin_deref(true);
654 PlaceTy::from_ty(deref_ty.map(|t| t.ty).unwrap_or_else(|| {
655 span_mirbug_and_err!(self, place, "deref of non-pointer {:?}", base_ty)
658 ProjectionElem::Index(i) => {
659 let index_ty = Place::from(i).ty(self.body(), tcx).ty;
660 if index_ty != tcx.types.usize {
661 PlaceTy::from_ty(span_mirbug_and_err!(self, i, "index by non-usize {:?}", i))
663 PlaceTy::from_ty(base_ty.builtin_index().unwrap_or_else(|| {
664 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
668 ProjectionElem::ConstantIndex { .. } => {
669 // consider verifying in-bounds
670 PlaceTy::from_ty(base_ty.builtin_index().unwrap_or_else(|| {
671 span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
674 ProjectionElem::Subslice { from, to, from_end } => {
675 PlaceTy::from_ty(match base_ty.kind() {
676 ty::Array(inner, _) => {
677 assert!(!from_end, "array subslices should not use from_end");
678 tcx.mk_array(*inner, to - from)
681 assert!(from_end, "slice subslices should use from_end");
684 _ => span_mirbug_and_err!(self, place, "slice of non-array {:?}", base_ty),
687 ProjectionElem::Downcast(maybe_name, index) => match base_ty.kind() {
688 ty::Adt(adt_def, _substs) if adt_def.is_enum() => {
689 if index.as_usize() >= adt_def.variants().len() {
690 PlaceTy::from_ty(span_mirbug_and_err!(
693 "cast to variant #{:?} but enum only has {:?}",
695 adt_def.variants().len()
698 PlaceTy { ty: base_ty, variant_index: Some(index) }
701 // We do not need to handle generators here, because this runs
702 // before the generator transform stage.
704 let ty = if let Some(name) = maybe_name {
705 span_mirbug_and_err!(
708 "can't downcast {:?} as {:?}",
713 span_mirbug_and_err!(self, place, "can't downcast {:?}", base_ty)
718 ProjectionElem::Field(field, fty) => {
719 let fty = self.sanitize_type(place, fty);
720 let fty = self.cx.normalize(fty, location);
721 match self.field_ty(place, base, field, location) {
723 let ty = self.cx.normalize(ty, location);
724 if let Err(terr) = self.cx.eq_types(
727 location.to_locations(),
728 ConstraintCategory::Boring,
733 "bad field access ({:?}: {:?}): {:?}",
740 Err(FieldAccessError::OutOfRange { field_count }) => span_mirbug!(
743 "accessed field #{} but variant only has {}",
748 PlaceTy::from_ty(fty)
750 ProjectionElem::OpaqueCast(ty) => {
751 let ty = self.sanitize_type(place, ty);
752 let ty = self.cx.normalize(ty, location);
757 location.to_locations(),
758 ConstraintCategory::TypeAnnotation,
766 fn error(&mut self) -> Ty<'tcx> {
767 self.errors_reported = true;
768 self.tcx().ty_error()
773 parent: &dyn fmt::Debug,
774 base_ty: PlaceTy<'tcx>,
777 ) -> Result<Ty<'tcx>, FieldAccessError> {
778 let tcx = self.tcx();
780 let (variant, substs) = match base_ty {
781 PlaceTy { ty, variant_index: Some(variant_index) } => match *ty.kind() {
782 ty::Adt(adt_def, substs) => (adt_def.variant(variant_index), substs),
783 ty::Generator(def_id, substs, _) => {
784 let mut variants = substs.as_generator().state_tys(def_id, tcx);
785 let Some(mut variant) = variants.nth(variant_index.into()) else {
787 "variant_index of generator out of range: {:?}/{:?}",
789 substs.as_generator().state_tys(def_id, tcx).count()
792 return match variant.nth(field.index()) {
794 None => Err(FieldAccessError::OutOfRange { field_count: variant.count() }),
797 _ => bug!("can't have downcast of non-adt non-generator type"),
799 PlaceTy { ty, variant_index: None } => match *ty.kind() {
800 ty::Adt(adt_def, substs) if !adt_def.is_enum() => {
801 (adt_def.variant(VariantIdx::new(0)), substs)
803 ty::Closure(_, substs) => {
811 None => Err(FieldAccessError::OutOfRange {
812 field_count: substs.as_closure().upvar_tys().count(),
816 ty::Generator(_, substs, _) => {
817 // Only prefix fields (upvars and current state) are
818 // accessible without a variant index.
819 return match substs.as_generator().prefix_tys().nth(field.index()) {
821 None => Err(FieldAccessError::OutOfRange {
822 field_count: substs.as_generator().prefix_tys().count(),
827 return match tys.get(field.index()) {
829 None => Err(FieldAccessError::OutOfRange { field_count: tys.len() }),
833 return Ok(span_mirbug_and_err!(
836 "can't project out of {:?}",
843 if let Some(field) = variant.fields.get(field.index()) {
844 Ok(self.cx.normalize(field.ty(tcx, substs), location))
846 Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
851 /// The MIR type checker. Visits the MIR and enforces all the
852 /// constraints needed for it to be valid and well-typed. Along the
853 /// way, it accrues region constraints -- these can later be used by
854 /// NLL region checking.
855 struct TypeChecker<'a, 'tcx> {
856 infcx: &'a InferCtxt<'tcx>,
857 param_env: ty::ParamEnv<'tcx>,
859 body: &'a Body<'tcx>,
860 /// User type annotations are shared between the main MIR and the MIR of
861 /// all of the promoted items.
862 user_type_annotations: &'a CanonicalUserTypeAnnotations<'tcx>,
863 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
864 implicit_region_bound: ty::Region<'tcx>,
865 reported_errors: FxHashSet<(Ty<'tcx>, Span)>,
866 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
869 struct BorrowCheckContext<'a, 'tcx> {
870 pub(crate) universal_regions: &'a UniversalRegions<'tcx>,
871 location_table: &'a LocationTable,
872 all_facts: &'a mut Option<AllFacts>,
873 borrow_set: &'a BorrowSet<'tcx>,
874 pub(crate) constraints: &'a mut MirTypeckRegionConstraints<'tcx>,
875 upvars: &'a [Upvar<'tcx>],
878 pub(crate) struct MirTypeckResults<'tcx> {
879 pub(crate) constraints: MirTypeckRegionConstraints<'tcx>,
880 pub(crate) universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,
881 pub(crate) opaque_type_values:
882 VecMap<OpaqueTypeKey<'tcx>, (OpaqueHiddenType<'tcx>, OpaqueTyOrigin)>,
885 /// A collection of region constraints that must be satisfied for the
886 /// program to be considered well-typed.
887 pub(crate) struct MirTypeckRegionConstraints<'tcx> {
888 /// Maps from a `ty::Placeholder` to the corresponding
889 /// `PlaceholderIndex` bit that we will use for it.
891 /// To keep everything in sync, do not insert this set
892 /// directly. Instead, use the `placeholder_region` helper.
893 pub(crate) placeholder_indices: PlaceholderIndices,
895 /// Each time we add a placeholder to `placeholder_indices`, we
896 /// also create a corresponding "representative" region vid for
897 /// that wraps it. This vector tracks those. This way, when we
898 /// convert the same `ty::RePlaceholder(p)` twice, we can map to
899 /// the same underlying `RegionVid`.
900 pub(crate) placeholder_index_to_region: IndexVec<PlaceholderIndex, ty::Region<'tcx>>,
902 /// In general, the type-checker is not responsible for enforcing
903 /// liveness constraints; this job falls to the region inferencer,
904 /// which performs a liveness analysis. However, in some limited
905 /// cases, the MIR type-checker creates temporary regions that do
906 /// not otherwise appear in the MIR -- in particular, the
907 /// late-bound regions that it instantiates at call-sites -- and
908 /// hence it must report on their liveness constraints.
909 pub(crate) liveness_constraints: LivenessValues<RegionVid>,
911 pub(crate) outlives_constraints: OutlivesConstraintSet<'tcx>,
913 pub(crate) member_constraints: MemberConstraintSet<'tcx, RegionVid>,
915 pub(crate) universe_causes: FxHashMap<ty::UniverseIndex, UniverseInfo<'tcx>>,
917 pub(crate) type_tests: Vec<TypeTest<'tcx>>,
920 impl<'tcx> MirTypeckRegionConstraints<'tcx> {
921 fn placeholder_region(
923 infcx: &InferCtxt<'tcx>,
924 placeholder: ty::PlaceholderRegion,
925 ) -> ty::Region<'tcx> {
926 let placeholder_index = self.placeholder_indices.insert(placeholder);
927 match self.placeholder_index_to_region.get(placeholder_index) {
930 let origin = NllRegionVariableOrigin::Placeholder(placeholder);
931 let region = infcx.next_nll_region_var_in_universe(origin, placeholder.universe);
932 self.placeholder_index_to_region.push(region);
939 /// The `Locations` type summarizes *where* region constraints are
940 /// required to hold. Normally, this is at a particular point which
941 /// created the obligation, but for constraints that the user gave, we
942 /// want the constraint to hold at all points.
943 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
945 /// Indicates that a type constraint should always be true. This
946 /// is particularly important in the new borrowck analysis for
947 /// things like the type of the return slot. Consider this
950 /// ```compile_fail,E0515
951 /// fn foo<'a>(x: &'a u32) -> &'a u32 {
953 /// return &y; // error
957 /// Here, we wind up with the signature from the return type being
958 /// something like `&'1 u32` where `'1` is a universal region. But
959 /// the type of the return slot `_0` is something like `&'2 u32`
960 /// where `'2` is an existential region variable. The type checker
961 /// requires that `&'2 u32 = &'1 u32` -- but at what point? In the
962 /// older NLL analysis, we required this only at the entry point
963 /// to the function. By the nature of the constraints, this wound
964 /// up propagating to all points reachable from start (because
965 /// `'1` -- as a universal region -- is live everywhere). In the
966 /// newer analysis, though, this doesn't work: `_0` is considered
967 /// dead at the start (it has no usable value) and hence this type
968 /// equality is basically a no-op. Then, later on, when we do `_0
969 /// = &'3 y`, that region `'3` never winds up related to the
970 /// universal region `'1` and hence no error occurs. Therefore, we
971 /// use Locations::All instead, which ensures that the `'1` and
972 /// `'2` are equal everything. We also use this for other
973 /// user-given type annotations; e.g., if the user wrote `let mut
974 /// x: &'static u32 = ...`, we would ensure that all values
975 /// assigned to `x` are of `'static` lifetime.
977 /// The span points to the place the constraint arose. For example,
978 /// it points to the type in a user-given type annotation. If
979 /// there's no sensible span then it's DUMMY_SP.
982 /// An outlives constraint that only has to hold at a single location,
983 /// usually it represents a point where references flow from one spot to
984 /// another (e.g., `x = y`)
989 pub fn from_location(&self) -> Option<Location> {
991 Locations::All(_) => None,
992 Locations::Single(from_location) => Some(*from_location),
996 /// Gets a span representing the location.
997 pub fn span(&self, body: &Body<'_>) -> Span {
999 Locations::All(span) => *span,
1000 Locations::Single(l) => body.source_info(*l).span,
1005 impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
1007 infcx: &'a InferCtxt<'tcx>,
1008 body: &'a Body<'tcx>,
1009 param_env: ty::ParamEnv<'tcx>,
1010 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
1011 implicit_region_bound: ty::Region<'tcx>,
1012 borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>,
1014 let mut checker = Self {
1016 last_span: DUMMY_SP,
1018 user_type_annotations: &body.user_type_annotations,
1021 implicit_region_bound,
1023 reported_errors: Default::default(),
1025 checker.check_user_type_annotations();
1029 fn body(&self) -> &Body<'tcx> {
1033 fn unsized_feature_enabled(&self) -> bool {
1034 let features = self.tcx().features();
1035 features.unsized_locals || features.unsized_fn_params
1038 /// Equate the inferred type and the annotated type for user type annotations
1039 #[instrument(skip(self), level = "debug")]
1040 fn check_user_type_annotations(&mut self) {
1041 debug!(?self.user_type_annotations);
1042 for user_annotation in self.user_type_annotations {
1043 let CanonicalUserTypeAnnotation { span, ref user_ty, inferred_ty } = *user_annotation;
1044 let inferred_ty = self.normalize(inferred_ty, Locations::All(span));
1045 let annotation = self.instantiate_canonical_with_fresh_inference_vars(span, user_ty);
1046 debug!(?annotation);
1048 UserType::Ty(mut ty) => {
1049 ty = self.normalize(ty, Locations::All(span));
1051 if let Err(terr) = self.eq_types(
1054 Locations::All(span),
1055 ConstraintCategory::BoringNoLocation,
1060 "bad user type ({:?} = {:?}): {:?}",
1067 self.prove_predicate(
1068 ty::Binder::dummy(ty::PredicateKind::WellFormed(inferred_ty.into())),
1069 Locations::All(span),
1070 ConstraintCategory::TypeAnnotation,
1073 UserType::TypeOf(def_id, user_substs) => {
1074 if let Err(terr) = self.fully_perform_op(
1075 Locations::All(span),
1076 ConstraintCategory::BoringNoLocation,
1077 self.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
1086 "bad user type AscribeUserType({:?}, {:?} {:?}, type_of={:?}): {:?}",
1090 self.tcx().type_of(def_id),
1099 #[instrument(skip(self, data), level = "debug")]
1100 fn push_region_constraints(
1102 locations: Locations,
1103 category: ConstraintCategory<'tcx>,
1104 data: &QueryRegionConstraints<'tcx>,
1106 debug!("constraints generated: {:#?}", data);
1108 constraint_conversion::ConstraintConversion::new(
1110 self.borrowck_context.universal_regions,
1111 self.region_bound_pairs,
1112 self.implicit_region_bound,
1115 locations.span(self.body),
1117 &mut self.borrowck_context.constraints,
1122 /// Try to relate `sub <: sup`
1127 locations: Locations,
1128 category: ConstraintCategory<'tcx>,
1130 // Use this order of parameters because the sup type is usually the
1131 // "expected" type in diagnostics.
1132 self.relate_types(sup, ty::Variance::Contravariant, sub, locations, category)
1135 #[instrument(skip(self, category), level = "debug")]
1140 locations: Locations,
1141 category: ConstraintCategory<'tcx>,
1143 self.relate_types(expected, ty::Variance::Invariant, found, locations, category)
1146 #[instrument(skip(self), level = "debug")]
1147 fn relate_type_and_user_type(
1151 user_ty: &UserTypeProjection,
1152 locations: Locations,
1153 category: ConstraintCategory<'tcx>,
1155 let annotated_type = self.user_type_annotations[user_ty.base].inferred_ty;
1156 trace!(?annotated_type);
1157 let mut curr_projected_ty = PlaceTy::from_ty(annotated_type);
1159 let tcx = self.infcx.tcx;
1161 for proj in &user_ty.projs {
1162 let projected_ty = curr_projected_ty.projection_ty_core(
1167 let ty = this.field_ty(tcx, field);
1168 self.normalize(ty, locations)
1170 |_, _| unreachable!(),
1172 curr_projected_ty = projected_ty;
1174 trace!(?curr_projected_ty);
1176 let ty = curr_projected_ty.ty;
1177 self.relate_types(ty, v.xform(ty::Variance::Contravariant), a, locations, category)?;
1182 fn tcx(&self) -> TyCtxt<'tcx> {
1186 #[instrument(skip(self, body, location), level = "debug")]
1187 fn check_stmt(&mut self, body: &Body<'tcx>, stmt: &Statement<'tcx>, location: Location) {
1188 let tcx = self.tcx();
1189 debug!("stmt kind: {:?}", stmt.kind);
1191 StatementKind::Assign(box (place, rv)) => {
1192 // Assignments to temporaries are not "interesting";
1193 // they are not caused by the user, but rather artifacts
1194 // of lowering. Assignments to other sorts of places *are* interesting
1196 let category = match place.as_local() {
1197 Some(RETURN_PLACE) => {
1198 let defining_ty = &self.borrowck_context.universal_regions.defining_ty;
1199 if defining_ty.is_const() {
1200 if tcx.is_static(defining_ty.def_id()) {
1201 ConstraintCategory::UseAsStatic
1203 ConstraintCategory::UseAsConst
1206 ConstraintCategory::Return(ReturnConstraint::Normal)
1211 body.local_decls[l].local_info,
1212 Some(box LocalInfo::AggregateTemp)
1215 ConstraintCategory::Usage
1217 Some(l) if !body.local_decls[l].is_user_variable() => {
1218 ConstraintCategory::Boring
1220 _ => ConstraintCategory::Assignment,
1223 "assignment category: {:?} {:?}",
1225 place.as_local().map(|l| &body.local_decls[l])
1228 let place_ty = place.ty(body, tcx).ty;
1230 let place_ty = self.normalize(place_ty, location);
1231 debug!("place_ty normalized: {:?}", place_ty);
1232 let rv_ty = rv.ty(body, tcx);
1234 let rv_ty = self.normalize(rv_ty, location);
1235 debug!("normalized rv_ty: {:?}", rv_ty);
1237 self.sub_types(rv_ty, place_ty, location.to_locations(), category)
1242 "bad assignment ({:?} = {:?}): {:?}",
1249 if let Some(annotation_index) = self.rvalue_user_ty(rv) {
1250 if let Err(terr) = self.relate_type_and_user_type(
1252 ty::Variance::Invariant,
1253 &UserTypeProjection { base: annotation_index, projs: vec![] },
1254 location.to_locations(),
1255 ConstraintCategory::Boring,
1257 let annotation = &self.user_type_annotations[annotation_index];
1261 "bad user type on rvalue ({:?} = {:?}): {:?}",
1269 self.check_rvalue(body, rv, location);
1270 if !self.unsized_feature_enabled() {
1272 tcx.at(self.last_span).mk_trait_ref(LangItem::Sized, [place_ty]);
1273 self.prove_trait_ref(
1275 location.to_locations(),
1276 ConstraintCategory::SizedBound,
1280 StatementKind::AscribeUserType(box (place, projection), variance) => {
1281 let place_ty = place.ty(body, tcx).ty;
1282 if let Err(terr) = self.relate_type_and_user_type(
1286 Locations::All(stmt.source_info.span),
1287 ConstraintCategory::TypeAnnotation,
1289 let annotation = &self.user_type_annotations[projection.base];
1293 "bad type assert ({:?} <: {:?} with projections {:?}): {:?}",
1301 StatementKind::Intrinsic(box kind) => match kind {
1302 NonDivergingIntrinsic::Assume(op) => self.check_operand(op, location),
1303 NonDivergingIntrinsic::CopyNonOverlapping(..) => span_bug!(
1304 stmt.source_info.span,
1305 "Unexpected NonDivergingIntrinsic::CopyNonOverlapping, should only appear after lowering_intrinsics",
1308 StatementKind::FakeRead(..)
1309 | StatementKind::StorageLive(..)
1310 | StatementKind::StorageDead(..)
1311 | StatementKind::Retag { .. }
1312 | StatementKind::Coverage(..)
1313 | StatementKind::Nop => {}
1314 StatementKind::Deinit(..) | StatementKind::SetDiscriminant { .. } => {
1315 bug!("Statement not allowed in this MIR phase")
1320 #[instrument(skip(self, body, term_location), level = "debug")]
1321 fn check_terminator(
1324 term: &Terminator<'tcx>,
1325 term_location: Location,
1327 let tcx = self.tcx();
1328 debug!("terminator kind: {:?}", term.kind);
1330 TerminatorKind::Goto { .. }
1331 | TerminatorKind::Resume
1332 | TerminatorKind::Abort
1333 | TerminatorKind::Return
1334 | TerminatorKind::GeneratorDrop
1335 | TerminatorKind::Unreachable
1336 | TerminatorKind::Drop { .. }
1337 | TerminatorKind::FalseEdge { .. }
1338 | TerminatorKind::FalseUnwind { .. }
1339 | TerminatorKind::InlineAsm { .. } => {
1340 // no checks needed for these
1343 TerminatorKind::DropAndReplace { place, value, target: _, unwind: _ } => {
1344 let place_ty = place.ty(body, tcx).ty;
1345 let rv_ty = value.ty(body, tcx);
1347 let locations = term_location.to_locations();
1349 self.sub_types(rv_ty, place_ty, locations, ConstraintCategory::Assignment)
1354 "bad DropAndReplace ({:?} = {:?}): {:?}",
1361 TerminatorKind::SwitchInt { discr, .. } => {
1362 self.check_operand(discr, term_location);
1364 let switch_ty = discr.ty(body, tcx);
1365 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
1366 span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
1368 // FIXME: check the values
1370 TerminatorKind::Call { func, args, destination, from_hir_call, target, .. } => {
1371 self.check_operand(func, term_location);
1373 self.check_operand(arg, term_location);
1376 let func_ty = func.ty(body, tcx);
1377 debug!("func_ty.kind: {:?}", func_ty.kind());
1379 let sig = match func_ty.kind() {
1380 ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx),
1382 span_mirbug!(self, term, "call to non-function {:?}", func_ty);
1386 let (sig, map) = tcx.replace_late_bound_regions(sig, |br| {
1387 self.infcx.next_region_var(LateBoundRegion(
1388 term.source_info.span,
1390 LateBoundRegionConversionTime::FnCall,
1394 // IMPORTANT: We have to prove well formed for the function signature before
1395 // we normalize it, as otherwise types like `<&'a &'b () as Trait>::Assoc`
1396 // get normalized away, causing us to ignore the `'b: 'a` bound used by the function.
1398 // Normalization results in a well formed type if the input is well formed, so we
1399 // don't have to check it twice.
1401 // See #91068 for an example.
1402 self.prove_predicates(
1403 sig.inputs_and_output
1405 .map(|ty| ty::Binder::dummy(ty::PredicateKind::WellFormed(ty.into()))),
1406 term_location.to_locations(),
1407 ConstraintCategory::Boring,
1409 let sig = self.normalize(sig, term_location);
1410 self.check_call_dest(body, term, &sig, *destination, *target, term_location);
1412 // The ordinary liveness rules will ensure that all
1413 // regions in the type of the callee are live here. We
1414 // then further constrain the late-bound regions that
1415 // were instantiated at the call site to be live as
1416 // well. The resulting is that all the input (and
1417 // output) types in the signature must be live, since
1418 // all the inputs that fed into it were live.
1419 for &late_bound_region in map.values() {
1421 self.borrowck_context.universal_regions.to_region_vid(late_bound_region);
1422 self.borrowck_context
1424 .liveness_constraints
1425 .add_element(region_vid, term_location);
1428 self.check_call_inputs(body, term, &sig, args, term_location, *from_hir_call);
1430 TerminatorKind::Assert { cond, msg, .. } => {
1431 self.check_operand(cond, term_location);
1433 let cond_ty = cond.ty(body, tcx);
1434 if cond_ty != tcx.types.bool {
1435 span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
1438 if let AssertKind::BoundsCheck { len, index } = msg {
1439 if len.ty(body, tcx) != tcx.types.usize {
1440 span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
1442 if index.ty(body, tcx) != tcx.types.usize {
1443 span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
1447 TerminatorKind::Yield { value, .. } => {
1448 self.check_operand(value, term_location);
1450 let value_ty = value.ty(body, tcx);
1451 match body.yield_ty() {
1452 None => span_mirbug!(self, term, "yield in non-generator"),
1454 if let Err(terr) = self.sub_types(
1457 term_location.to_locations(),
1458 ConstraintCategory::Yield,
1463 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
1478 term: &Terminator<'tcx>,
1479 sig: &ty::FnSig<'tcx>,
1480 destination: Place<'tcx>,
1481 target: Option<BasicBlock>,
1482 term_location: Location,
1484 let tcx = self.tcx();
1487 let dest_ty = destination.ty(body, tcx).ty;
1488 let dest_ty = self.normalize(dest_ty, term_location);
1489 let category = match destination.as_local() {
1490 Some(RETURN_PLACE) => {
1491 if let BorrowCheckContext {
1495 DefiningTy::Const(def_id, _)
1496 | DefiningTy::InlineConst(def_id, _),
1500 } = self.borrowck_context
1502 if tcx.is_static(*def_id) {
1503 ConstraintCategory::UseAsStatic
1505 ConstraintCategory::UseAsConst
1508 ConstraintCategory::Return(ReturnConstraint::Normal)
1511 Some(l) if !body.local_decls[l].is_user_variable() => {
1512 ConstraintCategory::Boring
1514 _ => ConstraintCategory::Assignment,
1517 let locations = term_location.to_locations();
1519 if let Err(terr) = self.sub_types(sig.output(), dest_ty, locations, category) {
1523 "call dest mismatch ({:?} <- {:?}): {:?}",
1530 // When `unsized_fn_params` and `unsized_locals` are both not enabled,
1531 // this check is done at `check_local`.
1532 if self.unsized_feature_enabled() {
1533 let span = term.source_info.span;
1534 self.ensure_place_sized(dest_ty, span);
1538 if !sig.output().is_privately_uninhabited(self.tcx(), self.param_env) {
1539 span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
1545 fn check_call_inputs(
1548 term: &Terminator<'tcx>,
1549 sig: &ty::FnSig<'tcx>,
1550 args: &[Operand<'tcx>],
1551 term_location: Location,
1552 from_hir_call: bool,
1554 debug!("check_call_inputs({:?}, {:?})", sig, args);
1555 if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.c_variadic) {
1556 span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1559 let func_ty = if let TerminatorKind::Call { func, .. } = &term.kind {
1560 Some(func.ty(body, self.infcx.tcx))
1566 for (n, (fn_arg, op_arg)) in iter::zip(sig.inputs(), args).enumerate() {
1567 let op_arg_ty = op_arg.ty(body, self.tcx());
1569 let op_arg_ty = self.normalize(op_arg_ty, term_location);
1570 let category = if from_hir_call {
1571 ConstraintCategory::CallArgument(self.infcx.tcx.erase_regions(func_ty))
1573 ConstraintCategory::Boring
1576 self.sub_types(op_arg_ty, *fn_arg, term_location.to_locations(), category)
1581 "bad arg #{:?} ({:?} <- {:?}): {:?}",
1591 fn check_iscleanup(&mut self, body: &Body<'tcx>, block_data: &BasicBlockData<'tcx>) {
1592 let is_cleanup = block_data.is_cleanup;
1593 self.last_span = block_data.terminator().source_info.span;
1594 match block_data.terminator().kind {
1595 TerminatorKind::Goto { target } => {
1596 self.assert_iscleanup(body, block_data, target, is_cleanup)
1598 TerminatorKind::SwitchInt { ref targets, .. } => {
1599 for target in targets.all_targets() {
1600 self.assert_iscleanup(body, block_data, *target, is_cleanup);
1603 TerminatorKind::Resume => {
1605 span_mirbug!(self, block_data, "resume on non-cleanup block!")
1608 TerminatorKind::Abort => {
1610 span_mirbug!(self, block_data, "abort on non-cleanup block!")
1613 TerminatorKind::Return => {
1615 span_mirbug!(self, block_data, "return on cleanup block")
1618 TerminatorKind::GeneratorDrop { .. } => {
1620 span_mirbug!(self, block_data, "generator_drop in cleanup block")
1623 TerminatorKind::Yield { resume, drop, .. } => {
1625 span_mirbug!(self, block_data, "yield in cleanup block")
1627 self.assert_iscleanup(body, block_data, resume, is_cleanup);
1628 if let Some(drop) = drop {
1629 self.assert_iscleanup(body, block_data, drop, is_cleanup);
1632 TerminatorKind::Unreachable => {}
1633 TerminatorKind::Drop { target, unwind, .. }
1634 | TerminatorKind::DropAndReplace { target, unwind, .. }
1635 | TerminatorKind::Assert { target, cleanup: unwind, .. } => {
1636 self.assert_iscleanup(body, block_data, target, is_cleanup);
1637 if let Some(unwind) = unwind {
1639 span_mirbug!(self, block_data, "unwind on cleanup block")
1641 self.assert_iscleanup(body, block_data, unwind, true);
1644 TerminatorKind::Call { ref target, cleanup, .. } => {
1645 if let &Some(target) = target {
1646 self.assert_iscleanup(body, block_data, target, is_cleanup);
1648 if let Some(cleanup) = cleanup {
1650 span_mirbug!(self, block_data, "cleanup on cleanup block")
1652 self.assert_iscleanup(body, block_data, cleanup, true);
1655 TerminatorKind::FalseEdge { real_target, imaginary_target } => {
1656 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1657 self.assert_iscleanup(body, block_data, imaginary_target, is_cleanup);
1659 TerminatorKind::FalseUnwind { real_target, unwind } => {
1660 self.assert_iscleanup(body, block_data, real_target, is_cleanup);
1661 if let Some(unwind) = unwind {
1663 span_mirbug!(self, block_data, "cleanup in cleanup block via false unwind");
1665 self.assert_iscleanup(body, block_data, unwind, true);
1668 TerminatorKind::InlineAsm { destination, cleanup, .. } => {
1669 if let Some(target) = destination {
1670 self.assert_iscleanup(body, block_data, target, is_cleanup);
1672 if let Some(cleanup) = cleanup {
1674 span_mirbug!(self, block_data, "cleanup on cleanup block")
1676 self.assert_iscleanup(body, block_data, cleanup, true);
1682 fn assert_iscleanup(
1685 ctxt: &dyn fmt::Debug,
1689 if body[bb].is_cleanup != iscleanuppad {
1690 span_mirbug!(self, ctxt, "cleanuppad mismatch: {:?} should be {:?}", bb, iscleanuppad);
1694 fn check_local(&mut self, body: &Body<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) {
1695 match body.local_kind(local) {
1696 LocalKind::ReturnPointer | LocalKind::Arg => {
1697 // return values of normal functions are required to be
1698 // sized by typeck, but return values of ADT constructors are
1699 // not because we don't include a `Self: Sized` bounds on them.
1701 // Unbound parts of arguments were never required to be Sized
1702 // - maybe we should make that a warning.
1705 LocalKind::Var | LocalKind::Temp => {}
1708 // When `unsized_fn_params` or `unsized_locals` is enabled, only function calls
1709 // and nullary ops are checked in `check_call_dest`.
1710 if !self.unsized_feature_enabled() {
1711 let span = local_decl.source_info.span;
1712 let ty = local_decl.ty;
1713 self.ensure_place_sized(ty, span);
1717 fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
1718 let tcx = self.tcx();
1720 // Erase the regions from `ty` to get a global type. The
1721 // `Sized` bound in no way depends on precise regions, so this
1722 // shouldn't affect `is_sized`.
1723 let erased_ty = tcx.erase_regions(ty);
1724 if !erased_ty.is_sized(tcx, self.param_env) {
1725 // in current MIR construction, all non-control-flow rvalue
1726 // expressions evaluate through `as_temp` or `into` a return
1727 // slot or local, so to find all unsized rvalues it is enough
1728 // to check all temps, return slots and locals.
1729 if self.reported_errors.replace((ty, span)).is_none() {
1730 // While this is located in `nll::typeck` this error is not
1731 // an NLL error, it's a required check to prevent creation
1732 // of unsized rvalues in a call expression.
1733 self.tcx().sess.emit_err(MoveUnsized { ty, span });
1738 fn aggregate_field_ty(
1740 ak: &AggregateKind<'tcx>,
1743 ) -> Result<Ty<'tcx>, FieldAccessError> {
1744 let tcx = self.tcx();
1747 AggregateKind::Adt(adt_did, variant_index, substs, _, active_field_index) => {
1748 let def = tcx.adt_def(adt_did);
1749 let variant = &def.variant(variant_index);
1750 let adj_field_index = active_field_index.unwrap_or(field_index);
1751 if let Some(field) = variant.fields.get(adj_field_index) {
1752 Ok(self.normalize(field.ty(tcx, substs), location))
1754 Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
1757 AggregateKind::Closure(_, substs) => {
1758 match substs.as_closure().upvar_tys().nth(field_index) {
1760 None => Err(FieldAccessError::OutOfRange {
1761 field_count: substs.as_closure().upvar_tys().count(),
1765 AggregateKind::Generator(_, substs, _) => {
1766 // It doesn't make sense to look at a field beyond the prefix;
1767 // these require a variant index, and are not initialized in
1768 // aggregate rvalues.
1769 match substs.as_generator().prefix_tys().nth(field_index) {
1771 None => Err(FieldAccessError::OutOfRange {
1772 field_count: substs.as_generator().prefix_tys().count(),
1776 AggregateKind::Array(ty) => Ok(ty),
1777 AggregateKind::Tuple => {
1778 unreachable!("This should have been covered in check_rvalues");
1783 fn check_operand(&mut self, op: &Operand<'tcx>, location: Location) {
1784 debug!(?op, ?location, "check_operand");
1786 if let Operand::Constant(constant) = op {
1787 let maybe_uneval = match constant.literal {
1788 ConstantKind::Val(..) | ConstantKind::Ty(_) => None,
1789 ConstantKind::Unevaluated(uv, _) => Some(uv),
1792 if let Some(uv) = maybe_uneval {
1793 if uv.promoted.is_none() {
1794 let tcx = self.tcx();
1795 let def_id = uv.def.def_id_for_type_of();
1796 if tcx.def_kind(def_id) == DefKind::InlineConst {
1797 let def_id = def_id.expect_local();
1799 self.prove_closure_bounds(tcx, def_id, uv.substs, location);
1800 self.normalize_and_prove_instantiated_predicates(
1803 location.to_locations(),
1811 #[instrument(skip(self, body), level = "debug")]
1812 fn check_rvalue(&mut self, body: &Body<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
1813 let tcx = self.tcx();
1814 let span = body.source_info(location).span;
1817 Rvalue::Aggregate(ak, ops) => {
1819 self.check_operand(op, location);
1821 self.check_aggregate_rvalue(&body, rvalue, ak, ops, location)
1824 Rvalue::Repeat(operand, len) => {
1825 self.check_operand(operand, location);
1827 // If the length cannot be evaluated we must assume that the length can be larger
1829 // If the length is larger than 1, the repeat expression will need to copy the
1830 // element, so we require the `Copy` trait.
1831 if len.try_eval_usize(tcx, self.param_env).map_or(true, |len| len > 1) {
1833 Operand::Copy(..) | Operand::Constant(..) => {
1834 // These are always okay: direct use of a const, or a value that can evidently be copied.
1836 Operand::Move(place) => {
1837 // Make sure that repeated elements implement `Copy`.
1838 let ty = place.ty(body, tcx).ty;
1839 let trait_ref = tcx.at(span).mk_trait_ref(LangItem::Copy, [ty]);
1841 self.prove_trait_ref(
1843 Locations::Single(location),
1844 ConstraintCategory::CopyBound,
1851 &Rvalue::NullaryOp(NullOp::SizeOf | NullOp::AlignOf, ty) => {
1852 let trait_ref = tcx.at(span).mk_trait_ref(LangItem::Sized, [ty]);
1854 self.prove_trait_ref(
1856 location.to_locations(),
1857 ConstraintCategory::SizedBound,
1861 Rvalue::ShallowInitBox(operand, ty) => {
1862 self.check_operand(operand, location);
1864 let trait_ref = tcx.at(span).mk_trait_ref(LangItem::Sized, [*ty]);
1866 self.prove_trait_ref(
1868 location.to_locations(),
1869 ConstraintCategory::SizedBound,
1873 Rvalue::Cast(cast_kind, op, ty) => {
1874 self.check_operand(op, location);
1877 CastKind::Pointer(PointerCast::ReifyFnPointer) => {
1878 let fn_sig = op.ty(body, tcx).fn_sig(tcx);
1880 // The type that we see in the fcx is like
1881 // `foo::<'a, 'b>`, where `foo` is the path to a
1882 // function definition. When we extract the
1883 // signature, it comes from the `fn_sig` query,
1884 // and hence may contain unnormalized results.
1885 let fn_sig = self.normalize(fn_sig, location);
1887 let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
1889 if let Err(terr) = self.eq_types(
1892 location.to_locations(),
1893 ConstraintCategory::Cast,
1898 "equating {:?} with {:?} yields {:?}",
1906 CastKind::Pointer(PointerCast::ClosureFnPointer(unsafety)) => {
1907 let sig = match op.ty(body, tcx).kind() {
1908 ty::Closure(_, substs) => substs.as_closure().sig(),
1911 let ty_fn_ptr_from = tcx.mk_fn_ptr(tcx.signature_unclosure(sig, *unsafety));
1913 if let Err(terr) = self.eq_types(
1916 location.to_locations(),
1917 ConstraintCategory::Cast,
1922 "equating {:?} with {:?} yields {:?}",
1930 CastKind::Pointer(PointerCast::UnsafeFnPointer) => {
1931 let fn_sig = op.ty(body, tcx).fn_sig(tcx);
1933 // The type that we see in the fcx is like
1934 // `foo::<'a, 'b>`, where `foo` is the path to a
1935 // function definition. When we extract the
1936 // signature, it comes from the `fn_sig` query,
1937 // and hence may contain unnormalized results.
1938 let fn_sig = self.normalize(fn_sig, location);
1940 let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
1942 if let Err(terr) = self.eq_types(
1945 location.to_locations(),
1946 ConstraintCategory::Cast,
1951 "equating {:?} with {:?} yields {:?}",
1959 CastKind::Pointer(PointerCast::Unsize) => {
1963 .mk_trait_ref(LangItem::CoerceUnsized, [op.ty(body, tcx), ty]);
1965 self.prove_trait_ref(
1967 location.to_locations(),
1968 ConstraintCategory::Cast,
1972 CastKind::DynStar => {
1973 // get the constraints from the target type (`dyn* Clone`)
1975 // apply them to prove that the source type `Foo` implements `Clone` etc
1976 let (existential_predicates, region) = match ty.kind() {
1977 Dynamic(predicates, region, ty::DynStar) => (predicates, region),
1978 _ => panic!("Invalid dyn* cast_ty"),
1981 let self_ty = op.ty(body, tcx);
1983 self.prove_predicates(
1984 existential_predicates
1986 .map(|predicate| predicate.with_self_ty(tcx, self_ty)),
1987 location.to_locations(),
1988 ConstraintCategory::Cast,
1991 let outlives_predicate =
1992 tcx.mk_predicate(Binder::dummy(ty::PredicateKind::Clause(
1993 ty::Clause::TypeOutlives(ty::OutlivesPredicate(self_ty, *region)),
1995 self.prove_predicate(
1997 location.to_locations(),
1998 ConstraintCategory::Cast,
2002 CastKind::Pointer(PointerCast::MutToConstPointer) => {
2003 let ty::RawPtr(ty::TypeAndMut {
2005 mutbl: hir::Mutability::Mut,
2006 }) = op.ty(body, tcx).kind() else {
2010 "unexpected base type for cast {:?}",
2015 let ty::RawPtr(ty::TypeAndMut {
2017 mutbl: hir::Mutability::Not,
2018 }) = ty.kind() else {
2022 "unexpected target type for cast {:?}",
2027 if let Err(terr) = self.sub_types(
2030 location.to_locations(),
2031 ConstraintCategory::Cast,
2036 "relating {:?} with {:?} yields {:?}",
2044 CastKind::Pointer(PointerCast::ArrayToPointer) => {
2045 let ty_from = op.ty(body, tcx);
2047 let opt_ty_elem_mut = match ty_from.kind() {
2048 ty::RawPtr(ty::TypeAndMut { mutbl: array_mut, ty: array_ty }) => {
2049 match array_ty.kind() {
2050 ty::Array(ty_elem, _) => Some((ty_elem, *array_mut)),
2057 let Some((ty_elem, ty_mut)) = opt_ty_elem_mut else {
2061 "ArrayToPointer cast from unexpected type {:?}",
2067 let (ty_to, ty_to_mut) = match ty.kind() {
2068 ty::RawPtr(ty::TypeAndMut { mutbl: ty_to_mut, ty: ty_to }) => {
2075 "ArrayToPointer cast to unexpected type {:?}",
2082 if ty_to_mut == Mutability::Mut && ty_mut == Mutability::Not {
2086 "ArrayToPointer cast from const {:?} to mut {:?}",
2093 if let Err(terr) = self.sub_types(
2096 location.to_locations(),
2097 ConstraintCategory::Cast,
2102 "relating {:?} with {:?} yields {:?}",
2110 CastKind::PointerExposeAddress => {
2111 let ty_from = op.ty(body, tcx);
2112 let cast_ty_from = CastTy::from_ty(ty_from);
2113 let cast_ty_to = CastTy::from_ty(*ty);
2114 match (cast_ty_from, cast_ty_to) {
2115 (Some(CastTy::Ptr(_) | CastTy::FnPtr), Some(CastTy::Int(_))) => (),
2120 "Invalid PointerExposeAddress cast {:?} -> {:?}",
2128 CastKind::PointerFromExposedAddress => {
2129 let ty_from = op.ty(body, tcx);
2130 let cast_ty_from = CastTy::from_ty(ty_from);
2131 let cast_ty_to = CastTy::from_ty(*ty);
2132 match (cast_ty_from, cast_ty_to) {
2133 (Some(CastTy::Int(_)), Some(CastTy::Ptr(_))) => (),
2138 "Invalid PointerFromExposedAddress cast {:?} -> {:?}",
2145 CastKind::IntToInt => {
2146 let ty_from = op.ty(body, tcx);
2147 let cast_ty_from = CastTy::from_ty(ty_from);
2148 let cast_ty_to = CastTy::from_ty(*ty);
2149 match (cast_ty_from, cast_ty_to) {
2150 (Some(CastTy::Int(_)), Some(CastTy::Int(_))) => (),
2155 "Invalid IntToInt cast {:?} -> {:?}",
2162 CastKind::IntToFloat => {
2163 let ty_from = op.ty(body, tcx);
2164 let cast_ty_from = CastTy::from_ty(ty_from);
2165 let cast_ty_to = CastTy::from_ty(*ty);
2166 match (cast_ty_from, cast_ty_to) {
2167 (Some(CastTy::Int(_)), Some(CastTy::Float)) => (),
2172 "Invalid IntToFloat cast {:?} -> {:?}",
2179 CastKind::FloatToInt => {
2180 let ty_from = op.ty(body, tcx);
2181 let cast_ty_from = CastTy::from_ty(ty_from);
2182 let cast_ty_to = CastTy::from_ty(*ty);
2183 match (cast_ty_from, cast_ty_to) {
2184 (Some(CastTy::Float), Some(CastTy::Int(_))) => (),
2189 "Invalid FloatToInt cast {:?} -> {:?}",
2196 CastKind::FloatToFloat => {
2197 let ty_from = op.ty(body, tcx);
2198 let cast_ty_from = CastTy::from_ty(ty_from);
2199 let cast_ty_to = CastTy::from_ty(*ty);
2200 match (cast_ty_from, cast_ty_to) {
2201 (Some(CastTy::Float), Some(CastTy::Float)) => (),
2206 "Invalid FloatToFloat cast {:?} -> {:?}",
2213 CastKind::FnPtrToPtr => {
2214 let ty_from = op.ty(body, tcx);
2215 let cast_ty_from = CastTy::from_ty(ty_from);
2216 let cast_ty_to = CastTy::from_ty(*ty);
2217 match (cast_ty_from, cast_ty_to) {
2218 (Some(CastTy::FnPtr), Some(CastTy::Ptr(_))) => (),
2223 "Invalid FnPtrToPtr cast {:?} -> {:?}",
2230 CastKind::PtrToPtr => {
2231 let ty_from = op.ty(body, tcx);
2232 let cast_ty_from = CastTy::from_ty(ty_from);
2233 let cast_ty_to = CastTy::from_ty(*ty);
2234 match (cast_ty_from, cast_ty_to) {
2235 (Some(CastTy::Ptr(_)), Some(CastTy::Ptr(_))) => (),
2240 "Invalid PtrToPtr cast {:?} -> {:?}",
2250 Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
2251 self.add_reborrow_constraint(&body, location, *region, borrowed_place);
2255 BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge,
2258 self.check_operand(left, location);
2259 self.check_operand(right, location);
2261 let ty_left = left.ty(body, tcx);
2262 match ty_left.kind() {
2263 // Types with regions are comparable if they have a common super-type.
2264 ty::RawPtr(_) | ty::FnPtr(_) => {
2265 let ty_right = right.ty(body, tcx);
2266 let common_ty = self.infcx.next_ty_var(TypeVariableOrigin {
2267 kind: TypeVariableOriginKind::MiscVariable,
2268 span: body.source_info(location).span,
2273 location.to_locations(),
2274 ConstraintCategory::Boring,
2276 .unwrap_or_else(|err| {
2277 bug!("Could not equate type variable with {:?}: {:?}", ty_left, err)
2279 if let Err(terr) = self.sub_types(
2282 location.to_locations(),
2283 ConstraintCategory::Boring,
2288 "unexpected comparison types {:?} and {:?} yields {:?}",
2295 // For types with no regions we can just check that the
2296 // both operands have the same type.
2297 ty::Int(_) | ty::Uint(_) | ty::Bool | ty::Char | ty::Float(_)
2298 if ty_left == right.ty(body, tcx) => {}
2299 // Other types are compared by trait methods, not by
2300 // `Rvalue::BinaryOp`.
2304 "unexpected comparison types {:?} and {:?}",
2311 Rvalue::Use(operand) | Rvalue::UnaryOp(_, operand) => {
2312 self.check_operand(operand, location);
2314 Rvalue::CopyForDeref(place) => {
2315 let op = &Operand::Copy(*place);
2316 self.check_operand(op, location);
2319 Rvalue::BinaryOp(_, box (left, right))
2320 | Rvalue::CheckedBinaryOp(_, box (left, right)) => {
2321 self.check_operand(left, location);
2322 self.check_operand(right, location);
2325 Rvalue::AddressOf(..)
2326 | Rvalue::ThreadLocalRef(..)
2328 | Rvalue::Discriminant(..) => {}
2332 /// If this rvalue supports a user-given type annotation, then
2333 /// extract and return it. This represents the final type of the
2334 /// rvalue and will be unified with the inferred type.
2335 fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotationIndex> {
2338 | Rvalue::ThreadLocalRef(_)
2339 | Rvalue::Repeat(..)
2341 | Rvalue::AddressOf(..)
2344 | Rvalue::ShallowInitBox(..)
2345 | Rvalue::BinaryOp(..)
2346 | Rvalue::CheckedBinaryOp(..)
2347 | Rvalue::NullaryOp(..)
2348 | Rvalue::CopyForDeref(..)
2349 | Rvalue::UnaryOp(..)
2350 | Rvalue::Discriminant(..) => None,
2352 Rvalue::Aggregate(aggregate, _) => match **aggregate {
2353 AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
2354 AggregateKind::Array(_) => None,
2355 AggregateKind::Tuple => None,
2356 AggregateKind::Closure(_, _) => None,
2357 AggregateKind::Generator(_, _, _) => None,
2362 fn check_aggregate_rvalue(
2365 rvalue: &Rvalue<'tcx>,
2366 aggregate_kind: &AggregateKind<'tcx>,
2367 operands: &[Operand<'tcx>],
2370 let tcx = self.tcx();
2372 self.prove_aggregate_predicates(aggregate_kind, location);
2374 if *aggregate_kind == AggregateKind::Tuple {
2375 // tuple rvalue field type is always the type of the op. Nothing to check here.
2379 for (i, operand) in operands.iter().enumerate() {
2380 let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
2381 Ok(field_ty) => field_ty,
2382 Err(FieldAccessError::OutOfRange { field_count }) => {
2386 "accessed field #{} but variant only has {}",
2393 let operand_ty = operand.ty(body, tcx);
2394 let operand_ty = self.normalize(operand_ty, location);
2396 if let Err(terr) = self.sub_types(
2399 location.to_locations(),
2400 ConstraintCategory::Boring,
2405 "{:?} is not a subtype of {:?}: {:?}",
2414 /// Adds the constraints that arise from a borrow expression `&'a P` at the location `L`.
2418 /// - `location`: the location `L` where the borrow expression occurs
2419 /// - `borrow_region`: the region `'a` associated with the borrow
2420 /// - `borrowed_place`: the place `P` being borrowed
2421 fn add_reborrow_constraint(
2425 borrow_region: ty::Region<'tcx>,
2426 borrowed_place: &Place<'tcx>,
2428 // These constraints are only meaningful during borrowck:
2429 let BorrowCheckContext { borrow_set, location_table, all_facts, constraints, .. } =
2430 self.borrowck_context;
2432 // In Polonius mode, we also push a `loan_issued_at` fact
2433 // linking the loan to the region (in some cases, though,
2434 // there is no loan associated with this borrow expression --
2435 // that occurs when we are borrowing an unsafe place, for
2437 if let Some(all_facts) = all_facts {
2438 let _prof_timer = self.infcx.tcx.prof.generic_activity("polonius_fact_generation");
2439 if let Some(borrow_index) = borrow_set.get_index_of(&location) {
2440 let region_vid = borrow_region.to_region_vid();
2441 all_facts.loan_issued_at.push((
2444 location_table.mid_index(location),
2449 // If we are reborrowing the referent of another reference, we
2450 // need to add outlives relationships. In a case like `&mut
2451 // *p`, where the `p` has type `&'b mut Foo`, for example, we
2452 // need to ensure that `'b: 'a`.
2455 "add_reborrow_constraint({:?}, {:?}, {:?})",
2456 location, borrow_region, borrowed_place
2459 let mut cursor = borrowed_place.projection.as_ref();
2460 let tcx = self.infcx.tcx;
2461 let field = path_utils::is_upvar_field_projection(
2463 &self.borrowck_context.upvars,
2464 borrowed_place.as_ref(),
2467 let category = if let Some(field) = field {
2468 ConstraintCategory::ClosureUpvar(field)
2470 ConstraintCategory::Boring
2473 while let [proj_base @ .., elem] = cursor {
2476 debug!("add_reborrow_constraint - iteration {:?}", elem);
2479 ProjectionElem::Deref => {
2480 let base_ty = Place::ty_from(borrowed_place.local, proj_base, body, tcx).ty;
2482 debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
2483 match base_ty.kind() {
2484 ty::Ref(ref_region, _, mutbl) => {
2485 constraints.outlives_constraints.push(OutlivesConstraint {
2486 sup: ref_region.to_region_vid(),
2487 sub: borrow_region.to_region_vid(),
2488 locations: location.to_locations(),
2489 span: location.to_locations().span(body),
2491 variance_info: ty::VarianceDiagInfo::default(),
2492 from_closure: false,
2496 hir::Mutability::Not => {
2497 // Immutable reference. We don't need the base
2498 // to be valid for the entire lifetime of
2502 hir::Mutability::Mut => {
2503 // Mutable reference. We *do* need the base
2504 // to be valid, because after the base becomes
2505 // invalid, someone else can use our mutable deref.
2507 // This is in order to make the following function
2510 // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
2515 // As otherwise you could clone `&mut T` using the
2516 // following function:
2518 // fn bad(x: &mut T) -> (&mut T, &mut T) {
2519 // let my_clone = unsafe_deref(&'a x);
2528 // deref of raw pointer, guaranteed to be valid
2531 ty::Adt(def, _) if def.is_box() => {
2532 // deref of `Box`, need the base to be valid - propagate
2534 _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2537 ProjectionElem::Field(..)
2538 | ProjectionElem::Downcast(..)
2539 | ProjectionElem::OpaqueCast(..)
2540 | ProjectionElem::Index(..)
2541 | ProjectionElem::ConstantIndex { .. }
2542 | ProjectionElem::Subslice { .. } => {
2543 // other field access
2549 fn prove_aggregate_predicates(
2551 aggregate_kind: &AggregateKind<'tcx>,
2554 let tcx = self.tcx();
2557 "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2558 aggregate_kind, location
2561 let (def_id, instantiated_predicates) = match *aggregate_kind {
2562 AggregateKind::Adt(adt_did, _, substs, _, _) => {
2563 (adt_did, tcx.predicates_of(adt_did).instantiate(tcx, substs))
2566 // For closures, we have some **extra requirements** we
2567 // have to check. In particular, in their upvars and
2568 // signatures, closures often reference various regions
2569 // from the surrounding function -- we call those the
2570 // closure's free regions. When we borrow-check (and hence
2571 // region-check) closures, we may find that the closure
2572 // requires certain relationships between those free
2573 // regions. However, because those free regions refer to
2574 // portions of the CFG of their caller, the closure is not
2575 // in a position to verify those relationships. In that
2576 // case, the requirements get "propagated" to us, and so
2577 // we have to solve them here where we instantiate the
2580 // Despite the opacity of the previous paragraph, this is
2581 // actually relatively easy to understand in terms of the
2582 // desugaring. A closure gets desugared to a struct, and
2583 // these extra requirements are basically like where
2584 // clauses on the struct.
2585 AggregateKind::Closure(def_id, substs)
2586 | AggregateKind::Generator(def_id, substs, _) => {
2587 (def_id.to_def_id(), self.prove_closure_bounds(tcx, def_id, substs, location))
2590 AggregateKind::Array(_) | AggregateKind::Tuple => {
2591 (CRATE_DEF_ID.to_def_id(), ty::InstantiatedPredicates::empty())
2595 self.normalize_and_prove_instantiated_predicates(
2597 instantiated_predicates,
2598 location.to_locations(),
2602 fn prove_closure_bounds(
2606 substs: SubstsRef<'tcx>,
2608 ) -> ty::InstantiatedPredicates<'tcx> {
2609 if let Some(closure_requirements) = &tcx.mir_borrowck(def_id).closure_requirements {
2610 constraint_conversion::ConstraintConversion::new(
2612 self.borrowck_context.universal_regions,
2613 self.region_bound_pairs,
2614 self.implicit_region_bound,
2616 location.to_locations(),
2617 DUMMY_SP, // irrelevant; will be overrided.
2618 ConstraintCategory::Boring, // same as above.
2619 &mut self.borrowck_context.constraints,
2621 .apply_closure_requirements(
2622 &closure_requirements,
2628 // Now equate closure substs to regions inherited from `typeck_root_def_id`. Fixes #98589.
2629 let typeck_root_def_id = tcx.typeck_root_def_id(self.body.source.def_id());
2630 let typeck_root_substs = ty::InternalSubsts::identity_for_item(tcx, typeck_root_def_id);
2632 let parent_substs = match tcx.def_kind(def_id) {
2633 DefKind::Closure => substs.as_closure().parent_substs(),
2634 DefKind::Generator => substs.as_generator().parent_substs(),
2635 DefKind::InlineConst => substs.as_inline_const().parent_substs(),
2636 other => bug!("unexpected item {:?}", other),
2638 let parent_substs = tcx.mk_substs(parent_substs.iter());
2640 assert_eq!(typeck_root_substs.len(), parent_substs.len());
2641 if let Err(_) = self.eq_substs(
2644 location.to_locations(),
2645 ConstraintCategory::BoringNoLocation,
2650 "could not relate closure to parent {:?} != {:?}",
2656 tcx.predicates_of(def_id).instantiate(tcx, substs)
2659 #[instrument(skip(self, body), level = "debug")]
2660 fn typeck_mir(&mut self, body: &Body<'tcx>) {
2661 self.last_span = body.span;
2664 for (local, local_decl) in body.local_decls.iter_enumerated() {
2665 self.check_local(&body, local, local_decl);
2668 for (block, block_data) in body.basic_blocks.iter_enumerated() {
2669 let mut location = Location { block, statement_index: 0 };
2670 for stmt in &block_data.statements {
2671 if !stmt.source_info.span.is_dummy() {
2672 self.last_span = stmt.source_info.span;
2674 self.check_stmt(body, stmt, location);
2675 location.statement_index += 1;
2678 self.check_terminator(&body, block_data.terminator(), location);
2679 self.check_iscleanup(&body, block_data);
2684 trait NormalizeLocation: fmt::Debug + Copy {
2685 fn to_locations(self) -> Locations;
2688 impl NormalizeLocation for Locations {
2689 fn to_locations(self) -> Locations {
2694 impl NormalizeLocation for Location {
2695 fn to_locations(self) -> Locations {
2696 Locations::Single(self)
2700 /// Runs `infcx.instantiate_opaque_types`. Unlike other `TypeOp`s,
2701 /// this is not canonicalized - it directly affects the main `InferCtxt`
2702 /// that we use during MIR borrowchecking.
2704 pub(super) struct InstantiateOpaqueType<'tcx> {
2705 pub base_universe: Option<ty::UniverseIndex>,
2706 pub region_constraints: Option<RegionConstraintData<'tcx>>,
2707 pub obligations: Vec<PredicateObligation<'tcx>>,
2710 impl<'tcx> TypeOp<'tcx> for InstantiateOpaqueType<'tcx> {
2712 /// We use this type itself to store the information used
2713 /// when reporting errors. Since this is not a query, we don't
2714 /// re-run anything during error reporting - we just use the information
2715 /// we saved to help extract an error from the already-existing region
2716 /// constraints in our `InferCtxt`
2717 type ErrorInfo = InstantiateOpaqueType<'tcx>;
2719 fn fully_perform(mut self, infcx: &InferCtxt<'tcx>) -> Fallible<TypeOpOutput<'tcx, Self>> {
2720 let (mut output, region_constraints) = scrape_region_constraints(infcx, || {
2721 Ok(InferOk { value: (), obligations: self.obligations.clone() })
2723 self.region_constraints = Some(region_constraints);
2724 output.error_info = Some(self);