1use std::rc::Rc;
4use std::{fmt, iter, mem};
5
6use rustc_abi::FieldIdx;
7use rustc_data_structures::frozen::Frozen;
8use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
9use rustc_errors::ErrorGuaranteed;
10use rustc_hir as hir;
11use rustc_hir::def::DefKind;
12use rustc_hir::def_id::LocalDefId;
13use rustc_hir::lang_items::LangItem;
14use rustc_index::{IndexSlice, IndexVec};
15use rustc_infer::infer::canonical::QueryRegionConstraints;
16use rustc_infer::infer::outlives::env::RegionBoundPairs;
17use rustc_infer::infer::region_constraints::RegionConstraintData;
18use rustc_infer::infer::{
19 BoundRegionConversionTime, InferCtxt, NllRegionVariableOrigin, RegionVariableOrigin,
20};
21use rustc_infer::traits::PredicateObligations;
22use rustc_middle::mir::visit::{NonMutatingUseContext, PlaceContext, Visitor};
23use rustc_middle::mir::*;
24use rustc_middle::traits::query::NoSolution;
25use rustc_middle::ty::adjustment::PointerCoercion;
26use rustc_middle::ty::cast::CastTy;
27use rustc_middle::ty::{
28 self, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, CoroutineArgsExt,
29 GenericArgsRef, Ty, TyCtxt, TypeVisitableExt, UserArgs, UserTypeAnnotationIndex, fold_regions,
30};
31use rustc_middle::{bug, span_bug};
32use rustc_mir_dataflow::move_paths::MoveData;
33use rustc_mir_dataflow::points::DenseLocationMap;
34use rustc_span::def_id::CRATE_DEF_ID;
35use rustc_span::source_map::Spanned;
36use rustc_span::{Span, sym};
37use rustc_trait_selection::infer::InferCtxtExt;
38use rustc_trait_selection::traits::query::type_op::custom::scrape_region_constraints;
39use rustc_trait_selection::traits::query::type_op::{TypeOp, TypeOpOutput};
40use tracing::{debug, instrument, trace};
41
42use crate::borrow_set::BorrowSet;
43use crate::constraints::{OutlivesConstraint, OutlivesConstraintSet};
44use crate::diagnostics::UniverseInfo;
45use crate::polonius::legacy::{PoloniusFacts, PoloniusLocationTable};
46use crate::polonius::{PoloniusContext, PoloniusLivenessContext};
47use crate::region_infer::TypeTest;
48use crate::region_infer::values::{LivenessValues, PlaceholderIndex, PlaceholderIndices};
49use crate::session_diagnostics::{MoveUnsized, SimdIntrinsicArgConst};
50use crate::type_check::free_region_relations::{CreateResult, UniversalRegionRelations};
51use crate::universal_regions::{DefiningTy, UniversalRegions};
52use crate::{BorrowCheckRootCtxt, BorrowckInferCtxt, DeferredClosureRequirements, path_utils};
53
54macro_rules! span_mirbug {
55 ($context:expr, $elem:expr, $($message:tt)*) => ({
56 $crate::type_check::mirbug(
57 $context.tcx(),
58 $context.last_span,
59 format!(
60 "broken MIR in {:?} ({:?}): {}",
61 $context.body().source.def_id(),
62 $elem,
63 format_args!($($message)*),
64 ),
65 )
66 })
67}
68
69pub(crate) mod canonical;
70pub(crate) mod constraint_conversion;
71pub(crate) mod free_region_relations;
72mod input_output;
73pub(crate) mod liveness;
74mod relate_tys;
75
76pub(crate) fn type_check<'tcx>(
99 root_cx: &mut BorrowCheckRootCtxt<'tcx>,
100 infcx: &BorrowckInferCtxt<'tcx>,
101 body: &Body<'tcx>,
102 promoted: &IndexSlice<Promoted, Body<'tcx>>,
103 universal_regions: UniversalRegions<'tcx>,
104 location_table: &PoloniusLocationTable,
105 borrow_set: &BorrowSet<'tcx>,
106 polonius_facts: &mut Option<PoloniusFacts>,
107 move_data: &MoveData<'tcx>,
108 location_map: Rc<DenseLocationMap>,
109) -> MirTypeckResults<'tcx> {
110 let mut constraints = MirTypeckRegionConstraints {
111 placeholder_indices: PlaceholderIndices::default(),
112 placeholder_index_to_region: IndexVec::default(),
113 liveness_constraints: LivenessValues::with_specific_points(Rc::clone(&location_map)),
114 outlives_constraints: OutlivesConstraintSet::default(),
115 type_tests: Vec::default(),
116 universe_causes: FxIndexMap::default(),
117 };
118
119 let CreateResult {
120 universal_region_relations,
121 region_bound_pairs,
122 normalized_inputs_and_output,
123 known_type_outlives_obligations,
124 } = free_region_relations::create(infcx, universal_regions, &mut constraints);
125
126 let pre_obligations = infcx.take_registered_region_obligations();
127 assert!(
128 pre_obligations.is_empty(),
129 "there should be no incoming region obligations = {pre_obligations:#?}",
130 );
131 let pre_assumptions = infcx.take_registered_region_assumptions();
132 assert!(
133 pre_assumptions.is_empty(),
134 "there should be no incoming region assumptions = {pre_assumptions:#?}",
135 );
136
137 debug!(?normalized_inputs_and_output);
138
139 let polonius_liveness = if infcx.tcx.sess.opts.unstable_opts.polonius.is_next_enabled() {
140 Some(PoloniusLivenessContext::default())
141 } else {
142 None
143 };
144
145 let mut deferred_closure_requirements = Default::default();
146 let mut typeck = TypeChecker {
147 root_cx,
148 infcx,
149 last_span: body.span,
150 body,
151 promoted,
152 user_type_annotations: &body.user_type_annotations,
153 region_bound_pairs: ®ion_bound_pairs,
154 known_type_outlives_obligations: &known_type_outlives_obligations,
155 reported_errors: Default::default(),
156 universal_regions: &universal_region_relations.universal_regions,
157 location_table,
158 polonius_facts,
159 borrow_set,
160 constraints: &mut constraints,
161 deferred_closure_requirements: &mut deferred_closure_requirements,
162 polonius_liveness,
163 };
164
165 typeck.check_user_type_annotations();
166 typeck.visit_body(body);
167 typeck.equate_inputs_and_outputs(&normalized_inputs_and_output);
168 typeck.check_signature_annotation();
169
170 liveness::generate(&mut typeck, &location_map, move_data);
171
172 let polonius_context = typeck.polonius_liveness.take().map(|liveness_context| {
174 PoloniusContext::create_from_liveness(
175 liveness_context,
176 infcx.num_region_vars(),
177 typeck.constraints.liveness_constraints.points(),
178 )
179 });
180
181 if let Some(guar) = universal_region_relations.universal_regions.encountered_re_error() {
184 debug!("encountered an error region; removing constraints!");
185 constraints.outlives_constraints = Default::default();
186 constraints.type_tests = Default::default();
187 root_cx.set_tainted_by_errors(guar);
188 infcx.set_tainted_by_errors(guar);
189 }
190
191 MirTypeckResults {
192 constraints,
193 universal_region_relations,
194 region_bound_pairs,
195 known_type_outlives_obligations,
196 deferred_closure_requirements,
197 polonius_context,
198 }
199}
200
201#[track_caller]
202fn mirbug(tcx: TyCtxt<'_>, span: Span, msg: String) {
203 tcx.dcx().span_delayed_bug(span, msg);
207}
208
209enum FieldAccessError {
210 OutOfRange { field_count: usize },
211}
212
213struct TypeChecker<'a, 'tcx> {
218 root_cx: &'a mut BorrowCheckRootCtxt<'tcx>,
219 infcx: &'a BorrowckInferCtxt<'tcx>,
220 last_span: Span,
221 body: &'a Body<'tcx>,
222 promoted: &'a IndexSlice<Promoted, Body<'tcx>>,
225 user_type_annotations: &'a CanonicalUserTypeAnnotations<'tcx>,
228 region_bound_pairs: &'a RegionBoundPairs<'tcx>,
229 known_type_outlives_obligations: &'a [ty::PolyTypeOutlivesPredicate<'tcx>],
230 reported_errors: FxIndexSet<(Ty<'tcx>, Span)>,
231 universal_regions: &'a UniversalRegions<'tcx>,
232 location_table: &'a PoloniusLocationTable,
233 polonius_facts: &'a mut Option<PoloniusFacts>,
234 borrow_set: &'a BorrowSet<'tcx>,
235 constraints: &'a mut MirTypeckRegionConstraints<'tcx>,
236 deferred_closure_requirements: &'a mut DeferredClosureRequirements<'tcx>,
237 polonius_liveness: Option<PoloniusLivenessContext>,
239}
240
241pub(crate) struct MirTypeckResults<'tcx> {
244 pub(crate) constraints: MirTypeckRegionConstraints<'tcx>,
245 pub(crate) universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,
246 pub(crate) region_bound_pairs: Frozen<RegionBoundPairs<'tcx>>,
247 pub(crate) known_type_outlives_obligations: Frozen<Vec<ty::PolyTypeOutlivesPredicate<'tcx>>>,
248 pub(crate) deferred_closure_requirements: DeferredClosureRequirements<'tcx>,
249 pub(crate) polonius_context: Option<PoloniusContext>,
250}
251
252#[derive(Clone)] pub(crate) struct MirTypeckRegionConstraints<'tcx> {
256 pub(crate) placeholder_indices: PlaceholderIndices,
262
263 pub(crate) placeholder_index_to_region: IndexVec<PlaceholderIndex, ty::Region<'tcx>>,
269
270 pub(crate) liveness_constraints: LivenessValues,
278
279 pub(crate) outlives_constraints: OutlivesConstraintSet<'tcx>,
280
281 pub(crate) universe_causes: FxIndexMap<ty::UniverseIndex, UniverseInfo<'tcx>>,
282
283 pub(crate) type_tests: Vec<TypeTest<'tcx>>,
284}
285
286impl<'tcx> MirTypeckRegionConstraints<'tcx> {
287 pub(crate) fn placeholder_region(
290 &mut self,
291 infcx: &InferCtxt<'tcx>,
292 placeholder: ty::PlaceholderRegion,
293 ) -> ty::Region<'tcx> {
294 let placeholder_index = self.placeholder_indices.insert(placeholder);
295 match self.placeholder_index_to_region.get(placeholder_index) {
296 Some(&v) => v,
297 None => {
298 let origin = NllRegionVariableOrigin::Placeholder(placeholder);
299 let region = infcx.next_nll_region_var_in_universe(origin, placeholder.universe);
300 self.placeholder_index_to_region.push(region);
301 region
302 }
303 }
304 }
305}
306
307#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
312pub enum Locations {
313 All(Span),
349
350 Single(Location),
354}
355
356impl Locations {
357 pub fn from_location(&self) -> Option<Location> {
358 match self {
359 Locations::All(_) => None,
360 Locations::Single(from_location) => Some(*from_location),
361 }
362 }
363
364 pub fn span(&self, body: &Body<'_>) -> Span {
366 match self {
367 Locations::All(span) => *span,
368 Locations::Single(l) => body.source_info(*l).span,
369 }
370 }
371}
372
373impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
374 fn tcx(&self) -> TyCtxt<'tcx> {
375 self.infcx.tcx
376 }
377
378 fn body(&self) -> &Body<'tcx> {
379 self.body
380 }
381
382 fn unsized_feature_enabled(&self) -> bool {
383 self.tcx().features().unsized_fn_params()
384 }
385
386 #[instrument(skip(self), level = "debug")]
388 fn check_user_type_annotations(&mut self) {
389 debug!(?self.user_type_annotations);
390 let tcx = self.tcx();
391 for user_annotation in self.user_type_annotations {
392 let CanonicalUserTypeAnnotation { span, ref user_ty, inferred_ty } = *user_annotation;
393 let annotation = self.instantiate_canonical(span, user_ty);
394 if let ty::UserTypeKind::TypeOf(def, args) = annotation.kind
395 && let DefKind::InlineConst = tcx.def_kind(def)
396 {
397 assert!(annotation.bounds.is_empty());
398 self.check_inline_const(inferred_ty, def.expect_local(), args, span);
399 } else {
400 self.ascribe_user_type(inferred_ty, annotation, span);
401 }
402 }
403 }
404
405 #[instrument(skip(self, data), level = "debug")]
406 fn push_region_constraints(
407 &mut self,
408 locations: Locations,
409 category: ConstraintCategory<'tcx>,
410 data: &QueryRegionConstraints<'tcx>,
411 ) {
412 debug!("constraints generated: {:#?}", data);
413
414 constraint_conversion::ConstraintConversion::new(
415 self.infcx,
416 self.universal_regions,
417 self.region_bound_pairs,
418 self.known_type_outlives_obligations,
419 locations,
420 locations.span(self.body),
421 category,
422 self.constraints,
423 )
424 .convert_all(data);
425 }
426
427 fn sub_types(
429 &mut self,
430 sub: Ty<'tcx>,
431 sup: Ty<'tcx>,
432 locations: Locations,
433 category: ConstraintCategory<'tcx>,
434 ) -> Result<(), NoSolution> {
435 self.relate_types(sup, ty::Contravariant, sub, locations, category)
438 }
439
440 #[instrument(skip(self, category), level = "debug")]
441 fn eq_types(
442 &mut self,
443 expected: Ty<'tcx>,
444 found: Ty<'tcx>,
445 locations: Locations,
446 category: ConstraintCategory<'tcx>,
447 ) -> Result<(), NoSolution> {
448 self.relate_types(expected, ty::Invariant, found, locations, category)
449 }
450
451 #[instrument(skip(self), level = "debug")]
452 fn relate_type_and_user_type(
453 &mut self,
454 a: Ty<'tcx>,
455 v: ty::Variance,
456 user_ty: &UserTypeProjection,
457 locations: Locations,
458 category: ConstraintCategory<'tcx>,
459 ) -> Result<(), NoSolution> {
460 let annotated_type = self.user_type_annotations[user_ty.base].inferred_ty;
461 trace!(?annotated_type);
462 let mut curr_projected_ty = PlaceTy::from_ty(annotated_type);
463
464 let tcx = self.infcx.tcx;
465
466 for proj in &user_ty.projs {
467 if !self.infcx.next_trait_solver()
468 && let ty::Alias(ty::Opaque, ..) = curr_projected_ty.ty.kind()
469 {
470 return Ok(());
474 }
475 let projected_ty = curr_projected_ty.projection_ty_core(
476 tcx,
477 proj,
478 |ty| self.structurally_resolve(ty, locations),
479 |ty, variant_index, field, ()| PlaceTy::field_ty(tcx, ty, variant_index, field),
480 |_| unreachable!(),
481 );
482 curr_projected_ty = projected_ty;
483 }
484 trace!(?curr_projected_ty);
485
486 let a = self.normalize(a, locations);
489 let ty = self.normalize(curr_projected_ty.ty, locations);
490 self.relate_types(ty, v.xform(ty::Contravariant), a, locations, category)?;
491
492 Ok(())
493 }
494
495 fn check_promoted(&mut self, promoted_body: &'a Body<'tcx>, location: Location) {
496 let parent_body = mem::replace(&mut self.body, promoted_body);
501
502 let polonius_facts = &mut None;
505 let mut constraints = Default::default();
506 let mut liveness_constraints =
507 LivenessValues::without_specific_points(Rc::new(DenseLocationMap::new(promoted_body)));
508 let mut deferred_closure_requirements = Default::default();
509
510 let mut swap_constraints = |this: &mut Self| {
513 mem::swap(this.polonius_facts, polonius_facts);
514 mem::swap(&mut this.constraints.outlives_constraints, &mut constraints);
515 mem::swap(&mut this.constraints.liveness_constraints, &mut liveness_constraints);
516 mem::swap(this.deferred_closure_requirements, &mut deferred_closure_requirements);
517 };
518
519 swap_constraints(self);
520
521 self.visit_body(promoted_body);
522
523 self.body = parent_body;
524
525 swap_constraints(self);
527 let locations = location.to_locations();
528 for constraint in constraints.outlives().iter() {
529 let mut constraint = *constraint;
530 constraint.locations = locations;
531 if let ConstraintCategory::Return(_)
532 | ConstraintCategory::UseAsConst
533 | ConstraintCategory::UseAsStatic = constraint.category
534 {
535 constraint.category = ConstraintCategory::Boring;
538 }
539 self.constraints.outlives_constraints.push(constraint)
540 }
541
542 for (closure_def_id, args, _locations) in deferred_closure_requirements {
549 self.deferred_closure_requirements.push((closure_def_id, args, locations));
550 }
551
552 #[allow(rustc::potential_query_instability)]
559 for region in liveness_constraints.live_regions_unordered() {
560 self.constraints.liveness_constraints.add_location(region, location);
561 }
562 }
563
564 fn check_inline_const(
565 &mut self,
566 inferred_ty: Ty<'tcx>,
567 def_id: LocalDefId,
568 args: UserArgs<'tcx>,
569 span: Span,
570 ) {
571 assert!(args.user_self_ty.is_none());
572 let tcx = self.tcx();
573 let const_ty = tcx.type_of(def_id).instantiate(tcx, args.args);
574 if let Err(terr) =
575 self.eq_types(const_ty, inferred_ty, Locations::All(span), ConstraintCategory::Boring)
576 {
577 span_bug!(
578 span,
579 "bad inline const pattern: ({:?} = {:?}) {:?}",
580 const_ty,
581 inferred_ty,
582 terr
583 );
584 }
585 let args = self.infcx.resolve_vars_if_possible(args.args);
586 let predicates = self.prove_closure_bounds(tcx, def_id, args, Locations::All(span));
587 self.normalize_and_prove_instantiated_predicates(
588 def_id.to_def_id(),
589 predicates,
590 Locations::All(span),
591 );
592 }
593}
594
595impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
596 fn visit_span(&mut self, span: Span) {
597 if !span.is_dummy() {
598 debug!(?span);
599 self.last_span = span;
600 }
601 }
602
603 #[instrument(skip(self, body), level = "debug")]
604 fn visit_body(&mut self, body: &Body<'tcx>) {
605 debug_assert!(std::ptr::eq(self.body, body));
606
607 for (local, local_decl) in body.local_decls.iter_enumerated() {
608 self.visit_local_decl(local, local_decl);
609 }
610
611 for (block, block_data) in body.basic_blocks.iter_enumerated() {
612 let mut location = Location { block, statement_index: 0 };
613 for stmt in &block_data.statements {
614 self.visit_statement(stmt, location);
615 location.statement_index += 1;
616 }
617
618 self.visit_terminator(block_data.terminator(), location);
619 self.check_iscleanup(block_data);
620 }
621 }
622
623 #[instrument(skip(self), level = "debug")]
624 fn visit_statement(&mut self, stmt: &Statement<'tcx>, location: Location) {
625 self.super_statement(stmt, location);
626 let tcx = self.tcx();
627 match &stmt.kind {
628 StatementKind::Assign(box (place, rv)) => {
629 let category = match place.as_local() {
634 Some(RETURN_PLACE) => {
635 let defining_ty = &self.universal_regions.defining_ty;
636 if defining_ty.is_const() {
637 if tcx.is_static(defining_ty.def_id()) {
638 ConstraintCategory::UseAsStatic
639 } else {
640 ConstraintCategory::UseAsConst
641 }
642 } else {
643 ConstraintCategory::Return(ReturnConstraint::Normal)
644 }
645 }
646 Some(l)
647 if matches!(
648 self.body.local_decls[l].local_info(),
649 LocalInfo::AggregateTemp
650 ) =>
651 {
652 ConstraintCategory::Usage
653 }
654 Some(l) if !self.body.local_decls[l].is_user_variable() => {
655 ConstraintCategory::Boring
656 }
657 _ => ConstraintCategory::Assignment,
658 };
659 debug!(
660 "assignment category: {:?} {:?}",
661 category,
662 place.as_local().map(|l| &self.body.local_decls[l])
663 );
664
665 let place_ty = place.ty(self.body, tcx).ty;
666 debug!(?place_ty);
667 let place_ty = self.normalize(place_ty, location);
668 debug!("place_ty normalized: {:?}", place_ty);
669 let rv_ty = rv.ty(self.body, tcx);
670 debug!(?rv_ty);
671 let rv_ty = self.normalize(rv_ty, location);
672 debug!("normalized rv_ty: {:?}", rv_ty);
673 if let Err(terr) =
674 self.sub_types(rv_ty, place_ty, location.to_locations(), category)
675 {
676 span_mirbug!(
677 self,
678 stmt,
679 "bad assignment ({:?} = {:?}): {:?}",
680 place_ty,
681 rv_ty,
682 terr
683 );
684 }
685
686 if let Some(annotation_index) = self.rvalue_user_ty(rv)
687 && let Err(terr) = self.relate_type_and_user_type(
688 rv_ty,
689 ty::Invariant,
690 &UserTypeProjection { base: annotation_index, projs: vec![] },
691 location.to_locations(),
692 ConstraintCategory::TypeAnnotation(AnnotationSource::GenericArg),
693 )
694 {
695 let annotation = &self.user_type_annotations[annotation_index];
696 span_mirbug!(
697 self,
698 stmt,
699 "bad user type on rvalue ({:?} = {:?}): {:?}",
700 annotation,
701 rv_ty,
702 terr
703 );
704 }
705
706 if !self.unsized_feature_enabled() {
707 let trait_ref = ty::TraitRef::new(
708 tcx,
709 tcx.require_lang_item(LangItem::Sized, self.last_span),
710 [place_ty],
711 );
712 self.prove_trait_ref(
713 trait_ref,
714 location.to_locations(),
715 ConstraintCategory::SizedBound,
716 );
717 }
718 }
719 StatementKind::AscribeUserType(box (place, projection), variance) => {
720 let place_ty = place.ty(self.body, tcx).ty;
721 if let Err(terr) = self.relate_type_and_user_type(
722 place_ty,
723 *variance,
724 projection,
725 Locations::All(stmt.source_info.span),
726 ConstraintCategory::TypeAnnotation(AnnotationSource::Ascription),
727 ) {
728 let annotation = &self.user_type_annotations[projection.base];
729 span_mirbug!(
730 self,
731 stmt,
732 "bad type assert ({:?} <: {:?} with projections {:?}): {:?}",
733 place_ty,
734 annotation,
735 projection.projs,
736 terr
737 );
738 }
739 }
740 StatementKind::Intrinsic(box NonDivergingIntrinsic::Assume(..))
741 | StatementKind::FakeRead(..)
742 | StatementKind::StorageLive(..)
743 | StatementKind::StorageDead(..)
744 | StatementKind::Retag { .. }
745 | StatementKind::Coverage(..)
746 | StatementKind::ConstEvalCounter
747 | StatementKind::PlaceMention(..)
748 | StatementKind::BackwardIncompatibleDropHint { .. }
749 | StatementKind::Nop => {}
750 StatementKind::Intrinsic(box NonDivergingIntrinsic::CopyNonOverlapping(..))
751 | StatementKind::SetDiscriminant { .. } => {
752 bug!("Statement not allowed in this MIR phase")
753 }
754 }
755 }
756
757 #[instrument(skip(self), level = "debug")]
758 fn visit_terminator(&mut self, term: &Terminator<'tcx>, term_location: Location) {
759 self.super_terminator(term, term_location);
760 let tcx = self.tcx();
761 debug!("terminator kind: {:?}", term.kind);
762 match &term.kind {
763 TerminatorKind::Goto { .. }
764 | TerminatorKind::UnwindResume
765 | TerminatorKind::UnwindTerminate(_)
766 | TerminatorKind::Return
767 | TerminatorKind::CoroutineDrop
768 | TerminatorKind::Unreachable
769 | TerminatorKind::Drop { .. }
770 | TerminatorKind::FalseEdge { .. }
771 | TerminatorKind::FalseUnwind { .. }
772 | TerminatorKind::InlineAsm { .. } => {
773 }
775
776 TerminatorKind::SwitchInt { discr, .. } => {
777 let switch_ty = discr.ty(self.body, tcx);
778 if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
779 span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
780 }
781 }
783 TerminatorKind::Call { func, args, .. }
784 | TerminatorKind::TailCall { func, args, .. } => {
785 let (call_source, destination, is_diverging) = match term.kind {
786 TerminatorKind::Call { call_source, destination, target, .. } => {
787 (call_source, destination, target.is_none())
788 }
789 TerminatorKind::TailCall { .. } => {
790 (CallSource::Normal, RETURN_PLACE.into(), false)
791 }
792 _ => unreachable!(),
793 };
794
795 let func_ty = func.ty(self.body, tcx);
796 debug!("func_ty.kind: {:?}", func_ty.kind());
797
798 let sig = match func_ty.kind() {
799 ty::FnDef(..) | ty::FnPtr(..) => func_ty.fn_sig(tcx),
800 _ => {
801 span_mirbug!(self, term, "call to non-function {:?}", func_ty);
802 return;
803 }
804 };
805 let (unnormalized_sig, map) = tcx.instantiate_bound_regions(sig, |br| {
806 use crate::renumber::RegionCtxt;
807
808 let region_ctxt_fn = || {
809 let reg_info = match br.kind {
810 ty::BoundRegionKind::Anon => sym::anon,
811 ty::BoundRegionKind::Named(def_id) => tcx.item_name(def_id),
812 ty::BoundRegionKind::ClosureEnv => sym::env,
813 ty::BoundRegionKind::NamedAnon(_) => {
814 bug!("only used for pretty printing")
815 }
816 };
817
818 RegionCtxt::LateBound(reg_info)
819 };
820
821 self.infcx.next_region_var(
822 RegionVariableOrigin::BoundRegion(
823 term.source_info.span,
824 br.kind,
825 BoundRegionConversionTime::FnCall,
826 ),
827 region_ctxt_fn,
828 )
829 });
830 debug!(?unnormalized_sig);
831 self.prove_predicates(
840 unnormalized_sig.inputs_and_output.iter().map(|ty| {
841 ty::Binder::dummy(ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(
842 ty.into(),
843 )))
844 }),
845 term_location.to_locations(),
846 ConstraintCategory::Boring,
847 );
848
849 let sig = self.deeply_normalize(unnormalized_sig, term_location);
850 if sig != unnormalized_sig {
854 self.prove_predicates(
855 sig.inputs_and_output.iter().map(|ty| {
856 ty::Binder::dummy(ty::PredicateKind::Clause(
857 ty::ClauseKind::WellFormed(ty.into()),
858 ))
859 }),
860 term_location.to_locations(),
861 ConstraintCategory::Boring,
862 );
863 }
864
865 self.check_call_dest(term, &sig, destination, is_diverging, term_location);
866
867 for &late_bound_region in map.values() {
875 let region_vid = self.universal_regions.to_region_vid(late_bound_region);
876 self.constraints.liveness_constraints.add_location(region_vid, term_location);
877 }
878
879 self.check_call_inputs(term, func, &sig, args, term_location, call_source);
880 }
881 TerminatorKind::Assert { cond, msg, .. } => {
882 let cond_ty = cond.ty(self.body, tcx);
883 if cond_ty != tcx.types.bool {
884 span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
885 }
886
887 if let AssertKind::BoundsCheck { len, index } = &**msg {
888 if len.ty(self.body, tcx) != tcx.types.usize {
889 span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
890 }
891 if index.ty(self.body, tcx) != tcx.types.usize {
892 span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
893 }
894 }
895 }
896 TerminatorKind::Yield { value, resume_arg, .. } => {
897 match self.body.yield_ty() {
898 None => span_mirbug!(self, term, "yield in non-coroutine"),
899 Some(ty) => {
900 let value_ty = value.ty(self.body, tcx);
901 if let Err(terr) = self.sub_types(
902 value_ty,
903 ty,
904 term_location.to_locations(),
905 ConstraintCategory::Yield,
906 ) {
907 span_mirbug!(
908 self,
909 term,
910 "type of yield value is {:?}, but the yield type is {:?}: {:?}",
911 value_ty,
912 ty,
913 terr
914 );
915 }
916 }
917 }
918
919 match self.body.resume_ty() {
920 None => span_mirbug!(self, term, "yield in non-coroutine"),
921 Some(ty) => {
922 let resume_ty = resume_arg.ty(self.body, tcx);
923 if let Err(terr) = self.sub_types(
924 ty,
925 resume_ty.ty,
926 term_location.to_locations(),
927 ConstraintCategory::Yield,
928 ) {
929 span_mirbug!(
930 self,
931 term,
932 "type of resume place is {:?}, but the resume type is {:?}: {:?}",
933 resume_ty,
934 ty,
935 terr
936 );
937 }
938 }
939 }
940 }
941 }
942 }
943
944 fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) {
945 self.super_local_decl(local, local_decl);
946
947 for user_ty in
948 local_decl.user_ty.as_deref().into_iter().flat_map(UserTypeProjections::projections)
949 {
950 let span = self.user_type_annotations[user_ty.base].span;
951
952 let ty = if local_decl.is_nonref_binding() {
953 local_decl.ty
954 } else if let &ty::Ref(_, rty, _) = local_decl.ty.kind() {
955 rty
959 } else {
960 bug!("{:?} with ref binding has wrong type {}", local, local_decl.ty);
961 };
962
963 if let Err(terr) = self.relate_type_and_user_type(
964 ty,
965 ty::Invariant,
966 user_ty,
967 Locations::All(span),
968 ConstraintCategory::TypeAnnotation(AnnotationSource::Declaration),
969 ) {
970 span_mirbug!(
971 self,
972 local,
973 "bad user type on variable {:?}: {:?} != {:?} ({:?})",
974 local,
975 local_decl.ty,
976 local_decl.user_ty,
977 terr,
978 );
979 }
980 }
981
982 if !self.unsized_feature_enabled() {
985 match self.body.local_kind(local) {
986 LocalKind::ReturnPointer | LocalKind::Arg => {
987 return;
994 }
995 LocalKind::Temp => {
996 let span = local_decl.source_info.span;
997 let ty = local_decl.ty;
998 self.ensure_place_sized(ty, span);
999 }
1000 }
1001 }
1002 }
1003
1004 #[instrument(skip(self), level = "debug")]
1005 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
1006 self.super_rvalue(rvalue, location);
1007 let tcx = self.tcx();
1008 let span = self.body.source_info(location).span;
1009 match rvalue {
1010 Rvalue::Aggregate(ak, ops) => self.check_aggregate_rvalue(rvalue, ak, ops, location),
1011
1012 Rvalue::Repeat(operand, len) => {
1013 let array_ty = rvalue.ty(self.body.local_decls(), tcx);
1014 self.prove_predicate(
1015 ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(array_ty.into())),
1016 Locations::Single(location),
1017 ConstraintCategory::Boring,
1018 );
1019
1020 if len.try_to_target_usize(tcx).is_none_or(|len| len > 1) {
1025 match operand {
1026 Operand::Copy(..) | Operand::Constant(..) => {
1027 }
1030 Operand::Move(place) => {
1031 let ty = place.ty(self.body, tcx).ty;
1033 let trait_ref = ty::TraitRef::new(
1034 tcx,
1035 tcx.require_lang_item(LangItem::Copy, span),
1036 [ty],
1037 );
1038
1039 self.prove_trait_ref(
1040 trait_ref,
1041 Locations::Single(location),
1042 ConstraintCategory::CopyBound,
1043 );
1044 }
1045 }
1046 }
1047 }
1048
1049 &Rvalue::NullaryOp(NullOp::RuntimeChecks(_)) => {}
1050
1051 Rvalue::ShallowInitBox(_operand, ty) => {
1052 let trait_ref =
1053 ty::TraitRef::new(tcx, tcx.require_lang_item(LangItem::Sized, span), [*ty]);
1054
1055 self.prove_trait_ref(
1056 trait_ref,
1057 location.to_locations(),
1058 ConstraintCategory::SizedBound,
1059 );
1060 }
1061
1062 Rvalue::Cast(cast_kind, op, ty) => {
1063 match *cast_kind {
1064 CastKind::PointerCoercion(PointerCoercion::ReifyFnPointer, coercion_source) => {
1065 let is_implicit_coercion = coercion_source == CoercionSource::Implicit;
1066 let src_ty = op.ty(self.body, tcx);
1067 let mut src_sig = src_ty.fn_sig(tcx);
1068 if let ty::FnDef(def_id, _) = src_ty.kind()
1069 && let ty::FnPtr(_, target_hdr) = *ty.kind()
1070 && tcx.codegen_fn_attrs(def_id).safe_target_features
1071 && target_hdr.safety.is_safe()
1072 && let Some(safe_sig) = tcx.adjust_target_feature_sig(
1073 *def_id,
1074 src_sig,
1075 self.body.source.def_id(),
1076 )
1077 {
1078 src_sig = safe_sig;
1079 }
1080
1081 if src_sig.has_bound_regions()
1096 && let ty::FnPtr(target_fn_tys, target_hdr) = *ty.kind()
1097 && let target_sig = target_fn_tys.with(target_hdr)
1098 && let Some(target_sig) = target_sig.no_bound_vars()
1099 {
1100 let src_sig = self.infcx.instantiate_binder_with_fresh_vars(
1101 span,
1102 BoundRegionConversionTime::HigherRankedType,
1103 src_sig,
1104 );
1105 let src_ty = Ty::new_fn_ptr(self.tcx(), ty::Binder::dummy(src_sig));
1106 self.prove_predicate(
1107 ty::ClauseKind::WellFormed(src_ty.into()),
1108 location.to_locations(),
1109 ConstraintCategory::Cast { is_implicit_coercion, unsize_to: None },
1110 );
1111
1112 let src_ty = self.normalize(src_ty, location);
1113 if let Err(terr) = self.sub_types(
1114 src_ty,
1115 *ty,
1116 location.to_locations(),
1117 ConstraintCategory::Cast { is_implicit_coercion, unsize_to: None },
1118 ) {
1119 span_mirbug!(
1120 self,
1121 rvalue,
1122 "equating {:?} with {:?} yields {:?}",
1123 target_sig,
1124 src_sig,
1125 terr
1126 );
1127 };
1128 }
1129
1130 let src_ty = Ty::new_fn_ptr(tcx, src_sig);
1131 self.prove_predicate(
1136 ty::ClauseKind::WellFormed(src_ty.into()),
1137 location.to_locations(),
1138 ConstraintCategory::Cast { is_implicit_coercion, unsize_to: None },
1139 );
1140
1141 let src_ty = self.normalize(src_ty, location);
1147 if let Err(terr) = self.sub_types(
1148 src_ty,
1149 *ty,
1150 location.to_locations(),
1151 ConstraintCategory::Cast { is_implicit_coercion, unsize_to: None },
1152 ) {
1153 span_mirbug!(
1154 self,
1155 rvalue,
1156 "equating {:?} with {:?} yields {:?}",
1157 src_ty,
1158 ty,
1159 terr
1160 );
1161 }
1162 }
1163
1164 CastKind::PointerCoercion(
1165 PointerCoercion::ClosureFnPointer(safety),
1166 coercion_source,
1167 ) => {
1168 let sig = match op.ty(self.body, tcx).kind() {
1169 ty::Closure(_, args) => args.as_closure().sig(),
1170 _ => bug!(),
1171 };
1172 let ty_fn_ptr_from =
1173 Ty::new_fn_ptr(tcx, tcx.signature_unclosure(sig, safety));
1174
1175 let is_implicit_coercion = coercion_source == CoercionSource::Implicit;
1176 if let Err(terr) = self.sub_types(
1177 ty_fn_ptr_from,
1178 *ty,
1179 location.to_locations(),
1180 ConstraintCategory::Cast { is_implicit_coercion, unsize_to: None },
1181 ) {
1182 span_mirbug!(
1183 self,
1184 rvalue,
1185 "equating {:?} with {:?} yields {:?}",
1186 ty_fn_ptr_from,
1187 ty,
1188 terr
1189 );
1190 }
1191 }
1192
1193 CastKind::PointerCoercion(
1194 PointerCoercion::UnsafeFnPointer,
1195 coercion_source,
1196 ) => {
1197 let fn_sig = op.ty(self.body, tcx).fn_sig(tcx);
1198
1199 let fn_sig = self.normalize(fn_sig, location);
1205
1206 let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
1207
1208 let is_implicit_coercion = coercion_source == CoercionSource::Implicit;
1209 if let Err(terr) = self.sub_types(
1210 ty_fn_ptr_from,
1211 *ty,
1212 location.to_locations(),
1213 ConstraintCategory::Cast { is_implicit_coercion, unsize_to: None },
1214 ) {
1215 span_mirbug!(
1216 self,
1217 rvalue,
1218 "equating {:?} with {:?} yields {:?}",
1219 ty_fn_ptr_from,
1220 ty,
1221 terr
1222 );
1223 }
1224 }
1225
1226 CastKind::PointerCoercion(PointerCoercion::Unsize, coercion_source) => {
1227 let &ty = ty;
1228 let trait_ref = ty::TraitRef::new(
1229 tcx,
1230 tcx.require_lang_item(LangItem::CoerceUnsized, span),
1231 [op.ty(self.body, tcx), ty],
1232 );
1233
1234 let is_implicit_coercion = coercion_source == CoercionSource::Implicit;
1235 let unsize_to = fold_regions(tcx, ty, |r, _| {
1236 if let ty::ReVar(_) = r.kind() { tcx.lifetimes.re_erased } else { r }
1237 });
1238 self.prove_trait_ref(
1239 trait_ref,
1240 location.to_locations(),
1241 ConstraintCategory::Cast {
1242 is_implicit_coercion,
1243 unsize_to: Some(unsize_to),
1244 },
1245 );
1246 }
1247
1248 CastKind::PointerCoercion(
1249 PointerCoercion::MutToConstPointer,
1250 coercion_source,
1251 ) => {
1252 let ty::RawPtr(ty_from, hir::Mutability::Mut) =
1253 op.ty(self.body, tcx).kind()
1254 else {
1255 span_mirbug!(self, rvalue, "unexpected base type for cast {:?}", ty,);
1256 return;
1257 };
1258 let ty::RawPtr(ty_to, hir::Mutability::Not) = ty.kind() else {
1259 span_mirbug!(self, rvalue, "unexpected target type for cast {:?}", ty,);
1260 return;
1261 };
1262 let is_implicit_coercion = coercion_source == CoercionSource::Implicit;
1263 if let Err(terr) = self.sub_types(
1264 *ty_from,
1265 *ty_to,
1266 location.to_locations(),
1267 ConstraintCategory::Cast { is_implicit_coercion, unsize_to: None },
1268 ) {
1269 span_mirbug!(
1270 self,
1271 rvalue,
1272 "relating {:?} with {:?} yields {:?}",
1273 ty_from,
1274 ty_to,
1275 terr
1276 );
1277 }
1278 }
1279
1280 CastKind::PointerCoercion(PointerCoercion::ArrayToPointer, coercion_source) => {
1281 let ty_from = op.ty(self.body, tcx);
1282
1283 let opt_ty_elem_mut = match ty_from.kind() {
1284 ty::RawPtr(array_ty, array_mut) => match array_ty.kind() {
1285 ty::Array(ty_elem, _) => Some((ty_elem, *array_mut)),
1286 _ => None,
1287 },
1288 _ => None,
1289 };
1290
1291 let Some((ty_elem, ty_mut)) = opt_ty_elem_mut else {
1292 span_mirbug!(
1293 self,
1294 rvalue,
1295 "ArrayToPointer cast from unexpected type {:?}",
1296 ty_from,
1297 );
1298 return;
1299 };
1300
1301 let (ty_to, ty_to_mut) = match ty.kind() {
1302 ty::RawPtr(ty_to, ty_to_mut) => (ty_to, *ty_to_mut),
1303 _ => {
1304 span_mirbug!(
1305 self,
1306 rvalue,
1307 "ArrayToPointer cast to unexpected type {:?}",
1308 ty,
1309 );
1310 return;
1311 }
1312 };
1313
1314 if ty_to_mut.is_mut() && ty_mut.is_not() {
1315 span_mirbug!(
1316 self,
1317 rvalue,
1318 "ArrayToPointer cast from const {:?} to mut {:?}",
1319 ty,
1320 ty_to
1321 );
1322 return;
1323 }
1324
1325 let is_implicit_coercion = coercion_source == CoercionSource::Implicit;
1326 if let Err(terr) = self.sub_types(
1327 *ty_elem,
1328 *ty_to,
1329 location.to_locations(),
1330 ConstraintCategory::Cast { is_implicit_coercion, unsize_to: None },
1331 ) {
1332 span_mirbug!(
1333 self,
1334 rvalue,
1335 "relating {:?} with {:?} yields {:?}",
1336 ty_elem,
1337 ty_to,
1338 terr
1339 )
1340 }
1341 }
1342
1343 CastKind::PointerExposeProvenance => {
1344 let ty_from = op.ty(self.body, tcx);
1345 let cast_ty_from = CastTy::from_ty(ty_from);
1346 let cast_ty_to = CastTy::from_ty(*ty);
1347 match (cast_ty_from, cast_ty_to) {
1348 (Some(CastTy::Ptr(_) | CastTy::FnPtr), Some(CastTy::Int(_))) => (),
1349 _ => {
1350 span_mirbug!(
1351 self,
1352 rvalue,
1353 "Invalid PointerExposeProvenance cast {:?} -> {:?}",
1354 ty_from,
1355 ty
1356 )
1357 }
1358 }
1359 }
1360
1361 CastKind::PointerWithExposedProvenance => {
1362 let ty_from = op.ty(self.body, tcx);
1363 let cast_ty_from = CastTy::from_ty(ty_from);
1364 let cast_ty_to = CastTy::from_ty(*ty);
1365 match (cast_ty_from, cast_ty_to) {
1366 (Some(CastTy::Int(_)), Some(CastTy::Ptr(_))) => (),
1367 _ => {
1368 span_mirbug!(
1369 self,
1370 rvalue,
1371 "Invalid PointerWithExposedProvenance cast {:?} -> {:?}",
1372 ty_from,
1373 ty
1374 )
1375 }
1376 }
1377 }
1378 CastKind::IntToInt => {
1379 let ty_from = op.ty(self.body, tcx);
1380 let cast_ty_from = CastTy::from_ty(ty_from);
1381 let cast_ty_to = CastTy::from_ty(*ty);
1382 match (cast_ty_from, cast_ty_to) {
1383 (Some(CastTy::Int(_)), Some(CastTy::Int(_))) => (),
1384 _ => {
1385 span_mirbug!(
1386 self,
1387 rvalue,
1388 "Invalid IntToInt cast {:?} -> {:?}",
1389 ty_from,
1390 ty
1391 )
1392 }
1393 }
1394 }
1395 CastKind::IntToFloat => {
1396 let ty_from = op.ty(self.body, tcx);
1397 let cast_ty_from = CastTy::from_ty(ty_from);
1398 let cast_ty_to = CastTy::from_ty(*ty);
1399 match (cast_ty_from, cast_ty_to) {
1400 (Some(CastTy::Int(_)), Some(CastTy::Float)) => (),
1401 _ => {
1402 span_mirbug!(
1403 self,
1404 rvalue,
1405 "Invalid IntToFloat cast {:?} -> {:?}",
1406 ty_from,
1407 ty
1408 )
1409 }
1410 }
1411 }
1412 CastKind::FloatToInt => {
1413 let ty_from = op.ty(self.body, tcx);
1414 let cast_ty_from = CastTy::from_ty(ty_from);
1415 let cast_ty_to = CastTy::from_ty(*ty);
1416 match (cast_ty_from, cast_ty_to) {
1417 (Some(CastTy::Float), Some(CastTy::Int(_))) => (),
1418 _ => {
1419 span_mirbug!(
1420 self,
1421 rvalue,
1422 "Invalid FloatToInt cast {:?} -> {:?}",
1423 ty_from,
1424 ty
1425 )
1426 }
1427 }
1428 }
1429 CastKind::FloatToFloat => {
1430 let ty_from = op.ty(self.body, tcx);
1431 let cast_ty_from = CastTy::from_ty(ty_from);
1432 let cast_ty_to = CastTy::from_ty(*ty);
1433 match (cast_ty_from, cast_ty_to) {
1434 (Some(CastTy::Float), Some(CastTy::Float)) => (),
1435 _ => {
1436 span_mirbug!(
1437 self,
1438 rvalue,
1439 "Invalid FloatToFloat cast {:?} -> {:?}",
1440 ty_from,
1441 ty
1442 )
1443 }
1444 }
1445 }
1446 CastKind::FnPtrToPtr => {
1447 let ty_from = op.ty(self.body, tcx);
1448 let cast_ty_from = CastTy::from_ty(ty_from);
1449 let cast_ty_to = CastTy::from_ty(*ty);
1450 match (cast_ty_from, cast_ty_to) {
1451 (Some(CastTy::FnPtr), Some(CastTy::Ptr(_))) => (),
1452 _ => {
1453 span_mirbug!(
1454 self,
1455 rvalue,
1456 "Invalid FnPtrToPtr cast {:?} -> {:?}",
1457 ty_from,
1458 ty
1459 )
1460 }
1461 }
1462 }
1463 CastKind::PtrToPtr => {
1464 let ty_from = op.ty(self.body, tcx);
1465 let Some(CastTy::Ptr(src)) = CastTy::from_ty(ty_from) else {
1466 unreachable!();
1467 };
1468 let Some(CastTy::Ptr(dst)) = CastTy::from_ty(*ty) else {
1469 unreachable!();
1470 };
1471
1472 if self.infcx.type_is_sized_modulo_regions(self.infcx.param_env, dst.ty) {
1473 let trait_ref = ty::TraitRef::new(
1479 tcx,
1480 tcx.require_lang_item(LangItem::Sized, self.last_span),
1481 [dst.ty],
1482 );
1483 self.prove_trait_ref(
1484 trait_ref,
1485 location.to_locations(),
1486 ConstraintCategory::Cast {
1487 is_implicit_coercion: true,
1488 unsize_to: None,
1489 },
1490 );
1491 } else if let ty::Dynamic(src_tty, _src_lt) =
1492 *self.struct_tail(src.ty, location).kind()
1493 && let ty::Dynamic(dst_tty, dst_lt) =
1494 *self.struct_tail(dst.ty, location).kind()
1495 && src_tty.principal().is_some()
1496 && dst_tty.principal().is_some()
1497 {
1498 let src_obj = Ty::new_dynamic(
1508 tcx,
1509 tcx.mk_poly_existential_predicates(
1510 &src_tty.without_auto_traits().collect::<Vec<_>>(),
1511 ),
1512 dst_lt,
1515 );
1516 let dst_obj = Ty::new_dynamic(
1517 tcx,
1518 tcx.mk_poly_existential_predicates(
1519 &dst_tty.without_auto_traits().collect::<Vec<_>>(),
1520 ),
1521 dst_lt,
1522 );
1523
1524 debug!(?src_tty, ?dst_tty, ?src_obj, ?dst_obj);
1525
1526 self.sub_types(
1527 src_obj,
1528 dst_obj,
1529 location.to_locations(),
1530 ConstraintCategory::Cast {
1531 is_implicit_coercion: false,
1532 unsize_to: None,
1533 },
1534 )
1535 .unwrap();
1536 }
1537 }
1538 CastKind::Transmute => {
1539 let ty_from = op.ty(self.body, tcx);
1540 match ty_from.kind() {
1541 ty::Pat(base, _) if base == ty => {}
1542 _ => span_mirbug!(
1543 self,
1544 rvalue,
1545 "Unexpected CastKind::Transmute {ty_from:?} -> {ty:?}, which is not permitted in Analysis MIR",
1546 ),
1547 }
1548 }
1549 CastKind::Subtype => {
1550 bug!("CastKind::Subtype shouldn't exist in borrowck")
1551 }
1552 }
1553 }
1554
1555 Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
1556 self.add_reborrow_constraint(location, *region, borrowed_place);
1557 }
1558
1559 Rvalue::BinaryOp(
1560 BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge,
1561 box (left, right),
1562 ) => {
1563 let ty_left = left.ty(self.body, tcx);
1564 match ty_left.kind() {
1565 ty::RawPtr(_, _) | ty::FnPtr(..) => {
1567 let ty_right = right.ty(self.body, tcx);
1568 let common_ty =
1569 self.infcx.next_ty_var(self.body.source_info(location).span);
1570 self.sub_types(
1571 ty_left,
1572 common_ty,
1573 location.to_locations(),
1574 ConstraintCategory::CallArgument(None),
1575 )
1576 .unwrap_or_else(|err| {
1577 bug!("Could not equate type variable with {:?}: {:?}", ty_left, err)
1578 });
1579 if let Err(terr) = self.sub_types(
1580 ty_right,
1581 common_ty,
1582 location.to_locations(),
1583 ConstraintCategory::CallArgument(None),
1584 ) {
1585 span_mirbug!(
1586 self,
1587 rvalue,
1588 "unexpected comparison types {:?} and {:?} yields {:?}",
1589 ty_left,
1590 ty_right,
1591 terr
1592 )
1593 }
1594 }
1595 ty::Int(_) | ty::Uint(_) | ty::Bool | ty::Char | ty::Float(_)
1598 if ty_left == right.ty(self.body, tcx) => {}
1599 _ => span_mirbug!(
1602 self,
1603 rvalue,
1604 "unexpected comparison types {:?} and {:?}",
1605 ty_left,
1606 right.ty(self.body, tcx)
1607 ),
1608 }
1609 }
1610
1611 Rvalue::WrapUnsafeBinder(op, ty) => {
1612 let operand_ty = op.ty(self.body, self.tcx());
1613 let ty::UnsafeBinder(binder_ty) = *ty.kind() else {
1614 unreachable!();
1615 };
1616 let expected_ty = self.infcx.instantiate_binder_with_fresh_vars(
1617 self.body().source_info(location).span,
1618 BoundRegionConversionTime::HigherRankedType,
1619 binder_ty.into(),
1620 );
1621 self.sub_types(
1622 operand_ty,
1623 expected_ty,
1624 location.to_locations(),
1625 ConstraintCategory::Boring,
1626 )
1627 .unwrap();
1628 }
1629
1630 Rvalue::Use(_)
1631 | Rvalue::UnaryOp(_, _)
1632 | Rvalue::CopyForDeref(_)
1633 | Rvalue::BinaryOp(..)
1634 | Rvalue::RawPtr(..)
1635 | Rvalue::ThreadLocalRef(..)
1636 | Rvalue::Discriminant(..) => {}
1637 }
1638 }
1639
1640 #[instrument(level = "debug", skip(self))]
1641 fn visit_operand(&mut self, op: &Operand<'tcx>, location: Location) {
1642 self.super_operand(op, location);
1643 if let Operand::Constant(constant) = op {
1644 let maybe_uneval = match constant.const_ {
1645 Const::Val(..) | Const::Ty(_, _) => None,
1646 Const::Unevaluated(uv, _) => Some(uv),
1647 };
1648
1649 if let Some(uv) = maybe_uneval {
1650 if uv.promoted.is_none() {
1651 let tcx = self.tcx();
1652 let def_id = uv.def;
1653 if tcx.def_kind(def_id) == DefKind::InlineConst {
1654 let def_id = def_id.expect_local();
1655 let predicates = self.prove_closure_bounds(
1656 tcx,
1657 def_id,
1658 uv.args,
1659 location.to_locations(),
1660 );
1661 self.normalize_and_prove_instantiated_predicates(
1662 def_id.to_def_id(),
1663 predicates,
1664 location.to_locations(),
1665 );
1666 }
1667 }
1668 }
1669 }
1670 }
1671
1672 #[instrument(level = "debug", skip(self))]
1673 fn visit_const_operand(&mut self, constant: &ConstOperand<'tcx>, location: Location) {
1674 self.super_const_operand(constant, location);
1675 let ty = constant.const_.ty();
1676
1677 self.infcx.tcx.for_each_free_region(&ty, |live_region| {
1678 let live_region_vid = self.universal_regions.to_region_vid(live_region);
1679 self.constraints.liveness_constraints.add_location(live_region_vid, location);
1680 });
1681
1682 let locations = location.to_locations();
1683 if let Some(annotation_index) = constant.user_ty {
1684 if let Err(terr) = self.relate_type_and_user_type(
1685 constant.const_.ty(),
1686 ty::Invariant,
1687 &UserTypeProjection { base: annotation_index, projs: vec![] },
1688 locations,
1689 ConstraintCategory::TypeAnnotation(AnnotationSource::GenericArg),
1690 ) {
1691 let annotation = &self.user_type_annotations[annotation_index];
1692 span_mirbug!(
1693 self,
1694 constant,
1695 "bad constant user type {:?} vs {:?}: {:?}",
1696 annotation,
1697 constant.const_.ty(),
1698 terr,
1699 );
1700 }
1701 } else {
1702 let tcx = self.tcx();
1703 let maybe_uneval = match constant.const_ {
1704 Const::Ty(_, ct) => match ct.kind() {
1705 ty::ConstKind::Unevaluated(uv) => {
1706 Some(UnevaluatedConst { def: uv.def, args: uv.args, promoted: None })
1707 }
1708 _ => None,
1709 },
1710 Const::Unevaluated(uv, _) => Some(uv),
1711 _ => None,
1712 };
1713
1714 if let Some(uv) = maybe_uneval {
1715 if let Some(promoted) = uv.promoted {
1716 let promoted_body = &self.promoted[promoted];
1717 self.check_promoted(promoted_body, location);
1718 let promoted_ty = promoted_body.return_ty();
1719 if let Err(terr) =
1720 self.eq_types(ty, promoted_ty, locations, ConstraintCategory::Boring)
1721 {
1722 span_mirbug!(
1723 self,
1724 promoted,
1725 "bad promoted type ({:?}: {:?}): {:?}",
1726 ty,
1727 promoted_ty,
1728 terr
1729 );
1730 };
1731 } else {
1732 self.ascribe_user_type(
1733 constant.const_.ty(),
1734 ty::UserType::new(ty::UserTypeKind::TypeOf(
1735 uv.def,
1736 UserArgs { args: uv.args, user_self_ty: None },
1737 )),
1738 locations.span(self.body),
1739 );
1740 }
1741 } else if let Some(static_def_id) = constant.check_static_ptr(tcx) {
1742 let unnormalized_ty = tcx.type_of(static_def_id).instantiate_identity();
1743 let normalized_ty = self.normalize(unnormalized_ty, locations);
1744 let literal_ty = constant.const_.ty().builtin_deref(true).unwrap();
1745
1746 if let Err(terr) =
1747 self.eq_types(literal_ty, normalized_ty, locations, ConstraintCategory::Boring)
1748 {
1749 span_mirbug!(self, constant, "bad static type {:?} ({:?})", constant, terr);
1750 }
1751 } else if let Const::Ty(_, ct) = constant.const_
1752 && let ty::ConstKind::Param(p) = ct.kind()
1753 {
1754 let body_def_id = self.universal_regions.defining_ty.def_id();
1755 let const_param = tcx.generics_of(body_def_id).const_param(p, tcx);
1756 self.ascribe_user_type(
1757 constant.const_.ty(),
1758 ty::UserType::new(ty::UserTypeKind::TypeOf(
1759 const_param.def_id,
1760 UserArgs {
1761 args: self.universal_regions.defining_ty.args(),
1762 user_self_ty: None,
1763 },
1764 )),
1765 locations.span(self.body),
1766 );
1767 }
1768
1769 if let ty::FnDef(def_id, args) = *constant.const_.ty().kind() {
1770 let instantiated_predicates = tcx.predicates_of(def_id).instantiate(tcx, args);
1771 self.normalize_and_prove_instantiated_predicates(
1772 def_id,
1773 instantiated_predicates,
1774 locations,
1775 );
1776
1777 assert_eq!(tcx.trait_impl_of_assoc(def_id), None);
1778 self.prove_predicates(
1779 args.types().map(|ty| ty::ClauseKind::WellFormed(ty.into())),
1780 locations,
1781 ConstraintCategory::Boring,
1782 );
1783 }
1784 }
1785 }
1786
1787 fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
1788 self.super_place(place, context, location);
1789 let tcx = self.tcx();
1790 let place_ty = place.ty(self.body, tcx);
1791 if let PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) = context {
1792 let trait_ref = ty::TraitRef::new(
1793 tcx,
1794 tcx.require_lang_item(LangItem::Copy, self.last_span),
1795 [place_ty.ty],
1796 );
1797
1798 self.prove_trait_ref(trait_ref, location.to_locations(), ConstraintCategory::CopyBound);
1810 }
1811 }
1812
1813 fn visit_projection_elem(
1814 &mut self,
1815 place: PlaceRef<'tcx>,
1816 elem: PlaceElem<'tcx>,
1817 context: PlaceContext,
1818 location: Location,
1819 ) {
1820 let tcx = self.tcx();
1821 let base_ty = place.ty(self.body(), tcx);
1822 match elem {
1823 ProjectionElem::Deref
1826 | ProjectionElem::Index(_)
1827 | ProjectionElem::ConstantIndex { .. }
1828 | ProjectionElem::Subslice { .. }
1829 | ProjectionElem::Downcast(..) => {}
1830 ProjectionElem::Field(field, fty) => {
1831 let fty = self.normalize(fty, location);
1832 let ty = PlaceTy::field_ty(tcx, base_ty.ty, base_ty.variant_index, field);
1833 let ty = self.normalize(ty, location);
1834 debug!(?fty, ?ty);
1835
1836 if let Err(terr) = self.relate_types(
1837 ty,
1838 context.ambient_variance(),
1839 fty,
1840 location.to_locations(),
1841 ConstraintCategory::Boring,
1842 ) {
1843 span_mirbug!(self, place, "bad field access ({:?}: {:?}): {:?}", ty, fty, terr);
1844 }
1845 }
1846 ProjectionElem::OpaqueCast(ty) => {
1847 let ty = self.normalize(ty, location);
1848 self.relate_types(
1849 ty,
1850 context.ambient_variance(),
1851 base_ty.ty,
1852 location.to_locations(),
1853 ConstraintCategory::TypeAnnotation(AnnotationSource::OpaqueCast),
1854 )
1855 .unwrap();
1856 }
1857 ProjectionElem::UnwrapUnsafeBinder(ty) => {
1858 let ty::UnsafeBinder(binder_ty) = *base_ty.ty.kind() else {
1859 unreachable!();
1860 };
1861 let found_ty = self.infcx.instantiate_binder_with_fresh_vars(
1862 self.body.source_info(location).span,
1863 BoundRegionConversionTime::HigherRankedType,
1864 binder_ty.into(),
1865 );
1866 self.relate_types(
1867 ty,
1868 context.ambient_variance(),
1869 found_ty,
1870 location.to_locations(),
1871 ConstraintCategory::Boring,
1872 )
1873 .unwrap();
1874 }
1875 }
1876 }
1877}
1878
1879impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
1880 fn check_call_dest(
1881 &mut self,
1882 term: &Terminator<'tcx>,
1883 sig: &ty::FnSig<'tcx>,
1884 destination: Place<'tcx>,
1885 is_diverging: bool,
1886 term_location: Location,
1887 ) {
1888 let tcx = self.tcx();
1889 if is_diverging {
1890 let output_ty = self.tcx().erase_and_anonymize_regions(sig.output());
1893 if !output_ty
1894 .is_privately_uninhabited(self.tcx(), self.infcx.typing_env(self.infcx.param_env))
1895 {
1896 span_mirbug!(self, term, "call to non-diverging function {:?} w/o dest", sig);
1897 }
1898 } else {
1899 let dest_ty = destination.ty(self.body, tcx).ty;
1900 let dest_ty = self.normalize(dest_ty, term_location);
1901 let category = match destination.as_local() {
1902 Some(RETURN_PLACE) => {
1903 if let DefiningTy::Const(def_id, _) | DefiningTy::InlineConst(def_id, _) =
1904 self.universal_regions.defining_ty
1905 {
1906 if tcx.is_static(def_id) {
1907 ConstraintCategory::UseAsStatic
1908 } else {
1909 ConstraintCategory::UseAsConst
1910 }
1911 } else {
1912 ConstraintCategory::Return(ReturnConstraint::Normal)
1913 }
1914 }
1915 Some(l) if !self.body.local_decls[l].is_user_variable() => {
1916 ConstraintCategory::Boring
1917 }
1918 _ => ConstraintCategory::Assignment,
1920 };
1921
1922 let locations = term_location.to_locations();
1923
1924 if let Err(terr) = self.sub_types(sig.output(), dest_ty, locations, category) {
1925 span_mirbug!(
1926 self,
1927 term,
1928 "call dest mismatch ({:?} <- {:?}): {:?}",
1929 dest_ty,
1930 sig.output(),
1931 terr
1932 );
1933 }
1934
1935 if self.unsized_feature_enabled() {
1938 let span = term.source_info.span;
1939 self.ensure_place_sized(dest_ty, span);
1940 }
1941 }
1942 }
1943
1944 #[instrument(level = "debug", skip(self, term, func, term_location, call_source))]
1945 fn check_call_inputs(
1946 &mut self,
1947 term: &Terminator<'tcx>,
1948 func: &Operand<'tcx>,
1949 sig: &ty::FnSig<'tcx>,
1950 args: &[Spanned<Operand<'tcx>>],
1951 term_location: Location,
1952 call_source: CallSource,
1953 ) {
1954 if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.c_variadic) {
1955 span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
1956 }
1957
1958 let func_ty = func.ty(self.body, self.infcx.tcx);
1959 if let ty::FnDef(def_id, _) = *func_ty.kind() {
1960 if let Some(name @ (sym::simd_shuffle | sym::simd_insert | sym::simd_extract)) =
1964 self.tcx().intrinsic(def_id).map(|i| i.name)
1965 {
1966 let idx = match name {
1967 sym::simd_shuffle => 2,
1968 _ => 1,
1969 };
1970 if !matches!(args[idx], Spanned { node: Operand::Constant(_), .. }) {
1971 self.tcx().dcx().emit_err(SimdIntrinsicArgConst {
1972 span: term.source_info.span,
1973 arg: idx + 1,
1974 intrinsic: name.to_string(),
1975 });
1976 }
1977 }
1978 }
1979 debug!(?func_ty);
1980
1981 for (n, (fn_arg, op_arg)) in iter::zip(sig.inputs(), args).enumerate() {
1982 let op_arg_ty = op_arg.node.ty(self.body, self.tcx());
1983
1984 let op_arg_ty = self.normalize(op_arg_ty, term_location);
1985 let category = if call_source.from_hir_call() {
1986 ConstraintCategory::CallArgument(Some(
1987 self.infcx.tcx.erase_and_anonymize_regions(func_ty),
1988 ))
1989 } else {
1990 ConstraintCategory::Boring
1991 };
1992 if let Err(terr) =
1993 self.sub_types(op_arg_ty, *fn_arg, term_location.to_locations(), category)
1994 {
1995 span_mirbug!(
1996 self,
1997 term,
1998 "bad arg #{:?} ({:?} <- {:?}): {:?}",
1999 n,
2000 fn_arg,
2001 op_arg_ty,
2002 terr
2003 );
2004 }
2005 }
2006 }
2007
2008 fn check_iscleanup(&mut self, block_data: &BasicBlockData<'tcx>) {
2009 let is_cleanup = block_data.is_cleanup;
2010 match block_data.terminator().kind {
2011 TerminatorKind::Goto { target } => {
2012 self.assert_iscleanup(block_data, target, is_cleanup)
2013 }
2014 TerminatorKind::SwitchInt { ref targets, .. } => {
2015 for target in targets.all_targets() {
2016 self.assert_iscleanup(block_data, *target, is_cleanup);
2017 }
2018 }
2019 TerminatorKind::UnwindResume => {
2020 if !is_cleanup {
2021 span_mirbug!(self, block_data, "resume on non-cleanup block!")
2022 }
2023 }
2024 TerminatorKind::UnwindTerminate(_) => {
2025 if !is_cleanup {
2026 span_mirbug!(self, block_data, "terminate on non-cleanup block!")
2027 }
2028 }
2029 TerminatorKind::Return => {
2030 if is_cleanup {
2031 span_mirbug!(self, block_data, "return on cleanup block")
2032 }
2033 }
2034 TerminatorKind::TailCall { .. } => {
2035 if is_cleanup {
2036 span_mirbug!(self, block_data, "tailcall on cleanup block")
2037 }
2038 }
2039 TerminatorKind::CoroutineDrop { .. } => {
2040 if is_cleanup {
2041 span_mirbug!(self, block_data, "coroutine_drop in cleanup block")
2042 }
2043 }
2044 TerminatorKind::Yield { resume, drop, .. } => {
2045 if is_cleanup {
2046 span_mirbug!(self, block_data, "yield in cleanup block")
2047 }
2048 self.assert_iscleanup(block_data, resume, is_cleanup);
2049 if let Some(drop) = drop {
2050 self.assert_iscleanup(block_data, drop, is_cleanup);
2051 }
2052 }
2053 TerminatorKind::Unreachable => {}
2054 TerminatorKind::Drop { target, unwind, drop, .. } => {
2055 self.assert_iscleanup(block_data, target, is_cleanup);
2056 self.assert_iscleanup_unwind(block_data, unwind, is_cleanup);
2057 if let Some(drop) = drop {
2058 self.assert_iscleanup(block_data, drop, is_cleanup);
2059 }
2060 }
2061 TerminatorKind::Assert { target, unwind, .. } => {
2062 self.assert_iscleanup(block_data, target, is_cleanup);
2063 self.assert_iscleanup_unwind(block_data, unwind, is_cleanup);
2064 }
2065 TerminatorKind::Call { ref target, unwind, .. } => {
2066 if let &Some(target) = target {
2067 self.assert_iscleanup(block_data, target, is_cleanup);
2068 }
2069 self.assert_iscleanup_unwind(block_data, unwind, is_cleanup);
2070 }
2071 TerminatorKind::FalseEdge { real_target, imaginary_target } => {
2072 self.assert_iscleanup(block_data, real_target, is_cleanup);
2073 self.assert_iscleanup(block_data, imaginary_target, is_cleanup);
2074 }
2075 TerminatorKind::FalseUnwind { real_target, unwind } => {
2076 self.assert_iscleanup(block_data, real_target, is_cleanup);
2077 self.assert_iscleanup_unwind(block_data, unwind, is_cleanup);
2078 }
2079 TerminatorKind::InlineAsm { ref targets, unwind, .. } => {
2080 for &target in targets {
2081 self.assert_iscleanup(block_data, target, is_cleanup);
2082 }
2083 self.assert_iscleanup_unwind(block_data, unwind, is_cleanup);
2084 }
2085 }
2086 }
2087
2088 fn assert_iscleanup(&mut self, ctxt: &dyn fmt::Debug, bb: BasicBlock, iscleanuppad: bool) {
2089 if self.body[bb].is_cleanup != iscleanuppad {
2090 span_mirbug!(self, ctxt, "cleanuppad mismatch: {:?} should be {:?}", bb, iscleanuppad);
2091 }
2092 }
2093
2094 fn assert_iscleanup_unwind(
2095 &mut self,
2096 ctxt: &dyn fmt::Debug,
2097 unwind: UnwindAction,
2098 is_cleanup: bool,
2099 ) {
2100 match unwind {
2101 UnwindAction::Cleanup(unwind) => {
2102 if is_cleanup {
2103 span_mirbug!(self, ctxt, "unwind on cleanup block")
2104 }
2105 self.assert_iscleanup(ctxt, unwind, true);
2106 }
2107 UnwindAction::Continue => {
2108 if is_cleanup {
2109 span_mirbug!(self, ctxt, "unwind on cleanup block")
2110 }
2111 }
2112 UnwindAction::Unreachable | UnwindAction::Terminate(_) => (),
2113 }
2114 }
2115
2116 fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
2117 let tcx = self.tcx();
2118
2119 let erased_ty = tcx.erase_and_anonymize_regions(ty);
2123 if !erased_ty.is_sized(tcx, self.infcx.typing_env(self.infcx.param_env)) {
2125 if self.reported_errors.replace((ty, span)).is_none() {
2130 self.tcx().dcx().emit_err(MoveUnsized { ty, span });
2134 }
2135 }
2136 }
2137
2138 fn aggregate_field_ty(
2139 &mut self,
2140 ak: &AggregateKind<'tcx>,
2141 field_index: FieldIdx,
2142 location: Location,
2143 ) -> Result<Ty<'tcx>, FieldAccessError> {
2144 let tcx = self.tcx();
2145
2146 match *ak {
2147 AggregateKind::Adt(adt_did, variant_index, args, _, active_field_index) => {
2148 let def = tcx.adt_def(adt_did);
2149 let variant = &def.variant(variant_index);
2150 let adj_field_index = active_field_index.unwrap_or(field_index);
2151 if let Some(field) = variant.fields.get(adj_field_index) {
2152 Ok(self.normalize(field.ty(tcx, args), location))
2153 } else {
2154 Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
2155 }
2156 }
2157 AggregateKind::Closure(_, args) => {
2158 match args.as_closure().upvar_tys().get(field_index.as_usize()) {
2159 Some(ty) => Ok(*ty),
2160 None => Err(FieldAccessError::OutOfRange {
2161 field_count: args.as_closure().upvar_tys().len(),
2162 }),
2163 }
2164 }
2165 AggregateKind::Coroutine(_, args) => {
2166 match args.as_coroutine().prefix_tys().get(field_index.as_usize()) {
2170 Some(ty) => Ok(*ty),
2171 None => Err(FieldAccessError::OutOfRange {
2172 field_count: args.as_coroutine().prefix_tys().len(),
2173 }),
2174 }
2175 }
2176 AggregateKind::CoroutineClosure(_, args) => {
2177 match args.as_coroutine_closure().upvar_tys().get(field_index.as_usize()) {
2178 Some(ty) => Ok(*ty),
2179 None => Err(FieldAccessError::OutOfRange {
2180 field_count: args.as_coroutine_closure().upvar_tys().len(),
2181 }),
2182 }
2183 }
2184 AggregateKind::Array(ty) => Ok(ty),
2185 AggregateKind::Tuple | AggregateKind::RawPtr(..) => {
2186 unreachable!("This should have been covered in check_rvalues");
2187 }
2188 }
2189 }
2190
2191 fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotationIndex> {
2195 match rvalue {
2196 Rvalue::Use(_)
2197 | Rvalue::ThreadLocalRef(_)
2198 | Rvalue::Repeat(..)
2199 | Rvalue::Ref(..)
2200 | Rvalue::RawPtr(..)
2201 | Rvalue::Cast(..)
2202 | Rvalue::ShallowInitBox(..)
2203 | Rvalue::BinaryOp(..)
2204 | Rvalue::NullaryOp(..)
2205 | Rvalue::CopyForDeref(..)
2206 | Rvalue::UnaryOp(..)
2207 | Rvalue::Discriminant(..)
2208 | Rvalue::WrapUnsafeBinder(..) => None,
2209
2210 Rvalue::Aggregate(aggregate, _) => match **aggregate {
2211 AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
2212 AggregateKind::Array(_) => None,
2213 AggregateKind::Tuple => None,
2214 AggregateKind::Closure(_, _) => None,
2215 AggregateKind::Coroutine(_, _) => None,
2216 AggregateKind::CoroutineClosure(_, _) => None,
2217 AggregateKind::RawPtr(_, _) => None,
2218 },
2219 }
2220 }
2221
2222 fn check_aggregate_rvalue(
2223 &mut self,
2224 rvalue: &Rvalue<'tcx>,
2225 aggregate_kind: &AggregateKind<'tcx>,
2226 operands: &IndexSlice<FieldIdx, Operand<'tcx>>,
2227 location: Location,
2228 ) {
2229 let tcx = self.tcx();
2230
2231 self.prove_aggregate_predicates(aggregate_kind, location);
2232
2233 if *aggregate_kind == AggregateKind::Tuple {
2234 return;
2236 }
2237
2238 if let AggregateKind::RawPtr(..) = aggregate_kind {
2239 bug!("RawPtr should only be in runtime MIR");
2240 }
2241
2242 for (i, operand) in operands.iter_enumerated() {
2243 let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
2244 Ok(field_ty) => field_ty,
2245 Err(FieldAccessError::OutOfRange { field_count }) => {
2246 span_mirbug!(
2247 self,
2248 rvalue,
2249 "accessed field #{} but variant only has {}",
2250 i.as_u32(),
2251 field_count,
2252 );
2253 continue;
2254 }
2255 };
2256 let operand_ty = operand.ty(self.body, tcx);
2257 let operand_ty = self.normalize(operand_ty, location);
2258
2259 if let Err(terr) = self.sub_types(
2260 operand_ty,
2261 field_ty,
2262 location.to_locations(),
2263 ConstraintCategory::Boring,
2264 ) {
2265 span_mirbug!(
2266 self,
2267 rvalue,
2268 "{:?} is not a subtype of {:?}: {:?}",
2269 operand_ty,
2270 field_ty,
2271 terr
2272 );
2273 }
2274 }
2275 }
2276
2277 fn add_reborrow_constraint(
2285 &mut self,
2286 location: Location,
2287 borrow_region: ty::Region<'tcx>,
2288 borrowed_place: &Place<'tcx>,
2289 ) {
2290 let Self { borrow_set, location_table, polonius_facts, constraints, .. } = self;
2292
2293 if let Some(polonius_facts) = polonius_facts {
2299 let _prof_timer = self.infcx.tcx.prof.generic_activity("polonius_fact_generation");
2300 if let Some(borrow_index) = borrow_set.get_index_of(&location) {
2301 let region_vid = borrow_region.as_var();
2302 polonius_facts.loan_issued_at.push((
2303 region_vid.into(),
2304 borrow_index,
2305 location_table.mid_index(location),
2306 ));
2307 }
2308 }
2309
2310 debug!(
2316 "add_reborrow_constraint({:?}, {:?}, {:?})",
2317 location, borrow_region, borrowed_place
2318 );
2319
2320 let tcx = self.infcx.tcx;
2321 let def = self.body.source.def_id().expect_local();
2322 let upvars = tcx.closure_captures(def);
2323 let field =
2324 path_utils::is_upvar_field_projection(tcx, upvars, borrowed_place.as_ref(), self.body);
2325 let category = if let Some(field) = field {
2326 ConstraintCategory::ClosureUpvar(field)
2327 } else {
2328 ConstraintCategory::Boring
2329 };
2330
2331 for (base, elem) in borrowed_place.as_ref().iter_projections().rev() {
2332 debug!("add_reborrow_constraint - iteration {:?}", elem);
2333
2334 match elem {
2335 ProjectionElem::Deref => {
2336 let base_ty = base.ty(self.body, tcx).ty;
2337
2338 debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
2339 match base_ty.kind() {
2340 ty::Ref(ref_region, _, mutbl) => {
2341 constraints.outlives_constraints.push(OutlivesConstraint {
2342 sup: ref_region.as_var(),
2343 sub: borrow_region.as_var(),
2344 locations: location.to_locations(),
2345 span: location.to_locations().span(self.body),
2346 category,
2347 variance_info: ty::VarianceDiagInfo::default(),
2348 from_closure: false,
2349 });
2350
2351 match mutbl {
2352 hir::Mutability::Not => {
2353 break;
2357 }
2358 hir::Mutability::Mut => {
2359 }
2381 }
2382 }
2383 ty::RawPtr(..) => {
2384 break;
2386 }
2387 ty::Adt(def, _) if def.is_box() => {
2388 }
2390 _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2391 }
2392 }
2393 ProjectionElem::Field(..)
2394 | ProjectionElem::Downcast(..)
2395 | ProjectionElem::OpaqueCast(..)
2396 | ProjectionElem::Index(..)
2397 | ProjectionElem::ConstantIndex { .. }
2398 | ProjectionElem::Subslice { .. }
2399 | ProjectionElem::UnwrapUnsafeBinder(_) => {
2400 }
2402 }
2403 }
2404 }
2405
2406 fn prove_aggregate_predicates(
2407 &mut self,
2408 aggregate_kind: &AggregateKind<'tcx>,
2409 location: Location,
2410 ) {
2411 let tcx = self.tcx();
2412
2413 debug!(
2414 "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2415 aggregate_kind, location
2416 );
2417
2418 let (def_id, instantiated_predicates) = match *aggregate_kind {
2419 AggregateKind::Adt(adt_did, _, args, _, _) => {
2420 (adt_did, tcx.predicates_of(adt_did).instantiate(tcx, args))
2421 }
2422
2423 AggregateKind::Closure(def_id, args)
2443 | AggregateKind::CoroutineClosure(def_id, args)
2444 | AggregateKind::Coroutine(def_id, args) => (
2445 def_id,
2446 self.prove_closure_bounds(
2447 tcx,
2448 def_id.expect_local(),
2449 args,
2450 location.to_locations(),
2451 ),
2452 ),
2453
2454 AggregateKind::Array(_) | AggregateKind::Tuple | AggregateKind::RawPtr(..) => {
2455 (CRATE_DEF_ID.to_def_id(), ty::InstantiatedPredicates::empty())
2456 }
2457 };
2458
2459 self.normalize_and_prove_instantiated_predicates(
2460 def_id,
2461 instantiated_predicates,
2462 location.to_locations(),
2463 );
2464 }
2465
2466 fn prove_closure_bounds(
2467 &mut self,
2468 tcx: TyCtxt<'tcx>,
2469 def_id: LocalDefId,
2470 args: GenericArgsRef<'tcx>,
2471 locations: Locations,
2472 ) -> ty::InstantiatedPredicates<'tcx> {
2473 let root_def_id = self.root_cx.root_def_id();
2474 self.deferred_closure_requirements.push((def_id, args, locations));
2477
2478 let typeck_root_args = ty::GenericArgs::identity_for_item(tcx, root_def_id);
2480
2481 let parent_args = match tcx.def_kind(def_id) {
2482 DefKind::Closure => {
2486 &args[..typeck_root_args.len()]
2490 }
2491 DefKind::InlineConst => args.as_inline_const().parent_args(),
2492 other => bug!("unexpected item {:?}", other),
2493 };
2494 let parent_args = tcx.mk_args(parent_args);
2495
2496 assert_eq!(typeck_root_args.len(), parent_args.len());
2497 if let Err(_) = self.eq_args(
2498 typeck_root_args,
2499 parent_args,
2500 locations,
2501 ConstraintCategory::BoringNoLocation,
2502 ) {
2503 span_mirbug!(
2504 self,
2505 def_id,
2506 "could not relate closure to parent {:?} != {:?}",
2507 typeck_root_args,
2508 parent_args
2509 );
2510 }
2511
2512 tcx.predicates_of(def_id).instantiate(tcx, args)
2513 }
2514}
2515
2516trait NormalizeLocation: fmt::Debug + Copy {
2517 fn to_locations(self) -> Locations;
2518}
2519
2520impl NormalizeLocation for Locations {
2521 fn to_locations(self) -> Locations {
2522 self
2523 }
2524}
2525
2526impl NormalizeLocation for Location {
2527 fn to_locations(self) -> Locations {
2528 Locations::Single(self)
2529 }
2530}
2531
2532#[derive(Debug)]
2536pub(super) struct InstantiateOpaqueType<'tcx> {
2537 pub base_universe: Option<ty::UniverseIndex>,
2538 pub region_constraints: Option<RegionConstraintData<'tcx>>,
2539 pub obligations: PredicateObligations<'tcx>,
2540}
2541
2542impl<'tcx> TypeOp<'tcx> for InstantiateOpaqueType<'tcx> {
2543 type Output = ();
2544 type ErrorInfo = InstantiateOpaqueType<'tcx>;
2550
2551 fn fully_perform(
2552 mut self,
2553 infcx: &InferCtxt<'tcx>,
2554 root_def_id: LocalDefId,
2555 span: Span,
2556 ) -> Result<TypeOpOutput<'tcx, Self>, ErrorGuaranteed> {
2557 let (mut output, region_constraints) =
2558 scrape_region_constraints(infcx, root_def_id, "InstantiateOpaqueType", span, |ocx| {
2559 ocx.register_obligations(self.obligations.clone());
2560 Ok(())
2561 })?;
2562 self.region_constraints = Some(region_constraints);
2563 output.error_info = Some(self);
2564 Ok(output)
2565 }
2566}