Skip to main content

rustc_borrowck/type_check/
mod.rs

1//! This pass type-checks the MIR to ensure it is not broken.
2
3use 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::bug;
23use rustc_middle::mir::visit::{NonMutatingUseContext, PlaceContext, Visitor};
24use rustc_middle::mir::*;
25use rustc_middle::traits::query::NoSolution;
26use rustc_middle::ty::adjustment::PointerCoercion;
27use rustc_middle::ty::cast::CastTy;
28use rustc_middle::ty::{
29    self, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, GenericArgsRef,
30    RegionUtilitiesExt, Ty, TyCtxt, TypeVisitableExt, UserArgs, UserTypeAnnotationIndex,
31    fold_regions,
32};
33use rustc_mir_dataflow::move_paths::MoveData;
34use rustc_mir_dataflow::points::DenseLocationMap;
35use rustc_span::def_id::CRATE_DEF_ID;
36use rustc_span::{Span, Spanned, 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::PoloniusContext;
46use crate::polonius::legacy::{PoloniusFacts, PoloniusLocationTable};
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
76/// Type checks the given `mir` in the context of the inference
77/// context `infcx`. Returns any region constraints that have yet to
78/// be proven. This result includes liveness constraints that
79/// ensure that regions appearing in the types of all local variables
80/// are live at all points where that local variable may later be
81/// used.
82///
83/// This phase of type-check ought to be infallible -- this is because
84/// the original, HIR-based type-check succeeded. So if any errors
85/// occur here, we will get a `bug!` reported.
86///
87/// # Parameters
88///
89/// - `infcx` -- inference context to use
90/// - `body` -- MIR body to type-check
91/// - `promoted` -- map of promoted constants within `body`
92/// - `universal_regions` -- the universal regions from `body`s function signature
93/// - `location_table` -- for datalog polonius, the map between `Location`s and `RichLocation`s
94/// - `borrow_set` -- information about borrows occurring in `body`
95/// - `polonius_facts` -- when using Polonius, this is the generated set of Polonius facts
96/// - `move_data` -- move-data constructed when performing the maybe-init dataflow analysis
97/// - `location_map` -- map between MIR `Location` and `PointIndex`
98pub(crate) fn type_check<'tcx>(
99    root_cx: &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    {
127        // Scope these variables so it's clear they're not used later
128        let pre_obligations = infcx.take_registered_region_obligations();
129        if !pre_obligations.is_empty() {
    {
        ::core::panicking::panic_fmt(format_args!("there should be no incoming region obligations = {0:#?}",
                pre_obligations));
    }
};assert!(
130            pre_obligations.is_empty(),
131            "there should be no incoming region obligations = {pre_obligations:#?}",
132        );
133        let pre_assumptions = infcx.take_registered_region_assumptions();
134        if !pre_assumptions.is_empty() {
    {
        ::core::panicking::panic_fmt(format_args!("there should be no incoming region assumptions = {0:#?}",
                pre_assumptions));
    }
};assert!(
135            pre_assumptions.is_empty(),
136            "there should be no incoming region assumptions = {pre_assumptions:#?}",
137        );
138    }
139
140    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/type_check/mod.rs:140",
                        "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(140u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("normalized_inputs_and_output")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("normalized_inputs_and_output");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&normalized_inputs_and_output)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?normalized_inputs_and_output);
141
142    let polonius_context = if infcx.tcx.sess.opts.unstable_opts.polonius.is_next_enabled() {
143        Some(PoloniusContext::default())
144    } else {
145        None
146    };
147
148    let mut deferred_closure_requirements = Default::default();
149    let mut typeck = TypeChecker {
150        root_cx,
151        infcx,
152        last_span: body.span,
153        body,
154        promoted,
155        user_type_annotations: &body.user_type_annotations,
156        region_bound_pairs: &region_bound_pairs,
157        known_type_outlives_obligations: &known_type_outlives_obligations,
158        reported_errors: Default::default(),
159        universal_regions: &universal_region_relations.universal_regions,
160        location_table,
161        polonius_facts,
162        borrow_set,
163        constraints: &mut constraints,
164        deferred_closure_requirements: &mut deferred_closure_requirements,
165        polonius_context,
166    };
167
168    typeck.check_user_type_annotations();
169    typeck.visit_body(body);
170    typeck.equate_inputs_and_outputs(&normalized_inputs_and_output);
171    typeck.check_signature_annotation();
172
173    liveness::generate(&mut typeck, &location_map, move_data);
174
175    let polonius_context = typeck.polonius_context;
176
177    if infcx.tcx.assumptions_on_binders() {
178        let mut converter = constraint_conversion::ConstraintConversion::new(
179            typeck.infcx,
180            typeck.universal_regions,
181            typeck.region_bound_pairs,
182            typeck.known_type_outlives_obligations,
183            Locations::All(rustc_span::DUMMY_SP),
184            rustc_span::DUMMY_SP,
185            ConstraintCategory::Boring,
186            typeck.constraints,
187        );
188        typeck.infcx.destructure_solver_region_constraints_for_borrowck(
189            &mut converter,
190            typeck.known_type_outlives_obligations,
191            universal_region_relations.outlives.clone(),
192            infcx.tcx.def_span(infcx.root_def_id),
193        );
194    }
195
196    // In case type check encountered an error region, we suppress unhelpful extra
197    // errors in by clearing out all outlives bounds that we may end up checking.
198    if let Some(guar) = universal_region_relations.universal_regions.encountered_re_error() {
199        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/type_check/mod.rs:199",
                        "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(199u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("encountered an error region; removing constraints!")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("encountered an error region; removing constraints!");
200        constraints.outlives_constraints = Default::default();
201        constraints.type_tests = Default::default();
202        infcx.set_tainted_by_errors(guar);
203    }
204
205    MirTypeckResults {
206        constraints,
207        universal_region_relations,
208        region_bound_pairs,
209        known_type_outlives_obligations,
210        deferred_closure_requirements,
211        polonius_context,
212    }
213}
214
215#[track_caller]
216fn mirbug(tcx: TyCtxt<'_>, span: Span, msg: String) {
217    // We sometimes see MIR failures (notably predicate failures) due to
218    // the fact that we check rvalue sized predicates here. So use `span_delayed_bug`
219    // to avoid reporting bugs in those cases.
220    tcx.dcx().span_delayed_bug(span, msg);
221}
222
223enum FieldAccessError {
224    OutOfRange { field_count: usize },
225}
226
227/// The MIR type checker. Visits the MIR and enforces all the
228/// constraints needed for it to be valid and well-typed. Along the
229/// way, it accrues region constraints -- these can later be used by
230/// NLL region checking.
231struct TypeChecker<'a, 'tcx> {
232    root_cx: &'a BorrowCheckRootCtxt<'a, 'tcx>,
233    infcx: &'a BorrowckInferCtxt<'tcx>,
234    last_span: Span,
235    body: &'a Body<'tcx>,
236    /// The bodies of all promoteds. As promoteds have a completely separate CFG
237    /// recursing into them may corrupt your data structures if you're not careful.
238    promoted: &'a IndexSlice<Promoted, Body<'tcx>>,
239    /// User type annotations are shared between the main MIR and the MIR of
240    /// all of the promoted items.
241    user_type_annotations: &'a CanonicalUserTypeAnnotations<'tcx>,
242    region_bound_pairs: &'a RegionBoundPairs<'tcx>,
243    known_type_outlives_obligations: &'a [ty::PolyTypeOutlivesPredicate<'tcx>],
244    reported_errors: FxIndexSet<(Ty<'tcx>, Span)>,
245    universal_regions: &'a UniversalRegions<'tcx>,
246    location_table: &'a PoloniusLocationTable,
247    polonius_facts: &'a mut Option<PoloniusFacts>,
248    borrow_set: &'a BorrowSet<'tcx>,
249    constraints: &'a mut MirTypeckRegionConstraints<'tcx>,
250    deferred_closure_requirements: &'a mut DeferredClosureRequirements<'tcx>,
251    /// When using `-Zpolonius=next`, the liveness helper data used to create polonius constraints.
252    polonius_context: Option<PoloniusContext>,
253}
254
255/// Holder struct for passing results from MIR typeck to the rest of the non-lexical regions
256/// inference computation.
257pub(crate) struct MirTypeckResults<'tcx> {
258    pub(crate) constraints: MirTypeckRegionConstraints<'tcx>,
259    pub(crate) universal_region_relations: Frozen<UniversalRegionRelations<'tcx>>,
260    pub(crate) region_bound_pairs: Frozen<RegionBoundPairs<'tcx>>,
261    pub(crate) known_type_outlives_obligations: Frozen<Vec<ty::PolyTypeOutlivesPredicate<'tcx>>>,
262    pub(crate) deferred_closure_requirements: DeferredClosureRequirements<'tcx>,
263    pub(crate) polonius_context: Option<PoloniusContext>,
264}
265
266/// A collection of region constraints that must be satisfied for the
267/// program to be considered well-typed.
268#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for MirTypeckRegionConstraints<'tcx> {
    #[inline]
    fn clone(&self) -> MirTypeckRegionConstraints<'tcx> {
        MirTypeckRegionConstraints {
            placeholder_indices: ::core::clone::Clone::clone(&self.placeholder_indices),
            placeholder_index_to_region: ::core::clone::Clone::clone(&self.placeholder_index_to_region),
            liveness_constraints: ::core::clone::Clone::clone(&self.liveness_constraints),
            outlives_constraints: ::core::clone::Clone::clone(&self.outlives_constraints),
            universe_causes: ::core::clone::Clone::clone(&self.universe_causes),
            type_tests: ::core::clone::Clone::clone(&self.type_tests),
        }
    }
}Clone)] // FIXME(#146079)
269pub(crate) struct MirTypeckRegionConstraints<'tcx> {
270    /// Maps from a `ty::Placeholder` to the corresponding
271    /// `PlaceholderIndex` bit that we will use for it.
272    ///
273    /// To keep everything in sync, do not insert this set
274    /// directly. Instead, use the `placeholder_region` helper.
275    pub(crate) placeholder_indices: PlaceholderIndices<'tcx>,
276
277    /// Each time we add a placeholder to `placeholder_indices`, we
278    /// also create a corresponding "representative" region vid for
279    /// that wraps it. This vector tracks those. This way, when we
280    /// convert the same `ty::RePlaceholder(p)` twice, we can map to
281    /// the same underlying `RegionVid`.
282    pub(crate) placeholder_index_to_region: IndexVec<PlaceholderIndex, ty::Region<'tcx>>,
283
284    /// In general, the type-checker is not responsible for enforcing
285    /// liveness constraints; this job falls to the region inferencer,
286    /// which performs a liveness analysis. However, in some limited
287    /// cases, the MIR type-checker creates temporary regions that do
288    /// not otherwise appear in the MIR -- in particular, the
289    /// late-bound regions that it instantiates at call-sites -- and
290    /// hence it must report on their liveness constraints.
291    pub(crate) liveness_constraints: LivenessValues,
292
293    pub(crate) outlives_constraints: OutlivesConstraintSet<'tcx>,
294
295    pub(crate) universe_causes: FxIndexMap<ty::UniverseIndex, UniverseInfo<'tcx>>,
296
297    pub(crate) type_tests: Vec<TypeTest<'tcx>>,
298}
299
300impl<'tcx> MirTypeckRegionConstraints<'tcx> {
301    /// Creates a `Region` for a given `PlaceholderRegion`, or returns the
302    /// region that corresponds to a previously created one.
303    pub(crate) fn placeholder_region(
304        &mut self,
305        infcx: &InferCtxt<'tcx>,
306        placeholder: ty::PlaceholderRegion<'tcx>,
307    ) -> ty::Region<'tcx> {
308        let placeholder_index = self.placeholder_indices.insert(placeholder);
309        match self.placeholder_index_to_region.get(placeholder_index) {
310            Some(&v) => v,
311            None => {
312                let origin = NllRegionVariableOrigin::Placeholder(placeholder);
313                let region = infcx.next_nll_region_var_in_universe(origin, placeholder.universe);
314                self.placeholder_index_to_region.push(region);
315                region
316            }
317        }
318    }
319}
320
321/// The `Locations` type summarizes *where* region constraints are
322/// required to hold. Normally, this is at a particular point which
323/// created the obligation, but for constraints that the user gave, we
324/// want the constraint to hold at all points.
325#[derive(#[automatically_derived]
impl ::core::marker::Copy for Locations { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Locations {
    #[inline]
    fn clone(&self) -> Locations {
        let _: ::core::clone::AssertParamIsClone<Span>;
        let _: ::core::clone::AssertParamIsClone<Location>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for Locations {
    #[inline]
    fn eq(&self, other: &Locations) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (Locations::All(__self_0), Locations::All(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Locations::Single(__self_0), Locations::Single(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => unsafe { ::core::intrinsics::unreachable() }
            }
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for Locations {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Span>;
        let _: ::core::cmp::AssertParamIsEq<Location>;
    }
}Eq, #[automatically_derived]
impl ::core::cmp::PartialOrd for Locations {
    #[inline]
    fn partial_cmp(&self, other: &Locations)
        -> ::core::option::Option<::core::cmp::Ordering> {
        ::core::option::Option::Some(::core::cmp::Ord::cmp(self, other))
    }
}PartialOrd, #[automatically_derived]
impl ::core::cmp::Ord for Locations {
    #[inline]
    fn cmp(&self, other: &Locations) -> ::core::cmp::Ordering {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        match ::core::cmp::Ord::cmp(&__self_discr, &__arg1_discr) {
            ::core::cmp::Ordering::Equal =>
                match (self, other) {
                    (Locations::All(__self_0), Locations::All(__arg1_0)) =>
                        ::core::cmp::Ord::cmp(__self_0, __arg1_0),
                    (Locations::Single(__self_0), Locations::Single(__arg1_0))
                        => ::core::cmp::Ord::cmp(__self_0, __arg1_0),
                    _ => unsafe { ::core::intrinsics::unreachable() }
                },
            cmp => cmp,
        }
    }
}Ord, #[automatically_derived]
impl ::core::hash::Hash for Locations {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        ::core::hash::Hash::hash(&__self_discr, state);
        match self {
            Locations::All(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
            Locations::Single(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
        }
    }
}Hash, #[automatically_derived]
impl ::core::fmt::Debug for Locations {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Locations::All(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "All",
                    &__self_0),
            Locations::Single(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Single",
                    &__self_0),
        }
    }
}Debug)]
326pub enum Locations {
327    /// Indicates that a type constraint should always be true. This
328    /// is particularly important in the new borrowck analysis for
329    /// things like the type of the return slot. Consider this
330    /// example:
331    ///
332    /// ```compile_fail,E0515
333    /// fn foo<'a>(x: &'a u32) -> &'a u32 {
334    ///     let y = 22;
335    ///     return &y; // error
336    /// }
337    /// ```
338    ///
339    /// Here, we wind up with the signature from the return type being
340    /// something like `&'1 u32` where `'1` is a universal region. But
341    /// the type of the return slot `_0` is something like `&'2 u32`
342    /// where `'2` is an existential region variable. The type checker
343    /// requires that `&'2 u32 = &'1 u32` -- but at what point? In the
344    /// older NLL analysis, we required this only at the entry point
345    /// to the function. By the nature of the constraints, this wound
346    /// up propagating to all points reachable from start (because
347    /// `'1` -- as a universal region -- is live everywhere). In the
348    /// newer analysis, though, this doesn't work: `_0` is considered
349    /// dead at the start (it has no usable value) and hence this type
350    /// equality is basically a no-op. Then, later on, when we do `_0
351    /// = &'3 y`, that region `'3` never winds up related to the
352    /// universal region `'1` and hence no error occurs. Therefore, we
353    /// use Locations::All instead, which ensures that the `'1` and
354    /// `'2` are equal everything. We also use this for other
355    /// user-given type annotations; e.g., if the user wrote `let mut
356    /// x: &'static u32 = ...`, we would ensure that all values
357    /// assigned to `x` are of `'static` lifetime.
358    ///
359    /// The span points to the place the constraint arose. For example,
360    /// it points to the type in a user-given type annotation. If
361    /// there's no sensible span then it's DUMMY_SP.
362    All(Span),
363
364    /// An outlives constraint that only has to hold at a single location,
365    /// usually it represents a point where references flow from one spot to
366    /// another (e.g., `x = y`)
367    Single(Location),
368}
369
370impl Locations {
371    pub fn from_location(&self) -> Option<Location> {
372        match self {
373            Locations::All(_) => None,
374            Locations::Single(from_location) => Some(*from_location),
375        }
376    }
377
378    /// Gets a span representing the location.
379    pub fn span(&self, body: &Body<'_>) -> Span {
380        match self {
381            Locations::All(span) => *span,
382            Locations::Single(l) => body.source_info(*l).span,
383        }
384    }
385}
386
387impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
388    fn tcx(&self) -> TyCtxt<'tcx> {
389        self.infcx.tcx
390    }
391
392    fn body(&self) -> &Body<'tcx> {
393        self.body
394    }
395
396    /// Equate the inferred type and the annotated type for user type annotations
397    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("check_user_type_annotations",
                                    "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(397u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set_all(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/type_check/mod.rs:399",
                                    "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(399u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("self.user_type_annotations")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("self.user_type_annotations");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self.user_type_annotations)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            for user_annotation in self.user_type_annotations {
                let CanonicalUserTypeAnnotation {
                        span, ref user_ty, inferred_ty } = *user_annotation;
                let annotation = self.instantiate_canonical(span, user_ty);
                self.ascribe_user_type(inferred_ty, annotation, span);
            }
        }
    }
}#[instrument(skip(self), level = "debug")]
398    fn check_user_type_annotations(&mut self) {
399        debug!(?self.user_type_annotations);
400        for user_annotation in self.user_type_annotations {
401            let CanonicalUserTypeAnnotation { span, ref user_ty, inferred_ty } = *user_annotation;
402            let annotation = self.instantiate_canonical(span, user_ty);
403            self.ascribe_user_type(inferred_ty, annotation, span);
404        }
405    }
406
407    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("push_region_constraints",
                                    "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(407u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("locations")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("locations");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("category")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("category");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&locations)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&category)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/type_check/mod.rs:414",
                                    "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(414u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("constraints generated: {0:#?}",
                                                                data) as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            constraint_conversion::ConstraintConversion::new(self.infcx,
                    self.universal_regions, self.region_bound_pairs,
                    self.known_type_outlives_obligations, locations,
                    locations.span(self.body), category,
                    self.constraints).convert_all(data);
        }
    }
}#[instrument(skip(self, data), level = "debug")]
408    fn push_region_constraints(
409        &mut self,
410        locations: Locations,
411        category: ConstraintCategory<'tcx>,
412        data: &QueryRegionConstraints<'tcx>,
413    ) {
414        debug!("constraints generated: {:#?}", data);
415
416        constraint_conversion::ConstraintConversion::new(
417            self.infcx,
418            self.universal_regions,
419            self.region_bound_pairs,
420            self.known_type_outlives_obligations,
421            locations,
422            locations.span(self.body),
423            category,
424            self.constraints,
425        )
426        .convert_all(data);
427    }
428
429    /// Try to relate `sub <: sup`
430    fn sub_types(
431        &mut self,
432        sub: Ty<'tcx>,
433        sup: Ty<'tcx>,
434        locations: Locations,
435        category: ConstraintCategory<'tcx>,
436    ) -> Result<(), NoSolution> {
437        // Use this order of parameters because the sup type is usually the
438        // "expected" type in diagnostics.
439        self.relate_types(sup, ty::Contravariant, sub, locations, category)
440    }
441
442    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("eq_types",
                                    "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(442u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("expected")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("expected");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("found")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("found");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("locations")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("locations");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&expected)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&found)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&locations)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), NoSolution> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.relate_types(expected, ty::Invariant, found, locations,
                category)
        }
    }
}#[instrument(skip(self, category), level = "debug")]
443    fn eq_types(
444        &mut self,
445        expected: Ty<'tcx>,
446        found: Ty<'tcx>,
447        locations: Locations,
448        category: ConstraintCategory<'tcx>,
449    ) -> Result<(), NoSolution> {
450        self.relate_types(expected, ty::Invariant, found, locations, category)
451    }
452
453    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("relate_type_and_user_type",
                                    "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(453u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("a")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("a");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("v")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("v");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("user_ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("user_ty");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("locations")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("locations");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("category")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("category");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&a)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&v)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&user_ty)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&locations)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&category)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Result<(), NoSolution> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let annotated_type =
                self.user_type_annotations[user_ty.base].inferred_ty;
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/type_check/mod.rs:463",
                                    "rustc_borrowck::type_check", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(463u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("annotated_type")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("annotated_type");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::TRACE <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::TRACE <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&annotated_type)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let mut curr_projected_ty = PlaceTy::from_ty(annotated_type);
            let tcx = self.infcx.tcx;
            for proj in &user_ty.projs {
                if !self.infcx.next_trait_solver() &&
                        let ty::Alias(_, ty::AliasTy { kind: ty::Opaque { .. }, ..
                            }) = curr_projected_ty.ty.kind() {
                    return Ok(());
                }
                let projected_ty =
                    curr_projected_ty.projection_ty_core(tcx, proj,
                        |ty|
                            self.normalize(ty::Unnormalized::new_wip(ty), locations),
                        |ty, variant_index, field, ()|
                            {
                                PlaceTy::field_ty(tcx, ty, variant_index,
                                        field).skip_norm_wip()
                            },
                        |_|
                            ::core::panicking::panic("internal error: entered unreachable code"));
                curr_projected_ty = projected_ty;
            }
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/type_check/mod.rs:491",
                                    "rustc_borrowck::type_check", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(491u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("curr_projected_ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("curr_projected_ty");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::TRACE <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::TRACE <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&curr_projected_ty)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let mut a = a;
            let mut ty = curr_projected_ty.ty;
            if !self.infcx.next_trait_solver() {
                a = self.normalize(ty::Unnormalized::new_wip(a), locations);
                ty = self.normalize(ty::Unnormalized::new_wip(ty), locations);
            }
            self.relate_types(ty, v.xform(ty::Contravariant), a, locations,
                    category)?;
            Ok(())
        }
    }
}#[instrument(skip(self), level = "debug")]
454    fn relate_type_and_user_type(
455        &mut self,
456        a: Ty<'tcx>,
457        v: ty::Variance,
458        user_ty: &UserTypeProjection,
459        locations: Locations,
460        category: ConstraintCategory<'tcx>,
461    ) -> Result<(), NoSolution> {
462        let annotated_type = self.user_type_annotations[user_ty.base].inferred_ty;
463        trace!(?annotated_type);
464        let mut curr_projected_ty = PlaceTy::from_ty(annotated_type);
465
466        let tcx = self.infcx.tcx;
467
468        for proj in &user_ty.projs {
469            // Necessary for non-trivial patterns whose user-type annotation is an opaque type,
470            // e.g. `let (_a,): Tait = whatever`, see #105897
471            if !self.infcx.next_trait_solver()
472                && let ty::Alias(_, ty::AliasTy { kind: ty::Opaque { .. }, .. }) =
473                    curr_projected_ty.ty.kind()
474            {
475                // There is nothing that we can compare here if we go through an opaque type.
476                // We're always in its defining scope as we can otherwise not project through
477                // it, so we're constraining it anyways.
478                return Ok(());
479            }
480            let projected_ty = curr_projected_ty.projection_ty_core(
481                tcx,
482                proj,
483                |ty| self.normalize(ty::Unnormalized::new_wip(ty), locations),
484                |ty, variant_index, field, ()| {
485                    PlaceTy::field_ty(tcx, ty, variant_index, field).skip_norm_wip()
486                },
487                |_| unreachable!(),
488            );
489            curr_projected_ty = projected_ty;
490        }
491        trace!(?curr_projected_ty);
492
493        // Need to renormalize `a` in the old solver as typecheck may have failed
494        // to normalize higher-ranked aliases if normalization was ambiguous due
495        // to inference.
496        //
497        // We properly normalize higher-ranked aliases during writeback with the
498        // new solver, so this is no longer necessary.
499        let mut a = a;
500        let mut ty = curr_projected_ty.ty;
501        if !self.infcx.next_trait_solver() {
502            a = self.normalize(ty::Unnormalized::new_wip(a), locations);
503            ty = self.normalize(ty::Unnormalized::new_wip(ty), locations);
504        }
505        self.relate_types(ty, v.xform(ty::Contravariant), a, locations, category)?;
506
507        Ok(())
508    }
509
510    fn check_promoted(&mut self, promoted_body: &'a Body<'tcx>, location: Location) {
511        // Determine the constraints from the promoted MIR by running the type
512        // checker on the promoted MIR, then transfer the constraints back to
513        // the main MIR, changing the locations to the provided location.
514
515        let parent_body = mem::replace(&mut self.body, promoted_body);
516
517        // Use new sets of constraints and closure bounds so that we can
518        // modify their locations.
519        let polonius_facts = &mut None;
520        let mut constraints = Default::default();
521        let mut liveness_constraints =
522            LivenessValues::without_specific_points(Rc::new(DenseLocationMap::new(promoted_body)));
523        let mut deferred_closure_requirements = Default::default();
524
525        // Don't try to add borrow_region facts for the promoted MIR as they refer
526        // to the wrong locations.
527        let mut swap_constraints = |this: &mut Self| {
528            mem::swap(this.polonius_facts, polonius_facts);
529            mem::swap(&mut this.constraints.outlives_constraints, &mut constraints);
530            mem::swap(&mut this.constraints.liveness_constraints, &mut liveness_constraints);
531            mem::swap(this.deferred_closure_requirements, &mut deferred_closure_requirements);
532        };
533
534        swap_constraints(self);
535
536        self.visit_body(promoted_body);
537
538        self.body = parent_body;
539
540        // Merge the outlives constraints back in, at the given location.
541        swap_constraints(self);
542        let locations = location.to_locations();
543        for constraint in constraints.outlives().iter() {
544            let mut constraint = *constraint;
545            constraint.locations = locations;
546            if let ConstraintCategory::Return(_)
547            | ConstraintCategory::UseAsConst
548            | ConstraintCategory::UseAsStatic = constraint.category
549            {
550                // "Returning" from a promoted is an assignment to a
551                // temporary from the user's point of view.
552                constraint.category = ConstraintCategory::Boring;
553            }
554            self.constraints.outlives_constraints.push(constraint)
555        }
556
557        // If there are nested bodies in promoteds, we also need to update their
558        // location to something in the actual body, not the promoted.
559        //
560        // We don't update the constraint categories of the resulting constraints
561        // as returns in nested bodies are a proper return, even if that nested body
562        // is in a promoted.
563        for (closure_def_id, args, _locations) in deferred_closure_requirements {
564            self.deferred_closure_requirements.push((closure_def_id, args, locations));
565        }
566
567        // If the region is live at least one location in the promoted MIR,
568        // then add a liveness constraint to the main MIR for this region
569        // at the location provided as an argument to this method
570        //
571        // add_location doesn't care about ordering so not a problem for the live regions to be
572        // unordered.
573        #[allow(rustc::potential_query_instability)]
574        for region in liveness_constraints.live_regions_unordered() {
575            self.constraints.liveness_constraints.add_location(region, location);
576        }
577    }
578}
579
580impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
581    fn visit_span(&mut self, span: Span) {
582        if !span.is_dummy() {
583            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/type_check/mod.rs:583",
                        "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(583u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("span")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("span");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&span)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?span);
584            self.last_span = span;
585        }
586    }
587
588    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("visit_body",
                                    "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(588u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set_all(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if true {
                if !std::ptr::eq(self.body, body) {
                    ::core::panicking::panic("assertion failed: std::ptr::eq(self.body, body)")
                };
            };
            for (local, local_decl) in body.local_decls.iter_enumerated() {
                self.visit_local_decl(local, local_decl);
            }
            for (block, block_data) in body.basic_blocks.iter_enumerated() {
                let mut location = Location { block, statement_index: 0 };
                for stmt in &block_data.statements {
                    self.visit_statement(stmt, location);
                    location.statement_index += 1;
                }
                self.visit_terminator(block_data.terminator(), location);
                self.check_iscleanup(block_data);
            }
        }
    }
}#[instrument(skip(self, body), level = "debug")]
589    fn visit_body(&mut self, body: &Body<'tcx>) {
590        debug_assert!(std::ptr::eq(self.body, body));
591
592        for (local, local_decl) in body.local_decls.iter_enumerated() {
593            self.visit_local_decl(local, local_decl);
594        }
595
596        for (block, block_data) in body.basic_blocks.iter_enumerated() {
597            let mut location = Location { block, statement_index: 0 };
598            for stmt in &block_data.statements {
599                self.visit_statement(stmt, location);
600                location.statement_index += 1;
601            }
602
603            self.visit_terminator(block_data.terminator(), location);
604            self.check_iscleanup(block_data);
605        }
606    }
607
608    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("visit_statement",
                                    "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(608u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("stmt")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("stmt");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("location")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("location");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&stmt)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&location)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.super_statement(stmt, location);
            let tcx = self.tcx();
            match &stmt.kind {
                StatementKind::Assign((place, rv)) => {
                    let category =
                        match place.as_local() {
                            Some(RETURN_PLACE) => {
                                let defining_ty = &self.universal_regions.defining_ty;
                                if defining_ty.is_const() {
                                    if tcx.is_static(defining_ty.def_id()) {
                                        ConstraintCategory::UseAsStatic
                                    } else { ConstraintCategory::UseAsConst }
                                } else {
                                    ConstraintCategory::Return(ReturnConstraint::Normal)
                                }
                            }
                            Some(l) if
                                #[allow(non_exhaustive_omitted_patterns)] match self.body.local_decls[l].local_info()
                                    {
                                    LocalInfo::AggregateTemp => true,
                                    _ => false,
                                } => {
                                ConstraintCategory::Usage
                            }
                            Some(l) if !self.body.local_decls[l].is_user_variable() => {
                                ConstraintCategory::Boring
                            }
                            _ => ConstraintCategory::Assignment,
                        };
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/type_check/mod.rs:644",
                                            "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                            ::tracing_core::__macro_support::Option::Some(644u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                            ::tracing_core::field::FieldSet::new(&["message"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("assignment category: {0:?} {1:?}",
                                                                        category,
                                                                        place.as_local().map(|l| &self.body.local_decls[l])) as
                                                                &dyn ::tracing::field::Value))])
                                });
                        } else { ; }
                    };
                    let place_ty = place.ty(self.body, tcx).ty;
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/type_check/mod.rs:651",
                                            "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                            ::tracing_core::__macro_support::Option::Some(651u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                            ::tracing_core::field::FieldSet::new(&[{
                                                                const NAME:
                                                                    ::tracing::__macro_support::FieldName<{
                                                                        ::tracing::__macro_support::FieldName::len("place_ty")
                                                                    }> =
                                                                    ::tracing::__macro_support::FieldName::new("place_ty");
                                                                NAME.as_str()
                                                            }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&place_ty)
                                                                as &dyn ::tracing::field::Value))])
                                });
                        } else { ; }
                    };
                    let place_ty =
                        self.normalize(ty::Unnormalized::new_wip(place_ty),
                            location);
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/type_check/mod.rs:653",
                                            "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                            ::tracing_core::__macro_support::Option::Some(653u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                            ::tracing_core::field::FieldSet::new(&["message"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("place_ty normalized: {0:?}",
                                                                        place_ty) as &dyn ::tracing::field::Value))])
                                });
                        } else { ; }
                    };
                    let rv_ty = rv.ty(self.body, tcx);
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/type_check/mod.rs:655",
                                            "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                            ::tracing_core::__macro_support::Option::Some(655u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                            ::tracing_core::field::FieldSet::new(&[{
                                                                const NAME:
                                                                    ::tracing::__macro_support::FieldName<{
                                                                        ::tracing::__macro_support::FieldName::len("rv_ty")
                                                                    }> =
                                                                    ::tracing::__macro_support::FieldName::new("rv_ty");
                                                                NAME.as_str()
                                                            }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&rv_ty)
                                                                as &dyn ::tracing::field::Value))])
                                });
                        } else { ; }
                    };
                    let rv_ty =
                        self.normalize(ty::Unnormalized::new_wip(rv_ty), location);
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/type_check/mod.rs:657",
                                            "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                            ::tracing_core::__macro_support::Option::Some(657u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                            ::tracing_core::field::FieldSet::new(&["message"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("normalized rv_ty: {0:?}",
                                                                        rv_ty) as &dyn ::tracing::field::Value))])
                                });
                        } else { ; }
                    };
                    if let Err(terr) =
                            self.sub_types(rv_ty, place_ty, location.to_locations(),
                                category) {
                        {
                            crate::type_check::mirbug(self.tcx(), self.last_span,
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                self.body().source.def_id(), stmt,
                                                format_args!("bad assignment ({0:?} = {1:?}): {2:?}",
                                                    place_ty, rv_ty, terr)))
                                    }))
                        };
                    }
                    if let Some(annotation_index) = self.rvalue_user_ty(rv) &&
                            let Err(terr) =
                                self.relate_type_and_user_type(rv_ty, ty::Invariant,
                                    &UserTypeProjection {
                                            base: annotation_index,
                                            projs: ::alloc::vec::Vec::new(),
                                        }, location.to_locations(),
                                    ConstraintCategory::TypeAnnotation(AnnotationSource::GenericArg))
                        {
                        let annotation =
                            &self.user_type_annotations[annotation_index];
                        {
                            crate::type_check::mirbug(self.tcx(), self.last_span,
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                self.body().source.def_id(), stmt,
                                                format_args!("bad user type on rvalue ({0:?} = {1:?}): {2:?}",
                                                    annotation, rv_ty, terr)))
                                    }))
                        };
                    }
                    if !self.tcx().features().unsized_fn_params() {
                        let trait_ref =
                            ty::TraitRef::new(tcx,
                                tcx.require_lang_item(LangItem::Sized, self.last_span),
                                [place_ty]);
                        self.prove_trait_ref(trait_ref, location.to_locations(),
                            ConstraintCategory::SizedBound);
                    }
                }
                StatementKind::AscribeUserType((place, projection), variance)
                    => {
                    let place_ty = place.ty(self.body, tcx).ty;
                    if let Err(terr) =
                            self.relate_type_and_user_type(place_ty, *variance,
                                projection, Locations::All(stmt.source_info.span),
                                ConstraintCategory::TypeAnnotation(AnnotationSource::Ascription))
                        {
                        let annotation =
                            &self.user_type_annotations[projection.base];
                        {
                            crate::type_check::mirbug(self.tcx(), self.last_span,
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                self.body().source.def_id(), stmt,
                                                format_args!("bad type assert ({0:?} <: {1:?} with projections {2:?}): {3:?}",
                                                    place_ty, annotation, projection.projs, terr)))
                                    }))
                        };
                    }
                }
                StatementKind::Intrinsic(NonDivergingIntrinsic::Assume(..)) |
                    StatementKind::FakeRead(..) | StatementKind::StorageLive(..)
                    | StatementKind::StorageDead(..) |
                    StatementKind::Coverage(..) |
                    StatementKind::ConstEvalCounter |
                    StatementKind::PlaceMention(..) |
                    StatementKind::BackwardIncompatibleDropHint { .. } |
                    StatementKind::Nop => {}
                StatementKind::Intrinsic(NonDivergingIntrinsic::CopyNonOverlapping(..))
                    | StatementKind::SetDiscriminant { .. } => {
                    ::rustc_middle::util::bug::bug_fmt(format_args!("Statement not allowed in this MIR phase"))
                }
            }
        }
    }
}#[instrument(skip(self), level = "debug")]
609    fn visit_statement(&mut self, stmt: &Statement<'tcx>, location: Location) {
610        self.super_statement(stmt, location);
611        let tcx = self.tcx();
612        match &stmt.kind {
613            StatementKind::Assign((place, rv)) => {
614                // Assignments to temporaries are not "interesting";
615                // they are not caused by the user, but rather artifacts
616                // of lowering. Assignments to other sorts of places *are* interesting
617                // though.
618                let category = match place.as_local() {
619                    Some(RETURN_PLACE) => {
620                        let defining_ty = &self.universal_regions.defining_ty;
621                        if defining_ty.is_const() {
622                            if tcx.is_static(defining_ty.def_id()) {
623                                ConstraintCategory::UseAsStatic
624                            } else {
625                                ConstraintCategory::UseAsConst
626                            }
627                        } else {
628                            ConstraintCategory::Return(ReturnConstraint::Normal)
629                        }
630                    }
631                    Some(l)
632                        if matches!(
633                            self.body.local_decls[l].local_info(),
634                            LocalInfo::AggregateTemp
635                        ) =>
636                    {
637                        ConstraintCategory::Usage
638                    }
639                    Some(l) if !self.body.local_decls[l].is_user_variable() => {
640                        ConstraintCategory::Boring
641                    }
642                    _ => ConstraintCategory::Assignment,
643                };
644                debug!(
645                    "assignment category: {:?} {:?}",
646                    category,
647                    place.as_local().map(|l| &self.body.local_decls[l])
648                );
649
650                let place_ty = place.ty(self.body, tcx).ty;
651                debug!(?place_ty);
652                let place_ty = self.normalize(ty::Unnormalized::new_wip(place_ty), location);
653                debug!("place_ty normalized: {:?}", place_ty);
654                let rv_ty = rv.ty(self.body, tcx);
655                debug!(?rv_ty);
656                let rv_ty = self.normalize(ty::Unnormalized::new_wip(rv_ty), location);
657                debug!("normalized rv_ty: {:?}", rv_ty);
658                if let Err(terr) =
659                    self.sub_types(rv_ty, place_ty, location.to_locations(), category)
660                {
661                    span_mirbug!(
662                        self,
663                        stmt,
664                        "bad assignment ({:?} = {:?}): {:?}",
665                        place_ty,
666                        rv_ty,
667                        terr
668                    );
669                }
670
671                if let Some(annotation_index) = self.rvalue_user_ty(rv)
672                    && let Err(terr) = self.relate_type_and_user_type(
673                        rv_ty,
674                        ty::Invariant,
675                        &UserTypeProjection { base: annotation_index, projs: vec![] },
676                        location.to_locations(),
677                        ConstraintCategory::TypeAnnotation(AnnotationSource::GenericArg),
678                    )
679                {
680                    let annotation = &self.user_type_annotations[annotation_index];
681                    span_mirbug!(
682                        self,
683                        stmt,
684                        "bad user type on rvalue ({:?} = {:?}): {:?}",
685                        annotation,
686                        rv_ty,
687                        terr
688                    );
689                }
690
691                if !self.tcx().features().unsized_fn_params() {
692                    let trait_ref = ty::TraitRef::new(
693                        tcx,
694                        tcx.require_lang_item(LangItem::Sized, self.last_span),
695                        [place_ty],
696                    );
697                    self.prove_trait_ref(
698                        trait_ref,
699                        location.to_locations(),
700                        ConstraintCategory::SizedBound,
701                    );
702                }
703            }
704            StatementKind::AscribeUserType((place, projection), variance) => {
705                let place_ty = place.ty(self.body, tcx).ty;
706                if let Err(terr) = self.relate_type_and_user_type(
707                    place_ty,
708                    *variance,
709                    projection,
710                    Locations::All(stmt.source_info.span),
711                    ConstraintCategory::TypeAnnotation(AnnotationSource::Ascription),
712                ) {
713                    let annotation = &self.user_type_annotations[projection.base];
714                    span_mirbug!(
715                        self,
716                        stmt,
717                        "bad type assert ({:?} <: {:?} with projections {:?}): {:?}",
718                        place_ty,
719                        annotation,
720                        projection.projs,
721                        terr
722                    );
723                }
724            }
725            StatementKind::Intrinsic(NonDivergingIntrinsic::Assume(..))
726            | StatementKind::FakeRead(..)
727            | StatementKind::StorageLive(..)
728            | StatementKind::StorageDead(..)
729            | StatementKind::Coverage(..)
730            | StatementKind::ConstEvalCounter
731            | StatementKind::PlaceMention(..)
732            | StatementKind::BackwardIncompatibleDropHint { .. }
733            | StatementKind::Nop => {}
734            StatementKind::Intrinsic(NonDivergingIntrinsic::CopyNonOverlapping(..))
735            | StatementKind::SetDiscriminant { .. } => {
736                bug!("Statement not allowed in this MIR phase")
737            }
738        }
739    }
740
741    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("visit_terminator",
                                    "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(741u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("term")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("term");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("term_location")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("term_location");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&term)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&term_location)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.super_terminator(term, term_location);
            let tcx = self.tcx();
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/type_check/mod.rs:745",
                                    "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(745u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("terminator kind: {0:?}",
                                                                term.kind) as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            match &term.kind {
                TerminatorKind::Goto { .. } | TerminatorKind::UnwindResume |
                    TerminatorKind::UnwindTerminate(_) | TerminatorKind::Return
                    | TerminatorKind::CoroutineDrop |
                    TerminatorKind::Unreachable | TerminatorKind::Drop { .. } |
                    TerminatorKind::FalseEdge { .. } |
                    TerminatorKind::FalseUnwind { .. } |
                    TerminatorKind::InlineAsm { .. } => {}
                TerminatorKind::SwitchInt { discr, .. } => {
                    let switch_ty = discr.ty(self.body, tcx);
                    if !switch_ty.is_integral() && !switch_ty.is_char() &&
                            !switch_ty.is_bool() {
                        {
                            crate::type_check::mirbug(self.tcx(), self.last_span,
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                self.body().source.def_id(), term,
                                                format_args!("bad SwitchInt discr ty {0:?}", switch_ty)))
                                    }))
                        };
                    }
                }
                TerminatorKind::Call { func, args, .. } |
                    TerminatorKind::TailCall { func, args, .. } => {
                    let (call_source, destination, is_diverging) =
                        match term.kind {
                            TerminatorKind::Call { call_source, destination, target, ..
                                } => {
                                (call_source, destination, target.is_none())
                            }
                            TerminatorKind::TailCall { .. } => {
                                (CallSource::Normal, RETURN_PLACE.into(), false)
                            }
                            _ =>
                                ::core::panicking::panic("internal error: entered unreachable code"),
                        };
                    let func_ty = func.ty(self.body, tcx);
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/type_check/mod.rs:780",
                                            "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                            ::tracing_core::__macro_support::Option::Some(780u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                            ::tracing_core::field::FieldSet::new(&["message"],
                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("func_ty.kind: {0:?}",
                                                                        func_ty.kind()) as &dyn ::tracing::field::Value))])
                                });
                        } else { ; }
                    };
                    let sig =
                        match func_ty.kind() {
                            ty::FnDef(..) | ty::FnPtr(..) => func_ty.fn_sig(tcx),
                            _ => {
                                {
                                    crate::type_check::mirbug(self.tcx(), self.last_span,
                                        ::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                        self.body().source.def_id(), term,
                                                        format_args!("call to non-function {0:?}", func_ty)))
                                            }))
                                };
                                return;
                            }
                        };
                    let (unnormalized_sig, map) =
                        tcx.instantiate_bound_regions(sig,
                            |br|
                                {
                                    use crate::renumber::RegionCtxt;
                                    let region_ctxt_fn =
                                        ||
                                            {
                                                let reg_info =
                                                    match br.kind {
                                                        ty::BoundRegionKind::Anon => sym::anon,
                                                        ty::BoundRegionKind::Named(def_id) => tcx.item_name(def_id),
                                                        ty::BoundRegionKind::ClosureEnv => sym::env,
                                                        ty::BoundRegionKind::NamedForPrinting(_) => {
                                                            ::rustc_middle::util::bug::bug_fmt(format_args!("only used for pretty printing"))
                                                        }
                                                    };
                                                RegionCtxt::LateBound(reg_info)
                                            };
                                    self.infcx.next_region_var(RegionVariableOrigin::BoundRegion(term.source_info.span,
                                            br.kind, BoundRegionConversionTime::FnCall), region_ctxt_fn)
                                });
                    {
                        use ::tracing::__macro_support::Callsite as _;
                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                            {
                                static META: ::tracing::Metadata<'static> =
                                    {
                                        ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/type_check/mod.rs:814",
                                            "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                            ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                            ::tracing_core::__macro_support::Option::Some(814u32),
                                            ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                            ::tracing_core::field::FieldSet::new(&[{
                                                                const NAME:
                                                                    ::tracing::__macro_support::FieldName<{
                                                                        ::tracing::__macro_support::FieldName::len("unnormalized_sig")
                                                                    }> =
                                                                    ::tracing::__macro_support::FieldName::new("unnormalized_sig");
                                                                NAME.as_str()
                                                            }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                            ::tracing::metadata::Kind::EVENT)
                                    };
                                ::tracing::callsite::DefaultCallsite::new(&META)
                            };
                        let enabled =
                            ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                    ::tracing::Level::DEBUG <=
                                        ::tracing::level_filters::LevelFilter::current() &&
                                {
                                    let interest = __CALLSITE.interest();
                                    !interest.is_never() &&
                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                            interest)
                                };
                        if enabled {
                            (|value_set: ::tracing::field::ValueSet|
                                        {
                                            let meta = __CALLSITE.metadata();
                                            ::tracing::Event::dispatch(meta, &value_set);
                                            ;
                                        })({
                                    #[allow(unused_imports)]
                                    use ::tracing::field::{debug, display, Value};
                                    __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&unnormalized_sig)
                                                                as &dyn ::tracing::field::Value))])
                                });
                        } else { ; }
                    };
                    self.prove_clauses(unnormalized_sig.inputs_and_output.iter().map(|ty|
                                ty::ClauseKind::WellFormed(ty.into())),
                        term_location.to_locations(), ConstraintCategory::Boring);
                    let sig =
                        match self.deeply_normalize(ty::Unnormalized::new_wip(unnormalized_sig),
                                term_location) {
                            Ok(sig) => sig,
                            Err(guar) => { let _: ErrorGuaranteed = guar; return; }
                        };
                    if sig != unnormalized_sig {
                        self.prove_clauses(sig.inputs_and_output.iter().map(|ty|
                                    ty::ClauseKind::WellFormed(ty.into())),
                            term_location.to_locations(), ConstraintCategory::Boring);
                    }
                    self.check_call_dest(term, &sig, destination, is_diverging,
                        term_location);
                    for &late_bound_region in map.values() {
                        let region_vid =
                            self.universal_regions.to_region_vid(late_bound_region);
                        self.constraints.liveness_constraints.add_location(region_vid,
                            term_location);
                    }
                    self.check_call_inputs(term, func, &sig, args,
                        term_location, call_source);
                }
                TerminatorKind::Assert { cond, msg, .. } => {
                    let cond_ty = cond.ty(self.body, tcx);
                    if cond_ty != tcx.types.bool {
                        {
                            crate::type_check::mirbug(self.tcx(), self.last_span,
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                self.body().source.def_id(), term,
                                                format_args!("bad Assert ({0:?}, not bool", cond_ty)))
                                    }))
                        };
                    }
                    if let AssertKind::BoundsCheck { len, index } = &**msg {
                        if len.ty(self.body, tcx) != tcx.types.usize {
                            {
                                crate::type_check::mirbug(self.tcx(), self.last_span,
                                    ::alloc::__export::must_use({
                                            ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                    self.body().source.def_id(), len,
                                                    format_args!("bounds-check length non-usize {0:?}", len)))
                                        }))
                            }
                        }
                        if index.ty(self.body, tcx) != tcx.types.usize {
                            {
                                crate::type_check::mirbug(self.tcx(), self.last_span,
                                    ::alloc::__export::must_use({
                                            ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                    self.body().source.def_id(), index,
                                                    format_args!("bounds-check index non-usize {0:?}", index)))
                                        }))
                            }
                        }
                    }
                }
                TerminatorKind::Yield { value, resume_arg, .. } => {
                    match self.body.yield_ty() {
                        None => {
                            crate::type_check::mirbug(self.tcx(), self.last_span,
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                self.body().source.def_id(), term,
                                                format_args!("yield in non-coroutine")))
                                    }))
                        }
                        Some(ty) => {
                            let value_ty = value.ty(self.body, tcx);
                            if let Err(terr) =
                                    self.sub_types(value_ty, ty, term_location.to_locations(),
                                        ConstraintCategory::Yield) {
                                {
                                    crate::type_check::mirbug(self.tcx(), self.last_span,
                                        ::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                        self.body().source.def_id(), term,
                                                        format_args!("type of yield value is {0:?}, but the yield type is {1:?}: {2:?}",
                                                            value_ty, ty, terr)))
                                            }))
                                };
                            }
                        }
                    }
                    match self.body.resume_ty() {
                        None => {
                            crate::type_check::mirbug(self.tcx(), self.last_span,
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                self.body().source.def_id(), term,
                                                format_args!("yield in non-coroutine")))
                                    }))
                        }
                        Some(ty) => {
                            let resume_ty = resume_arg.ty(self.body, tcx);
                            if let Err(terr) =
                                    self.sub_types(ty, resume_ty.ty,
                                        term_location.to_locations(), ConstraintCategory::Yield) {
                                {
                                    crate::type_check::mirbug(self.tcx(), self.last_span,
                                        ::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                        self.body().source.def_id(), term,
                                                        format_args!("type of resume place is {0:?}, but the resume type is {1:?}: {2:?}",
                                                            resume_ty, ty, terr)))
                                            }))
                                };
                            }
                        }
                    }
                }
            }
        }
    }
}#[instrument(skip(self), level = "debug")]
742    fn visit_terminator(&mut self, term: &Terminator<'tcx>, term_location: Location) {
743        self.super_terminator(term, term_location);
744        let tcx = self.tcx();
745        debug!("terminator kind: {:?}", term.kind);
746        match &term.kind {
747            TerminatorKind::Goto { .. }
748            | TerminatorKind::UnwindResume
749            | TerminatorKind::UnwindTerminate(_)
750            | TerminatorKind::Return
751            | TerminatorKind::CoroutineDrop
752            | TerminatorKind::Unreachable
753            | TerminatorKind::Drop { .. }
754            | TerminatorKind::FalseEdge { .. }
755            | TerminatorKind::FalseUnwind { .. }
756            | TerminatorKind::InlineAsm { .. } => {
757                // no checks needed for these
758            }
759
760            TerminatorKind::SwitchInt { discr, .. } => {
761                let switch_ty = discr.ty(self.body, tcx);
762                if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
763                    span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
764                }
765                // FIXME: check the values
766            }
767            TerminatorKind::Call { func, args, .. }
768            | TerminatorKind::TailCall { func, args, .. } => {
769                let (call_source, destination, is_diverging) = match term.kind {
770                    TerminatorKind::Call { call_source, destination, target, .. } => {
771                        (call_source, destination, target.is_none())
772                    }
773                    TerminatorKind::TailCall { .. } => {
774                        (CallSource::Normal, RETURN_PLACE.into(), false)
775                    }
776                    _ => unreachable!(),
777                };
778
779                let func_ty = func.ty(self.body, tcx);
780                debug!("func_ty.kind: {:?}", func_ty.kind());
781
782                let sig = match func_ty.kind() {
783                    ty::FnDef(..) | ty::FnPtr(..) => func_ty.fn_sig(tcx),
784                    _ => {
785                        span_mirbug!(self, term, "call to non-function {:?}", func_ty);
786                        return;
787                    }
788                };
789                let (unnormalized_sig, map) = tcx.instantiate_bound_regions(sig, |br| {
790                    use crate::renumber::RegionCtxt;
791
792                    let region_ctxt_fn = || {
793                        let reg_info = match br.kind {
794                            ty::BoundRegionKind::Anon => sym::anon,
795                            ty::BoundRegionKind::Named(def_id) => tcx.item_name(def_id),
796                            ty::BoundRegionKind::ClosureEnv => sym::env,
797                            ty::BoundRegionKind::NamedForPrinting(_) => {
798                                bug!("only used for pretty printing")
799                            }
800                        };
801
802                        RegionCtxt::LateBound(reg_info)
803                    };
804
805                    self.infcx.next_region_var(
806                        RegionVariableOrigin::BoundRegion(
807                            term.source_info.span,
808                            br.kind,
809                            BoundRegionConversionTime::FnCall,
810                        ),
811                        region_ctxt_fn,
812                    )
813                });
814                debug!(?unnormalized_sig);
815                // IMPORTANT: We have to prove well formed for the function signature before
816                // we normalize it, as otherwise types like `<&'a &'b () as Trait>::Assoc`
817                // get normalized away, causing us to ignore the `'b: 'a` bound used by the function.
818                //
819                // Normalization results in a well formed type if the input is well formed, so we
820                // don't have to check it twice.
821                //
822                // See #91068 for an example.
823                self.prove_clauses(
824                    unnormalized_sig
825                        .inputs_and_output
826                        .iter()
827                        .map(|ty| ty::ClauseKind::WellFormed(ty.into())),
828                    term_location.to_locations(),
829                    ConstraintCategory::Boring,
830                );
831
832                let sig = match self
833                    .deeply_normalize(ty::Unnormalized::new_wip(unnormalized_sig), term_location)
834                {
835                    Ok(sig) => sig,
836                    Err(guar) => {
837                        let _: ErrorGuaranteed = guar;
838                        return;
839                    }
840                };
841                // HACK(#114936): `WF(sig)` does not imply `WF(normalized(sig))`
842                // with built-in `Fn` implementations, since the impl may not be
843                // well-formed itself.
844                if sig != unnormalized_sig {
845                    self.prove_clauses(
846                        sig.inputs_and_output
847                            .iter()
848                            .map(|ty| ty::ClauseKind::WellFormed(ty.into())),
849                        term_location.to_locations(),
850                        ConstraintCategory::Boring,
851                    );
852                }
853
854                self.check_call_dest(term, &sig, destination, is_diverging, term_location);
855
856                // The ordinary liveness rules will ensure that all
857                // regions in the type of the callee are live here. We
858                // then further constrain the late-bound regions that
859                // were instantiated at the call site to be live as
860                // well. The resulting is that all the input (and
861                // output) types in the signature must be live, since
862                // all the inputs that fed into it were live.
863                for &late_bound_region in map.values() {
864                    let region_vid = self.universal_regions.to_region_vid(late_bound_region);
865                    self.constraints.liveness_constraints.add_location(region_vid, term_location);
866                }
867
868                self.check_call_inputs(term, func, &sig, args, term_location, call_source);
869            }
870            TerminatorKind::Assert { cond, msg, .. } => {
871                let cond_ty = cond.ty(self.body, tcx);
872                if cond_ty != tcx.types.bool {
873                    span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
874                }
875
876                if let AssertKind::BoundsCheck { len, index } = &**msg {
877                    if len.ty(self.body, tcx) != tcx.types.usize {
878                        span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
879                    }
880                    if index.ty(self.body, tcx) != tcx.types.usize {
881                        span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
882                    }
883                }
884            }
885            TerminatorKind::Yield { value, resume_arg, .. } => {
886                match self.body.yield_ty() {
887                    None => span_mirbug!(self, term, "yield in non-coroutine"),
888                    Some(ty) => {
889                        let value_ty = value.ty(self.body, tcx);
890                        if let Err(terr) = self.sub_types(
891                            value_ty,
892                            ty,
893                            term_location.to_locations(),
894                            ConstraintCategory::Yield,
895                        ) {
896                            span_mirbug!(
897                                self,
898                                term,
899                                "type of yield value is {:?}, but the yield type is {:?}: {:?}",
900                                value_ty,
901                                ty,
902                                terr
903                            );
904                        }
905                    }
906                }
907
908                match self.body.resume_ty() {
909                    None => span_mirbug!(self, term, "yield in non-coroutine"),
910                    Some(ty) => {
911                        let resume_ty = resume_arg.ty(self.body, tcx);
912                        if let Err(terr) = self.sub_types(
913                            ty,
914                            resume_ty.ty,
915                            term_location.to_locations(),
916                            ConstraintCategory::Yield,
917                        ) {
918                            span_mirbug!(
919                                self,
920                                term,
921                                "type of resume place is {:?}, but the resume type is {:?}: {:?}",
922                                resume_ty,
923                                ty,
924                                terr
925                            );
926                        }
927                    }
928                }
929            }
930        }
931    }
932
933    fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) {
934        self.super_local_decl(local, local_decl);
935
936        for user_ty in
937            local_decl.user_ty.as_deref().map(UserTypeProjections::projections).into_flat_iter()
938        {
939            let span = self.user_type_annotations[user_ty.base].span;
940
941            let ty = if local_decl.is_nonref_binding() {
942                local_decl.ty
943            } else if let &ty::Ref(_, rty, _) = local_decl.ty.kind() {
944                // If we have a binding of the form `let ref x: T = ..`
945                // then remove the outermost reference so we can check the
946                // type annotation for the remaining type.
947                rty
948            } else {
949                ::rustc_middle::util::bug::bug_fmt(format_args!("{0:?} with ref binding has wrong type {1}",
        local, local_decl.ty));bug!("{:?} with ref binding has wrong type {}", local, local_decl.ty);
950            };
951
952            if let Err(terr) = self.relate_type_and_user_type(
953                ty,
954                ty::Invariant,
955                user_ty,
956                Locations::All(span),
957                ConstraintCategory::TypeAnnotation(AnnotationSource::Declaration),
958            ) {
959                {
    crate::type_check::mirbug(self.tcx(), self.last_span,
        ::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                        self.body().source.def_id(), local,
                        format_args!("bad user type on variable {0:?}: {1:?} != {2:?} ({3:?})",
                            local, local_decl.ty, local_decl.user_ty, terr)))
            }))
};span_mirbug!(
960                    self,
961                    local,
962                    "bad user type on variable {:?}: {:?} != {:?} ({:?})",
963                    local,
964                    local_decl.ty,
965                    local_decl.user_ty,
966                    terr,
967                );
968            }
969        }
970
971        // When `unsized_fn_params` is enabled, this is checked in `check_call_dest`,
972        // and `hir_typeck` still forces all non-argument locals to be sized (i.e., we don't
973        // fully re-check what was already checked on HIR).
974        if !self.tcx().features().unsized_fn_params() {
975            match self.body.local_kind(local) {
976                LocalKind::ReturnPointer | LocalKind::Arg => {
977                    // return values of normal functions are required to be
978                    // sized by typeck, but return values of ADT constructors are
979                    // not because we don't include a `Self: Sized` bounds on them.
980                    //
981                    // Unbound parts of arguments were never required to be Sized
982                    // - maybe we should make that a warning.
983                    return;
984                }
985                LocalKind::Temp => {
986                    let span = local_decl.source_info.span;
987                    let ty = local_decl.ty;
988                    self.ensure_place_sized(ty, span);
989                }
990            }
991        }
992    }
993
994    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("visit_rvalue",
                                    "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(994u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("rvalue")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("rvalue");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("location")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("location");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&rvalue)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&location)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.super_rvalue(rvalue, location);
            let tcx = self.tcx();
            let span = self.body.source_info(location).span;
            match rvalue {
                Rvalue::Aggregate(ak, ops) =>
                    self.check_aggregate_rvalue(rvalue, ak, ops, location),
                Rvalue::Repeat(operand, len) => {
                    let array_ty = rvalue.ty(self.body.local_decls(), tcx);
                    self.prove_clause(ty::ClauseKind::WellFormed(array_ty.into()),
                        Locations::Single(location), ConstraintCategory::Boring);
                    if len.try_to_target_usize(tcx).is_none_or(|len| len > 1) {
                        match operand {
                            Operand::Copy(..) | Operand::Constant(..) |
                                Operand::RuntimeChecks(_) => {}
                            Operand::Move(place) => {
                                let ty = place.ty(self.body, tcx).ty;
                                let trait_ref =
                                    ty::TraitRef::new(tcx,
                                        tcx.require_lang_item(LangItem::Copy, span), [ty]);
                                self.prove_trait_ref(trait_ref, Locations::Single(location),
                                    ConstraintCategory::CopyBound);
                            }
                        }
                    }
                }
                Rvalue::Cast(cast_kind, op, ty) => {
                    match *cast_kind {
                        CastKind::PointerCoercion(PointerCoercion::ReifyFnPointer(target_safety),
                            coercion_source) => {
                            let is_implicit_coercion =
                                coercion_source == CoercionSource::Implicit;
                            let src_ty = op.ty(self.body, tcx);
                            let mut src_sig = src_ty.fn_sig(tcx);
                            if let ty::FnDef(def_id, _) = *src_ty.kind() &&
                                                let ty::FnPtr(_, target_hdr) = *ty.kind() &&
                                            tcx.codegen_fn_attrs(def_id).safe_target_features &&
                                        target_hdr.safety().is_safe() &&
                                    let Some(safe_sig) =
                                        tcx.adjust_target_feature_sig(def_id, src_sig,
                                            self.body.source.def_id()) {
                                src_sig = safe_sig;
                            }
                            if src_sig.safety().is_safe() && target_safety.is_unsafe() {
                                src_sig = tcx.safe_to_unsafe_sig(src_sig);
                            }
                            if src_sig.has_bound_regions() &&
                                            let ty::FnPtr(target_fn_tys, target_hdr) = *ty.kind() &&
                                        let target_sig = target_fn_tys.with(target_hdr) &&
                                    let Some(target_sig) = target_sig.no_bound_vars() {
                                let src_sig =
                                    self.infcx.instantiate_binder_with_fresh_vars(span,
                                        BoundRegionConversionTime::HigherRankedType, src_sig);
                                let src_ty =
                                    Ty::new_fn_ptr(self.tcx(), ty::Binder::dummy(src_sig));
                                self.prove_clause(ty::ClauseKind::WellFormed(src_ty.into()),
                                    location.to_locations(),
                                    ConstraintCategory::Cast {
                                        is_raw_ptr_dyn_type_cast: false,
                                        is_implicit_coercion,
                                        unsize_to: None,
                                    });
                                let src_ty =
                                    self.normalize(ty::Unnormalized::new_wip(src_ty), location);
                                if let Err(terr) =
                                        self.sub_types(src_ty, *ty, location.to_locations(),
                                            ConstraintCategory::Cast {
                                                is_raw_ptr_dyn_type_cast: false,
                                                is_implicit_coercion,
                                                unsize_to: None,
                                            }) {
                                    {
                                        crate::type_check::mirbug(self.tcx(), self.last_span,
                                            ::alloc::__export::must_use({
                                                    ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                            self.body().source.def_id(), rvalue,
                                                            format_args!("equating {0:?} with {1:?} yields {2:?}",
                                                                target_sig, src_sig, terr)))
                                                }))
                                    };
                                };
                            }
                            let src_ty = Ty::new_fn_ptr(tcx, src_sig);
                            self.prove_clause(ty::ClauseKind::WellFormed(src_ty.into()),
                                location.to_locations(),
                                ConstraintCategory::Cast {
                                    is_raw_ptr_dyn_type_cast: false,
                                    is_implicit_coercion,
                                    unsize_to: None,
                                });
                            let src_ty =
                                self.normalize(ty::Unnormalized::new_wip(src_ty), location);
                            if let Err(terr) =
                                    self.sub_types(src_ty, *ty, location.to_locations(),
                                        ConstraintCategory::Cast {
                                            is_raw_ptr_dyn_type_cast: false,
                                            is_implicit_coercion,
                                            unsize_to: None,
                                        }) {
                                {
                                    crate::type_check::mirbug(self.tcx(), self.last_span,
                                        ::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                        self.body().source.def_id(), rvalue,
                                                        format_args!("equating {0:?} with {1:?} yields {2:?}",
                                                            src_ty, ty, terr)))
                                            }))
                                };
                            }
                        }
                        CastKind::PointerCoercion(PointerCoercion::ClosureFnPointer(safety),
                            coercion_source) => {
                            let sig =
                                match op.ty(self.body, tcx).kind() {
                                    ty::Closure(_, args) => args.as_closure().sig(),
                                    _ =>
                                        ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached")),
                                };
                            let ty_fn_ptr_from =
                                Ty::new_fn_ptr(tcx, tcx.signature_unclosure(sig, safety));
                            let is_implicit_coercion =
                                coercion_source == CoercionSource::Implicit;
                            if let Err(terr) =
                                    self.sub_types(ty_fn_ptr_from, *ty, location.to_locations(),
                                        ConstraintCategory::Cast {
                                            is_raw_ptr_dyn_type_cast: false,
                                            is_implicit_coercion,
                                            unsize_to: None,
                                        }) {
                                {
                                    crate::type_check::mirbug(self.tcx(), self.last_span,
                                        ::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                        self.body().source.def_id(), rvalue,
                                                        format_args!("equating {0:?} with {1:?} yields {2:?}",
                                                            ty_fn_ptr_from, ty, terr)))
                                            }))
                                };
                            }
                        }
                        CastKind::PointerCoercion(PointerCoercion::UnsafeFnPointer,
                            coercion_source) => {
                            let fn_sig = op.ty(self.body, tcx).fn_sig(tcx);
                            let fn_sig =
                                self.normalize(ty::Unnormalized::new_wip(fn_sig), location);
                            let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
                            let is_implicit_coercion =
                                coercion_source == CoercionSource::Implicit;
                            if let Err(terr) =
                                    self.sub_types(ty_fn_ptr_from, *ty, location.to_locations(),
                                        ConstraintCategory::Cast {
                                            is_raw_ptr_dyn_type_cast: false,
                                            is_implicit_coercion,
                                            unsize_to: None,
                                        }) {
                                {
                                    crate::type_check::mirbug(self.tcx(), self.last_span,
                                        ::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                        self.body().source.def_id(), rvalue,
                                                        format_args!("equating {0:?} with {1:?} yields {2:?}",
                                                            ty_fn_ptr_from, ty, terr)))
                                            }))
                                };
                            }
                        }
                        CastKind::PointerCoercion(PointerCoercion::Unsize,
                            coercion_source) => {
                            let &ty = ty;
                            let trait_ref =
                                ty::TraitRef::new(tcx,
                                    tcx.require_lang_item(LangItem::CoerceUnsized, span),
                                    [op.ty(self.body, tcx), ty]);
                            let is_implicit_coercion =
                                coercion_source == CoercionSource::Implicit;
                            let unsize_to =
                                fold_regions(tcx, ty,
                                    |r, _|
                                        {
                                            if let ty::ReVar(_) = r.kind() {
                                                tcx.lifetimes.re_erased
                                            } else { r }
                                        });
                            self.prove_trait_ref(trait_ref, location.to_locations(),
                                ConstraintCategory::Cast {
                                    is_raw_ptr_dyn_type_cast: false,
                                    is_implicit_coercion,
                                    unsize_to: Some(unsize_to),
                                });
                        }
                        CastKind::PointerCoercion(PointerCoercion::MutToConstPointer,
                            coercion_source) => {
                            let ty::RawPtr(ty_from, hir::Mutability::Mut) =
                                op.ty(self.body,
                                        tcx).kind() else {
                                    {
                                        crate::type_check::mirbug(self.tcx(), self.last_span,
                                            ::alloc::__export::must_use({
                                                    ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                            self.body().source.def_id(), rvalue,
                                                            format_args!("unexpected base type for cast {0:?}", ty)))
                                                }))
                                    };
                                    return;
                                };
                            let ty::RawPtr(ty_to, hir::Mutability::Not) =
                                ty.kind() else {
                                    {
                                        crate::type_check::mirbug(self.tcx(), self.last_span,
                                            ::alloc::__export::must_use({
                                                    ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                            self.body().source.def_id(), rvalue,
                                                            format_args!("unexpected target type for cast {0:?}", ty)))
                                                }))
                                    };
                                    return;
                                };
                            let is_implicit_coercion =
                                coercion_source == CoercionSource::Implicit;
                            if let Err(terr) =
                                    self.sub_types(*ty_from, *ty_to, location.to_locations(),
                                        ConstraintCategory::Cast {
                                            is_raw_ptr_dyn_type_cast: false,
                                            is_implicit_coercion,
                                            unsize_to: None,
                                        }) {
                                {
                                    crate::type_check::mirbug(self.tcx(), self.last_span,
                                        ::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                        self.body().source.def_id(), rvalue,
                                                        format_args!("relating {0:?} with {1:?} yields {2:?}",
                                                            ty_from, ty_to, terr)))
                                            }))
                                };
                            }
                        }
                        CastKind::PointerCoercion(PointerCoercion::ArrayToPointer,
                            coercion_source) => {
                            let ty_from = op.ty(self.body, tcx);
                            let opt_ty_elem_mut =
                                match ty_from.kind() {
                                    ty::RawPtr(array_ty, array_mut) =>
                                        match array_ty.kind() {
                                            ty::Array(ty_elem, _) => Some((ty_elem, *array_mut)),
                                            _ => None,
                                        },
                                    _ => None,
                                };
                            let Some((ty_elem, ty_mut)) =
                                opt_ty_elem_mut else {
                                    {
                                        crate::type_check::mirbug(self.tcx(), self.last_span,
                                            ::alloc::__export::must_use({
                                                    ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                            self.body().source.def_id(), rvalue,
                                                            format_args!("ArrayToPointer cast from unexpected type {0:?}",
                                                                ty_from)))
                                                }))
                                    };
                                    return;
                                };
                            let (ty_to, ty_to_mut) =
                                match ty.kind() {
                                    ty::RawPtr(ty_to, ty_to_mut) => (ty_to, *ty_to_mut),
                                    _ => {
                                        {
                                            crate::type_check::mirbug(self.tcx(), self.last_span,
                                                ::alloc::__export::must_use({
                                                        ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                                self.body().source.def_id(), rvalue,
                                                                format_args!("ArrayToPointer cast to unexpected type {0:?}",
                                                                    ty)))
                                                    }))
                                        };
                                        return;
                                    }
                                };
                            if ty_to_mut.is_mut() && ty_mut.is_not() {
                                {
                                    crate::type_check::mirbug(self.tcx(), self.last_span,
                                        ::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                        self.body().source.def_id(), rvalue,
                                                        format_args!("ArrayToPointer cast from const {0:?} to mut {1:?}",
                                                            ty, ty_to)))
                                            }))
                                };
                                return;
                            }
                            let is_implicit_coercion =
                                coercion_source == CoercionSource::Implicit;
                            if let Err(terr) =
                                    self.sub_types(*ty_elem, *ty_to, location.to_locations(),
                                        ConstraintCategory::Cast {
                                            is_raw_ptr_dyn_type_cast: false,
                                            is_implicit_coercion,
                                            unsize_to: None,
                                        }) {
                                {
                                    crate::type_check::mirbug(self.tcx(), self.last_span,
                                        ::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                        self.body().source.def_id(), rvalue,
                                                        format_args!("relating {0:?} with {1:?} yields {2:?}",
                                                            ty_elem, ty_to, terr)))
                                            }))
                                }
                            }
                        }
                        CastKind::PointerExposeProvenance => {
                            let ty_from = op.ty(self.body, tcx);
                            let cast_ty_from = CastTy::from_ty(ty_from);
                            let cast_ty_to = CastTy::from_ty(*ty);
                            match (cast_ty_from, cast_ty_to) {
                                (Some(CastTy::Ptr(_) | CastTy::FnPtr), Some(CastTy::Int(_)))
                                    => (),
                                _ => {
                                    {
                                        crate::type_check::mirbug(self.tcx(), self.last_span,
                                            ::alloc::__export::must_use({
                                                    ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                            self.body().source.def_id(), rvalue,
                                                            format_args!("Invalid PointerExposeProvenance cast {0:?} -> {1:?}",
                                                                ty_from, ty)))
                                                }))
                                    }
                                }
                            }
                        }
                        CastKind::PointerWithExposedProvenance => {
                            let ty_from = op.ty(self.body, tcx);
                            let cast_ty_from = CastTy::from_ty(ty_from);
                            let cast_ty_to = CastTy::from_ty(*ty);
                            match (cast_ty_from, cast_ty_to) {
                                (Some(CastTy::Int(_)), Some(CastTy::Ptr(_))) => (),
                                _ => {
                                    {
                                        crate::type_check::mirbug(self.tcx(), self.last_span,
                                            ::alloc::__export::must_use({
                                                    ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                            self.body().source.def_id(), rvalue,
                                                            format_args!("Invalid PointerWithExposedProvenance cast {0:?} -> {1:?}",
                                                                ty_from, ty)))
                                                }))
                                    }
                                }
                            }
                        }
                        CastKind::IntToInt => {
                            let ty_from = op.ty(self.body, tcx);
                            let cast_ty_from = CastTy::from_ty(ty_from);
                            let cast_ty_to = CastTy::from_ty(*ty);
                            match (cast_ty_from, cast_ty_to) {
                                (Some(CastTy::Int(_)), Some(CastTy::Int(_))) => (),
                                _ => {
                                    {
                                        crate::type_check::mirbug(self.tcx(), self.last_span,
                                            ::alloc::__export::must_use({
                                                    ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                            self.body().source.def_id(), rvalue,
                                                            format_args!("Invalid IntToInt cast {0:?} -> {1:?}",
                                                                ty_from, ty)))
                                                }))
                                    }
                                }
                            }
                        }
                        CastKind::IntToFloat => {
                            let ty_from = op.ty(self.body, tcx);
                            let cast_ty_from = CastTy::from_ty(ty_from);
                            let cast_ty_to = CastTy::from_ty(*ty);
                            match (cast_ty_from, cast_ty_to) {
                                (Some(CastTy::Int(_)), Some(CastTy::Float)) => (),
                                _ => {
                                    {
                                        crate::type_check::mirbug(self.tcx(), self.last_span,
                                            ::alloc::__export::must_use({
                                                    ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                            self.body().source.def_id(), rvalue,
                                                            format_args!("Invalid IntToFloat cast {0:?} -> {1:?}",
                                                                ty_from, ty)))
                                                }))
                                    }
                                }
                            }
                        }
                        CastKind::FloatToInt => {
                            let ty_from = op.ty(self.body, tcx);
                            let cast_ty_from = CastTy::from_ty(ty_from);
                            let cast_ty_to = CastTy::from_ty(*ty);
                            match (cast_ty_from, cast_ty_to) {
                                (Some(CastTy::Float), Some(CastTy::Int(_))) => (),
                                _ => {
                                    {
                                        crate::type_check::mirbug(self.tcx(), self.last_span,
                                            ::alloc::__export::must_use({
                                                    ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                            self.body().source.def_id(), rvalue,
                                                            format_args!("Invalid FloatToInt cast {0:?} -> {1:?}",
                                                                ty_from, ty)))
                                                }))
                                    }
                                }
                            }
                        }
                        CastKind::FloatToFloat => {
                            let ty_from = op.ty(self.body, tcx);
                            let cast_ty_from = CastTy::from_ty(ty_from);
                            let cast_ty_to = CastTy::from_ty(*ty);
                            match (cast_ty_from, cast_ty_to) {
                                (Some(CastTy::Float), Some(CastTy::Float)) => (),
                                _ => {
                                    {
                                        crate::type_check::mirbug(self.tcx(), self.last_span,
                                            ::alloc::__export::must_use({
                                                    ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                            self.body().source.def_id(), rvalue,
                                                            format_args!("Invalid FloatToFloat cast {0:?} -> {1:?}",
                                                                ty_from, ty)))
                                                }))
                                    }
                                }
                            }
                        }
                        CastKind::FnPtrToPtr => {
                            let ty_from = op.ty(self.body, tcx);
                            let cast_ty_from = CastTy::from_ty(ty_from);
                            let cast_ty_to = CastTy::from_ty(*ty);
                            match (cast_ty_from, cast_ty_to) {
                                (Some(CastTy::FnPtr), Some(CastTy::Ptr(_))) => (),
                                _ => {
                                    {
                                        crate::type_check::mirbug(self.tcx(), self.last_span,
                                            ::alloc::__export::must_use({
                                                    ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                            self.body().source.def_id(), rvalue,
                                                            format_args!("Invalid FnPtrToPtr cast {0:?} -> {1:?}",
                                                                ty_from, ty)))
                                                }))
                                    }
                                }
                            }
                        }
                        CastKind::PtrToPtr => {
                            let ty_from = op.ty(self.body, tcx);
                            let Some(CastTy::Ptr(src)) =
                                CastTy::from_ty(ty_from) else {
                                    ::core::panicking::panic("internal error: entered unreachable code");
                                };
                            let Some(CastTy::Ptr(dst)) =
                                CastTy::from_ty(*ty) else {
                                    ::core::panicking::panic("internal error: entered unreachable code");
                                };
                            if self.infcx.type_is_sized_modulo_regions(self.infcx.param_env,
                                    dst.ty) {
                                let trait_ref =
                                    ty::TraitRef::new(tcx,
                                        tcx.require_lang_item(LangItem::Sized, self.last_span),
                                        [dst.ty]);
                                self.prove_trait_ref(trait_ref, location.to_locations(),
                                    ConstraintCategory::Cast {
                                        is_raw_ptr_dyn_type_cast: false,
                                        is_implicit_coercion: true,
                                        unsize_to: None,
                                    });
                            } else if let ty::Dynamic(src_tty, src_lt) =
                                        *self.struct_tail(src.ty, location).kind() &&
                                    let ty::Dynamic(dst_tty, dst_lt) =
                                        *self.struct_tail(dst.ty, location).kind() {
                                match (src_tty.principal(), dst_tty.principal()) {
                                    (Some(_), Some(_)) => {
                                        let src_obj =
                                            Ty::new_dynamic(tcx,
                                                tcx.mk_poly_existential_predicates(&src_tty.without_auto_traits().collect::<Vec<_>>()),
                                                src_lt);
                                        let dst_obj =
                                            Ty::new_dynamic(tcx,
                                                tcx.mk_poly_existential_predicates(&dst_tty.without_auto_traits().collect::<Vec<_>>()),
                                                dst_lt);
                                        {
                                            use ::tracing::__macro_support::Callsite as _;
                                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                                {
                                                    static META: ::tracing::Metadata<'static> =
                                                        {
                                                            ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/type_check/mod.rs:1541",
                                                                "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                                                ::tracing_core::__macro_support::Option::Some(1541u32),
                                                                ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                                                ::tracing_core::field::FieldSet::new(&[{
                                                                                    const NAME:
                                                                                        ::tracing::__macro_support::FieldName<{
                                                                                            ::tracing::__macro_support::FieldName::len("src_tty")
                                                                                        }> =
                                                                                        ::tracing::__macro_support::FieldName::new("src_tty");
                                                                                    NAME.as_str()
                                                                                },
                                                                                {
                                                                                    const NAME:
                                                                                        ::tracing::__macro_support::FieldName<{
                                                                                            ::tracing::__macro_support::FieldName::len("dst_tty")
                                                                                        }> =
                                                                                        ::tracing::__macro_support::FieldName::new("dst_tty");
                                                                                    NAME.as_str()
                                                                                },
                                                                                {
                                                                                    const NAME:
                                                                                        ::tracing::__macro_support::FieldName<{
                                                                                            ::tracing::__macro_support::FieldName::len("src_obj")
                                                                                        }> =
                                                                                        ::tracing::__macro_support::FieldName::new("src_obj");
                                                                                    NAME.as_str()
                                                                                },
                                                                                {
                                                                                    const NAME:
                                                                                        ::tracing::__macro_support::FieldName<{
                                                                                            ::tracing::__macro_support::FieldName::len("dst_obj")
                                                                                        }> =
                                                                                        ::tracing::__macro_support::FieldName::new("dst_obj");
                                                                                    NAME.as_str()
                                                                                }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                                ::tracing::metadata::Kind::EVENT)
                                                        };
                                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                                };
                                            let enabled =
                                                ::tracing::Level::DEBUG <=
                                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                        ::tracing::Level::DEBUG <=
                                                            ::tracing::level_filters::LevelFilter::current() &&
                                                    {
                                                        let interest = __CALLSITE.interest();
                                                        !interest.is_never() &&
                                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                                interest)
                                                    };
                                            if enabled {
                                                (|value_set: ::tracing::field::ValueSet|
                                                            {
                                                                let meta = __CALLSITE.metadata();
                                                                ::tracing::Event::dispatch(meta, &value_set);
                                                                ;
                                                            })({
                                                        #[allow(unused_imports)]
                                                        use ::tracing::field::{debug, display, Value};
                                                        __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&src_tty)
                                                                                    as &dyn ::tracing::field::Value)),
                                                                        (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&dst_tty)
                                                                                    as &dyn ::tracing::field::Value)),
                                                                        (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&src_obj)
                                                                                    as &dyn ::tracing::field::Value)),
                                                                        (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&dst_obj)
                                                                                    as &dyn ::tracing::field::Value))])
                                                    });
                                            } else { ; }
                                        };
                                        self.sub_types(src_obj, dst_obj, location.to_locations(),
                                                ConstraintCategory::Cast {
                                                    is_raw_ptr_dyn_type_cast: true,
                                                    is_implicit_coercion: false,
                                                    unsize_to: None,
                                                }).unwrap();
                                    }
                                    (None, None) => {
                                        let src_lt = self.universal_regions.to_region_vid(src_lt);
                                        let dst_lt = self.universal_regions.to_region_vid(dst_lt);
                                        self.constraints.outlives_constraints.push(OutlivesConstraint {
                                                sup: src_lt,
                                                sub: dst_lt,
                                                locations: location.to_locations(),
                                                span: location.to_locations().span(self.body),
                                                category: ConstraintCategory::Cast {
                                                    is_raw_ptr_dyn_type_cast: true,
                                                    is_implicit_coercion: false,
                                                    unsize_to: None,
                                                },
                                                variance_info: ty::VarianceDiagInfo::default(),
                                                from_closure: false,
                                            });
                                    }
                                    (None, Some(_)) =>
                                        ::rustc_middle::util::bug::bug_fmt(format_args!("introducing a principal should have errored in HIR typeck")),
                                    (Some(_), None) => {
                                        ::rustc_middle::util::bug::bug_fmt(format_args!("dropping the principal should have been an unsizing cast"))
                                    }
                                }
                            }
                        }
                        CastKind::Transmute => {
                            let ty_from = op.ty(self.body, tcx);
                            match ty_from.kind() {
                                ty::Pat(base, _) if base == ty => {}
                                _ => {
                                    crate::type_check::mirbug(self.tcx(), self.last_span,
                                        ::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                        self.body().source.def_id(), rvalue,
                                                        format_args!("Unexpected CastKind::Transmute {0:?} -> {1:?}, which is not permitted in Analysis MIR",
                                                            ty_from, ty)))
                                            }))
                                }
                            }
                        }
                        CastKind::Subtype => {
                            ::rustc_middle::util::bug::bug_fmt(format_args!("CastKind::Subtype shouldn\'t exist in borrowck"))
                        }
                    }
                }
                Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
                    self.add_reborrow_constraint(location, *region,
                        borrowed_place);
                }
                Rvalue::Reborrow(target, mutability, borrowed_place) => {
                    self.add_generic_reborrow_constraint(*mutability, location,
                        borrowed_place, *target);
                }
                Rvalue::BinaryOp(BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le
                    | BinOp::Gt | BinOp::Ge, (left, right)) => {
                    let ty_left = left.ty(self.body, tcx);
                    match ty_left.kind() {
                        ty::RawPtr(_, _) | ty::FnPtr(..) => {
                            let ty_right = right.ty(self.body, tcx);
                            let common_ty =
                                self.infcx.next_ty_var(self.body.source_info(location).span);
                            self.sub_types(ty_left, common_ty, location.to_locations(),
                                    ConstraintCategory::CallArgument(None)).unwrap_or_else(|err|
                                    {
                                        ::rustc_middle::util::bug::bug_fmt(format_args!("Could not equate type variable with {0:?}: {1:?}",
                                                ty_left, err))
                                    });
                            if let Err(terr) =
                                    self.sub_types(ty_right, common_ty, location.to_locations(),
                                        ConstraintCategory::CallArgument(None)) {
                                {
                                    crate::type_check::mirbug(self.tcx(), self.last_span,
                                        ::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                        self.body().source.def_id(), rvalue,
                                                        format_args!("unexpected comparison types {0:?} and {1:?} yields {2:?}",
                                                            ty_left, ty_right, terr)))
                                            }))
                                }
                            }
                        }
                        ty::Int(_) | ty::Uint(_) | ty::Bool | ty::Char |
                            ty::Float(_) if ty_left == right.ty(self.body, tcx) => {}
                        _ => {
                            crate::type_check::mirbug(self.tcx(), self.last_span,
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                self.body().source.def_id(), rvalue,
                                                format_args!("unexpected comparison types {0:?} and {1:?}",
                                                    ty_left, right.ty(self.body, tcx))))
                                    }))
                        }
                    }
                }
                Rvalue::WrapUnsafeBinder(op, ty) => {
                    let operand_ty = op.ty(self.body, self.tcx());
                    let ty::UnsafeBinder(binder_ty) =
                        *ty.kind() else {
                            ::core::panicking::panic("internal error: entered unreachable code");
                        };
                    let expected_ty =
                        self.infcx.instantiate_binder_with_fresh_vars(self.body().source_info(location).span,
                            BoundRegionConversionTime::HigherRankedType,
                            binder_ty.into());
                    self.sub_types(operand_ty, expected_ty,
                            location.to_locations(),
                            ConstraintCategory::Boring).unwrap();
                }
                Rvalue::Use(_, _) | Rvalue::UnaryOp(_, _) |
                    Rvalue::CopyForDeref(_) | Rvalue::BinaryOp(..) |
                    Rvalue::RawPtr(..) | Rvalue::ThreadLocalRef(..) |
                    Rvalue::Discriminant(..) => {}
            }
        }
    }
}#[instrument(skip(self), level = "debug")]
995    fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
996        self.super_rvalue(rvalue, location);
997        let tcx = self.tcx();
998        let span = self.body.source_info(location).span;
999        match rvalue {
1000            Rvalue::Aggregate(ak, ops) => self.check_aggregate_rvalue(rvalue, ak, ops, location),
1001
1002            Rvalue::Repeat(operand, len) => {
1003                let array_ty = rvalue.ty(self.body.local_decls(), tcx);
1004                self.prove_clause(
1005                    ty::ClauseKind::WellFormed(array_ty.into()),
1006                    Locations::Single(location),
1007                    ConstraintCategory::Boring,
1008                );
1009
1010                // If the length cannot be evaluated we must assume that the length can be larger
1011                // than 1.
1012                // If the length is larger than 1, the repeat expression will need to copy the
1013                // element, so we require the `Copy` trait.
1014                if len.try_to_target_usize(tcx).is_none_or(|len| len > 1) {
1015                    match operand {
1016                        Operand::Copy(..) | Operand::Constant(..) | Operand::RuntimeChecks(_) => {
1017                            // These are always okay: direct use of a const, or a value that can
1018                            // evidently be copied.
1019                        }
1020                        Operand::Move(place) => {
1021                            // Make sure that repeated elements implement `Copy`.
1022                            let ty = place.ty(self.body, tcx).ty;
1023                            let trait_ref = ty::TraitRef::new(
1024                                tcx,
1025                                tcx.require_lang_item(LangItem::Copy, span),
1026                                [ty],
1027                            );
1028
1029                            self.prove_trait_ref(
1030                                trait_ref,
1031                                Locations::Single(location),
1032                                ConstraintCategory::CopyBound,
1033                            );
1034                        }
1035                    }
1036                }
1037            }
1038
1039            Rvalue::Cast(cast_kind, op, ty) => {
1040                match *cast_kind {
1041                    CastKind::PointerCoercion(
1042                        PointerCoercion::ReifyFnPointer(target_safety),
1043                        coercion_source,
1044                    ) => {
1045                        let is_implicit_coercion = coercion_source == CoercionSource::Implicit;
1046                        let src_ty = op.ty(self.body, tcx);
1047                        let mut src_sig = src_ty.fn_sig(tcx);
1048                        if let ty::FnDef(def_id, _) = *src_ty.kind()
1049                            && let ty::FnPtr(_, target_hdr) = *ty.kind()
1050                            && tcx.codegen_fn_attrs(def_id).safe_target_features
1051                            && target_hdr.safety().is_safe()
1052                            && let Some(safe_sig) = tcx.adjust_target_feature_sig(
1053                                def_id,
1054                                src_sig,
1055                                self.body.source.def_id(),
1056                            )
1057                        {
1058                            src_sig = safe_sig;
1059                        }
1060
1061                        if src_sig.safety().is_safe() && target_safety.is_unsafe() {
1062                            src_sig = tcx.safe_to_unsafe_sig(src_sig);
1063                        }
1064
1065                        // HACK: This shouldn't be necessary... We can remove this when we actually
1066                        // get binders with where clauses, then elaborate implied bounds into that
1067                        // binder, and implement a higher-ranked subtyping algorithm that actually
1068                        // respects these implied bounds.
1069                        //
1070                        // This protects against the case where we are casting from a higher-ranked
1071                        // fn item to a non-higher-ranked fn pointer, where the cast throws away
1072                        // implied bounds that would've needed to be checked at the call site. This
1073                        // only works when we're casting to a non-higher-ranked fn ptr, since
1074                        // placeholders in the target signature could have untracked implied
1075                        // bounds, resulting in incorrect errors.
1076                        //
1077                        // We check that this signature is WF before subtyping the signature with
1078                        // the target fn sig.
1079                        if src_sig.has_bound_regions()
1080                            && let ty::FnPtr(target_fn_tys, target_hdr) = *ty.kind()
1081                            && let target_sig = target_fn_tys.with(target_hdr)
1082                            && let Some(target_sig) = target_sig.no_bound_vars()
1083                        {
1084                            let src_sig = self.infcx.instantiate_binder_with_fresh_vars(
1085                                span,
1086                                BoundRegionConversionTime::HigherRankedType,
1087                                src_sig,
1088                            );
1089                            let src_ty = Ty::new_fn_ptr(self.tcx(), ty::Binder::dummy(src_sig));
1090                            self.prove_clause(
1091                                ty::ClauseKind::WellFormed(src_ty.into()),
1092                                location.to_locations(),
1093                                ConstraintCategory::Cast {
1094                                    is_raw_ptr_dyn_type_cast: false,
1095                                    is_implicit_coercion,
1096                                    unsize_to: None,
1097                                },
1098                            );
1099
1100                            let src_ty =
1101                                self.normalize(ty::Unnormalized::new_wip(src_ty), location);
1102                            if let Err(terr) = self.sub_types(
1103                                src_ty,
1104                                *ty,
1105                                location.to_locations(),
1106                                ConstraintCategory::Cast {
1107                                    is_raw_ptr_dyn_type_cast: false,
1108                                    is_implicit_coercion,
1109                                    unsize_to: None,
1110                                },
1111                            ) {
1112                                span_mirbug!(
1113                                    self,
1114                                    rvalue,
1115                                    "equating {:?} with {:?} yields {:?}",
1116                                    target_sig,
1117                                    src_sig,
1118                                    terr
1119                                );
1120                            };
1121                        }
1122
1123                        let src_ty = Ty::new_fn_ptr(tcx, src_sig);
1124                        // HACK: We want to assert that the signature of the source fn is
1125                        // well-formed, because we don't enforce that via the WF of FnDef
1126                        // types normally. This should be removed when we improve the tracking
1127                        // of implied bounds of fn signatures.
1128                        self.prove_clause(
1129                            ty::ClauseKind::WellFormed(src_ty.into()),
1130                            location.to_locations(),
1131                            ConstraintCategory::Cast {
1132                                is_raw_ptr_dyn_type_cast: false,
1133                                is_implicit_coercion,
1134                                unsize_to: None,
1135                            },
1136                        );
1137
1138                        // The type that we see in the fcx is like
1139                        // `foo::<'a, 'b>`, where `foo` is the path to a
1140                        // function definition. When we extract the
1141                        // signature, it comes from the `fn_sig` query,
1142                        // and hence may contain unnormalized results.
1143                        let src_ty = self.normalize(ty::Unnormalized::new_wip(src_ty), location);
1144                        if let Err(terr) = self.sub_types(
1145                            src_ty,
1146                            *ty,
1147                            location.to_locations(),
1148                            ConstraintCategory::Cast {
1149                                is_raw_ptr_dyn_type_cast: false,
1150                                is_implicit_coercion,
1151                                unsize_to: None,
1152                            },
1153                        ) {
1154                            span_mirbug!(
1155                                self,
1156                                rvalue,
1157                                "equating {:?} with {:?} yields {:?}",
1158                                src_ty,
1159                                ty,
1160                                terr
1161                            );
1162                        }
1163                    }
1164
1165                    CastKind::PointerCoercion(
1166                        PointerCoercion::ClosureFnPointer(safety),
1167                        coercion_source,
1168                    ) => {
1169                        let sig = match op.ty(self.body, tcx).kind() {
1170                            ty::Closure(_, args) => args.as_closure().sig(),
1171                            _ => bug!(),
1172                        };
1173                        let ty_fn_ptr_from =
1174                            Ty::new_fn_ptr(tcx, tcx.signature_unclosure(sig, safety));
1175
1176                        let is_implicit_coercion = coercion_source == CoercionSource::Implicit;
1177                        if let Err(terr) = self.sub_types(
1178                            ty_fn_ptr_from,
1179                            *ty,
1180                            location.to_locations(),
1181                            ConstraintCategory::Cast {
1182                                is_raw_ptr_dyn_type_cast: false,
1183                                is_implicit_coercion,
1184                                unsize_to: None,
1185                            },
1186                        ) {
1187                            span_mirbug!(
1188                                self,
1189                                rvalue,
1190                                "equating {:?} with {:?} yields {:?}",
1191                                ty_fn_ptr_from,
1192                                ty,
1193                                terr
1194                            );
1195                        }
1196                    }
1197
1198                    CastKind::PointerCoercion(
1199                        PointerCoercion::UnsafeFnPointer,
1200                        coercion_source,
1201                    ) => {
1202                        let fn_sig = op.ty(self.body, tcx).fn_sig(tcx);
1203
1204                        // The type that we see in the fcx is like
1205                        // `foo::<'a, 'b>`, where `foo` is the path to a
1206                        // function definition. When we extract the
1207                        // signature, it comes from the `fn_sig` query,
1208                        // and hence may contain unnormalized results.
1209                        let fn_sig = self.normalize(ty::Unnormalized::new_wip(fn_sig), location);
1210
1211                        let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
1212
1213                        let is_implicit_coercion = coercion_source == CoercionSource::Implicit;
1214                        if let Err(terr) = self.sub_types(
1215                            ty_fn_ptr_from,
1216                            *ty,
1217                            location.to_locations(),
1218                            ConstraintCategory::Cast {
1219                                is_raw_ptr_dyn_type_cast: false,
1220                                is_implicit_coercion,
1221                                unsize_to: None,
1222                            },
1223                        ) {
1224                            span_mirbug!(
1225                                self,
1226                                rvalue,
1227                                "equating {:?} with {:?} yields {:?}",
1228                                ty_fn_ptr_from,
1229                                ty,
1230                                terr
1231                            );
1232                        }
1233                    }
1234
1235                    CastKind::PointerCoercion(PointerCoercion::Unsize, coercion_source) => {
1236                        let &ty = ty;
1237                        let trait_ref = ty::TraitRef::new(
1238                            tcx,
1239                            tcx.require_lang_item(LangItem::CoerceUnsized, span),
1240                            [op.ty(self.body, tcx), ty],
1241                        );
1242
1243                        let is_implicit_coercion = coercion_source == CoercionSource::Implicit;
1244                        let unsize_to = fold_regions(tcx, ty, |r, _| {
1245                            if let ty::ReVar(_) = r.kind() { tcx.lifetimes.re_erased } else { r }
1246                        });
1247                        self.prove_trait_ref(
1248                            trait_ref,
1249                            location.to_locations(),
1250                            ConstraintCategory::Cast {
1251                                is_raw_ptr_dyn_type_cast: false,
1252                                is_implicit_coercion,
1253                                unsize_to: Some(unsize_to),
1254                            },
1255                        );
1256                    }
1257
1258                    CastKind::PointerCoercion(
1259                        PointerCoercion::MutToConstPointer,
1260                        coercion_source,
1261                    ) => {
1262                        let ty::RawPtr(ty_from, hir::Mutability::Mut) =
1263                            op.ty(self.body, tcx).kind()
1264                        else {
1265                            span_mirbug!(self, rvalue, "unexpected base type for cast {:?}", ty,);
1266                            return;
1267                        };
1268                        let ty::RawPtr(ty_to, hir::Mutability::Not) = ty.kind() else {
1269                            span_mirbug!(self, rvalue, "unexpected target type for cast {:?}", ty,);
1270                            return;
1271                        };
1272                        let is_implicit_coercion = coercion_source == CoercionSource::Implicit;
1273                        if let Err(terr) = self.sub_types(
1274                            *ty_from,
1275                            *ty_to,
1276                            location.to_locations(),
1277                            ConstraintCategory::Cast {
1278                                is_raw_ptr_dyn_type_cast: false,
1279                                is_implicit_coercion,
1280                                unsize_to: None,
1281                            },
1282                        ) {
1283                            span_mirbug!(
1284                                self,
1285                                rvalue,
1286                                "relating {:?} with {:?} yields {:?}",
1287                                ty_from,
1288                                ty_to,
1289                                terr
1290                            );
1291                        }
1292                    }
1293
1294                    CastKind::PointerCoercion(PointerCoercion::ArrayToPointer, coercion_source) => {
1295                        let ty_from = op.ty(self.body, tcx);
1296
1297                        let opt_ty_elem_mut = match ty_from.kind() {
1298                            ty::RawPtr(array_ty, array_mut) => match array_ty.kind() {
1299                                ty::Array(ty_elem, _) => Some((ty_elem, *array_mut)),
1300                                _ => None,
1301                            },
1302                            _ => None,
1303                        };
1304
1305                        let Some((ty_elem, ty_mut)) = opt_ty_elem_mut else {
1306                            span_mirbug!(
1307                                self,
1308                                rvalue,
1309                                "ArrayToPointer cast from unexpected type {:?}",
1310                                ty_from,
1311                            );
1312                            return;
1313                        };
1314
1315                        let (ty_to, ty_to_mut) = match ty.kind() {
1316                            ty::RawPtr(ty_to, ty_to_mut) => (ty_to, *ty_to_mut),
1317                            _ => {
1318                                span_mirbug!(
1319                                    self,
1320                                    rvalue,
1321                                    "ArrayToPointer cast to unexpected type {:?}",
1322                                    ty,
1323                                );
1324                                return;
1325                            }
1326                        };
1327
1328                        if ty_to_mut.is_mut() && ty_mut.is_not() {
1329                            span_mirbug!(
1330                                self,
1331                                rvalue,
1332                                "ArrayToPointer cast from const {:?} to mut {:?}",
1333                                ty,
1334                                ty_to
1335                            );
1336                            return;
1337                        }
1338
1339                        let is_implicit_coercion = coercion_source == CoercionSource::Implicit;
1340                        if let Err(terr) = self.sub_types(
1341                            *ty_elem,
1342                            *ty_to,
1343                            location.to_locations(),
1344                            ConstraintCategory::Cast {
1345                                is_raw_ptr_dyn_type_cast: false,
1346                                is_implicit_coercion,
1347                                unsize_to: None,
1348                            },
1349                        ) {
1350                            span_mirbug!(
1351                                self,
1352                                rvalue,
1353                                "relating {:?} with {:?} yields {:?}",
1354                                ty_elem,
1355                                ty_to,
1356                                terr
1357                            )
1358                        }
1359                    }
1360
1361                    CastKind::PointerExposeProvenance => {
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::Ptr(_) | CastTy::FnPtr), Some(CastTy::Int(_))) => (),
1367                            _ => {
1368                                span_mirbug!(
1369                                    self,
1370                                    rvalue,
1371                                    "Invalid PointerExposeProvenance cast {:?} -> {:?}",
1372                                    ty_from,
1373                                    ty
1374                                )
1375                            }
1376                        }
1377                    }
1378
1379                    CastKind::PointerWithExposedProvenance => {
1380                        let ty_from = op.ty(self.body, tcx);
1381                        let cast_ty_from = CastTy::from_ty(ty_from);
1382                        let cast_ty_to = CastTy::from_ty(*ty);
1383                        match (cast_ty_from, cast_ty_to) {
1384                            (Some(CastTy::Int(_)), Some(CastTy::Ptr(_))) => (),
1385                            _ => {
1386                                span_mirbug!(
1387                                    self,
1388                                    rvalue,
1389                                    "Invalid PointerWithExposedProvenance cast {:?} -> {:?}",
1390                                    ty_from,
1391                                    ty
1392                                )
1393                            }
1394                        }
1395                    }
1396                    CastKind::IntToInt => {
1397                        let ty_from = op.ty(self.body, tcx);
1398                        let cast_ty_from = CastTy::from_ty(ty_from);
1399                        let cast_ty_to = CastTy::from_ty(*ty);
1400                        match (cast_ty_from, cast_ty_to) {
1401                            (Some(CastTy::Int(_)), Some(CastTy::Int(_))) => (),
1402                            _ => {
1403                                span_mirbug!(
1404                                    self,
1405                                    rvalue,
1406                                    "Invalid IntToInt cast {:?} -> {:?}",
1407                                    ty_from,
1408                                    ty
1409                                )
1410                            }
1411                        }
1412                    }
1413                    CastKind::IntToFloat => {
1414                        let ty_from = op.ty(self.body, tcx);
1415                        let cast_ty_from = CastTy::from_ty(ty_from);
1416                        let cast_ty_to = CastTy::from_ty(*ty);
1417                        match (cast_ty_from, cast_ty_to) {
1418                            (Some(CastTy::Int(_)), Some(CastTy::Float)) => (),
1419                            _ => {
1420                                span_mirbug!(
1421                                    self,
1422                                    rvalue,
1423                                    "Invalid IntToFloat cast {:?} -> {:?}",
1424                                    ty_from,
1425                                    ty
1426                                )
1427                            }
1428                        }
1429                    }
1430                    CastKind::FloatToInt => {
1431                        let ty_from = op.ty(self.body, tcx);
1432                        let cast_ty_from = CastTy::from_ty(ty_from);
1433                        let cast_ty_to = CastTy::from_ty(*ty);
1434                        match (cast_ty_from, cast_ty_to) {
1435                            (Some(CastTy::Float), Some(CastTy::Int(_))) => (),
1436                            _ => {
1437                                span_mirbug!(
1438                                    self,
1439                                    rvalue,
1440                                    "Invalid FloatToInt cast {:?} -> {:?}",
1441                                    ty_from,
1442                                    ty
1443                                )
1444                            }
1445                        }
1446                    }
1447                    CastKind::FloatToFloat => {
1448                        let ty_from = op.ty(self.body, tcx);
1449                        let cast_ty_from = CastTy::from_ty(ty_from);
1450                        let cast_ty_to = CastTy::from_ty(*ty);
1451                        match (cast_ty_from, cast_ty_to) {
1452                            (Some(CastTy::Float), Some(CastTy::Float)) => (),
1453                            _ => {
1454                                span_mirbug!(
1455                                    self,
1456                                    rvalue,
1457                                    "Invalid FloatToFloat cast {:?} -> {:?}",
1458                                    ty_from,
1459                                    ty
1460                                )
1461                            }
1462                        }
1463                    }
1464                    CastKind::FnPtrToPtr => {
1465                        let ty_from = op.ty(self.body, tcx);
1466                        let cast_ty_from = CastTy::from_ty(ty_from);
1467                        let cast_ty_to = CastTy::from_ty(*ty);
1468                        match (cast_ty_from, cast_ty_to) {
1469                            (Some(CastTy::FnPtr), Some(CastTy::Ptr(_))) => (),
1470                            _ => {
1471                                span_mirbug!(
1472                                    self,
1473                                    rvalue,
1474                                    "Invalid FnPtrToPtr cast {:?} -> {:?}",
1475                                    ty_from,
1476                                    ty
1477                                )
1478                            }
1479                        }
1480                    }
1481                    CastKind::PtrToPtr => {
1482                        let ty_from = op.ty(self.body, tcx);
1483                        let Some(CastTy::Ptr(src)) = CastTy::from_ty(ty_from) else {
1484                            unreachable!();
1485                        };
1486                        let Some(CastTy::Ptr(dst)) = CastTy::from_ty(*ty) else {
1487                            unreachable!();
1488                        };
1489
1490                        if self.infcx.type_is_sized_modulo_regions(self.infcx.param_env, dst.ty) {
1491                            // Wide to thin ptr cast. This may even occur in an env with
1492                            // impossible predicates, such as `where dyn Trait: Sized`.
1493                            // In this case, we don't want to fall into the case below,
1494                            // since the types may not actually be equatable, but it's
1495                            // fine to perform this operation in an impossible env.
1496                            let trait_ref = ty::TraitRef::new(
1497                                tcx,
1498                                tcx.require_lang_item(LangItem::Sized, self.last_span),
1499                                [dst.ty],
1500                            );
1501                            self.prove_trait_ref(
1502                                trait_ref,
1503                                location.to_locations(),
1504                                ConstraintCategory::Cast {
1505                                    is_raw_ptr_dyn_type_cast: false,
1506                                    is_implicit_coercion: true,
1507                                    unsize_to: None,
1508                                },
1509                            );
1510                        } else if let ty::Dynamic(src_tty, src_lt) =
1511                            *self.struct_tail(src.ty, location).kind()
1512                            && let ty::Dynamic(dst_tty, dst_lt) =
1513                                *self.struct_tail(dst.ty, location).kind()
1514                        {
1515                            match (src_tty.principal(), dst_tty.principal()) {
1516                                (Some(_), Some(_)) => {
1517                                    // This checks (lifetime part of) vtable validity for pointer casts,
1518                                    // which is irrelevant when there are aren't principal traits on
1519                                    // both sides (aka only auto traits).
1520                                    //
1521                                    // Note that other checks (such as denying `dyn Send` -> `dyn
1522                                    // Debug`) are in `rustc_hir_typeck`.
1523
1524                                    // Remove auto traits.
1525                                    // Auto trait checks are handled in `rustc_hir_typeck`.
1526                                    let src_obj = Ty::new_dynamic(
1527                                        tcx,
1528                                        tcx.mk_poly_existential_predicates(
1529                                            &src_tty.without_auto_traits().collect::<Vec<_>>(),
1530                                        ),
1531                                        src_lt,
1532                                    );
1533                                    let dst_obj = Ty::new_dynamic(
1534                                        tcx,
1535                                        tcx.mk_poly_existential_predicates(
1536                                            &dst_tty.without_auto_traits().collect::<Vec<_>>(),
1537                                        ),
1538                                        dst_lt,
1539                                    );
1540
1541                                    debug!(?src_tty, ?dst_tty, ?src_obj, ?dst_obj);
1542
1543                                    // Trait parameters are invariant, the only part that actually has
1544                                    // subtyping here is the lifetime bound of the dyn-type.
1545                                    //
1546                                    // For example in `dyn Trait<'a> + 'b <: dyn Trait<'c> + 'd`  we would
1547                                    // require that `'a == 'c` but only that `'b: 'd`.
1548                                    //
1549                                    // We must not allow freely casting lifetime bounds of dyn-types as it
1550                                    // may allow for inaccessible VTable methods being callable: #136702
1551                                    self.sub_types(
1552                                        src_obj,
1553                                        dst_obj,
1554                                        location.to_locations(),
1555                                        ConstraintCategory::Cast {
1556                                            is_raw_ptr_dyn_type_cast: true,
1557                                            is_implicit_coercion: false,
1558                                            unsize_to: None,
1559                                        },
1560                                    )
1561                                    .unwrap();
1562                                }
1563                                (None, None) => {
1564                                    // `struct_tail` returns regions which haven't been mapped
1565                                    // to nll vars yet so we do it here as `outlives_constraints`
1566                                    // expects nll vars.
1567                                    let src_lt = self.universal_regions.to_region_vid(src_lt);
1568                                    let dst_lt = self.universal_regions.to_region_vid(dst_lt);
1569
1570                                    // The principalless (no non-auto traits) case:
1571                                    // You can only cast `dyn Send + 'long` to `dyn Send + 'short`.
1572                                    self.constraints.outlives_constraints.push(
1573                                        OutlivesConstraint {
1574                                            sup: src_lt,
1575                                            sub: dst_lt,
1576                                            locations: location.to_locations(),
1577                                            span: location.to_locations().span(self.body),
1578                                            category: ConstraintCategory::Cast {
1579                                                is_raw_ptr_dyn_type_cast: true,
1580                                                is_implicit_coercion: false,
1581                                                unsize_to: None,
1582                                            },
1583                                            variance_info: ty::VarianceDiagInfo::default(),
1584                                            from_closure: false,
1585                                        },
1586                                    );
1587                                }
1588                                (None, Some(_)) => bug!(
1589                                    "introducing a principal should have errored in HIR typeck"
1590                                ),
1591                                (Some(_), None) => {
1592                                    bug!("dropping the principal should have been an unsizing cast")
1593                                }
1594                            }
1595                        }
1596                    }
1597                    CastKind::Transmute => {
1598                        let ty_from = op.ty(self.body, tcx);
1599                        match ty_from.kind() {
1600                            ty::Pat(base, _) if base == ty => {}
1601                            _ => span_mirbug!(
1602                                self,
1603                                rvalue,
1604                                "Unexpected CastKind::Transmute {ty_from:?} -> {ty:?}, which is not permitted in Analysis MIR",
1605                            ),
1606                        }
1607                    }
1608                    CastKind::Subtype => {
1609                        bug!("CastKind::Subtype shouldn't exist in borrowck")
1610                    }
1611                }
1612            }
1613
1614            Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
1615                self.add_reborrow_constraint(location, *region, borrowed_place);
1616            }
1617
1618            Rvalue::Reborrow(target, mutability, borrowed_place) => {
1619                self.add_generic_reborrow_constraint(
1620                    *mutability,
1621                    location,
1622                    borrowed_place,
1623                    *target,
1624                );
1625            }
1626
1627            Rvalue::BinaryOp(
1628                BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge,
1629                (left, right),
1630            ) => {
1631                let ty_left = left.ty(self.body, tcx);
1632                match ty_left.kind() {
1633                    // Types with regions are comparable if they have a common super-type.
1634                    ty::RawPtr(_, _) | ty::FnPtr(..) => {
1635                        let ty_right = right.ty(self.body, tcx);
1636                        let common_ty =
1637                            self.infcx.next_ty_var(self.body.source_info(location).span);
1638                        self.sub_types(
1639                            ty_left,
1640                            common_ty,
1641                            location.to_locations(),
1642                            ConstraintCategory::CallArgument(None),
1643                        )
1644                        .unwrap_or_else(|err| {
1645                            bug!("Could not equate type variable with {:?}: {:?}", ty_left, err)
1646                        });
1647                        if let Err(terr) = self.sub_types(
1648                            ty_right,
1649                            common_ty,
1650                            location.to_locations(),
1651                            ConstraintCategory::CallArgument(None),
1652                        ) {
1653                            span_mirbug!(
1654                                self,
1655                                rvalue,
1656                                "unexpected comparison types {:?} and {:?} yields {:?}",
1657                                ty_left,
1658                                ty_right,
1659                                terr
1660                            )
1661                        }
1662                    }
1663                    // For types with no regions we can just check that the
1664                    // both operands have the same type.
1665                    ty::Int(_) | ty::Uint(_) | ty::Bool | ty::Char | ty::Float(_)
1666                        if ty_left == right.ty(self.body, tcx) => {}
1667                    // Other types are compared by trait methods, not by
1668                    // `Rvalue::BinaryOp`.
1669                    _ => span_mirbug!(
1670                        self,
1671                        rvalue,
1672                        "unexpected comparison types {:?} and {:?}",
1673                        ty_left,
1674                        right.ty(self.body, tcx)
1675                    ),
1676                }
1677            }
1678
1679            Rvalue::WrapUnsafeBinder(op, ty) => {
1680                let operand_ty = op.ty(self.body, self.tcx());
1681                let ty::UnsafeBinder(binder_ty) = *ty.kind() else {
1682                    unreachable!();
1683                };
1684                let expected_ty = self.infcx.instantiate_binder_with_fresh_vars(
1685                    self.body().source_info(location).span,
1686                    BoundRegionConversionTime::HigherRankedType,
1687                    binder_ty.into(),
1688                );
1689                self.sub_types(
1690                    operand_ty,
1691                    expected_ty,
1692                    location.to_locations(),
1693                    ConstraintCategory::Boring,
1694                )
1695                .unwrap();
1696            }
1697
1698            Rvalue::Use(_, _)
1699            | Rvalue::UnaryOp(_, _)
1700            | Rvalue::CopyForDeref(_)
1701            | Rvalue::BinaryOp(..)
1702            | Rvalue::RawPtr(..)
1703            | Rvalue::ThreadLocalRef(..)
1704            | Rvalue::Discriminant(..) => {}
1705        }
1706    }
1707
1708    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("visit_operand",
                                    "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1708u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("op")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("op");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("location")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("location");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&op)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&location)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.super_operand(op, location);
            if let Operand::Constant(constant) = op {
                let maybe_uneval =
                    match constant.const_ {
                        Const::Val(..) | Const::Ty(_, _) => None,
                        Const::Unevaluated(uv, _) => Some(uv),
                    };
                if let Some(uv) = maybe_uneval {
                    if uv.promoted.is_none() {
                        let tcx = self.tcx();
                        let def_id = uv.def;
                        if tcx.def_kind(def_id) == DefKind::AnonConst &&
                                tcx.anon_const_kind(def_id) ==
                                    ty::AnonConstKind::NonTypeSystemInline {
                            let def_id = def_id.expect_local();
                            let predicates =
                                self.prove_closure_bounds(tcx, def_id, uv.args, location);
                            self.normalize_and_prove_instantiated_predicates(def_id.to_def_id(),
                                predicates, location.to_locations());
                        }
                    }
                }
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
1709    fn visit_operand(&mut self, op: &Operand<'tcx>, location: Location) {
1710        self.super_operand(op, location);
1711        if let Operand::Constant(constant) = op {
1712            let maybe_uneval = match constant.const_ {
1713                Const::Val(..) | Const::Ty(_, _) => None,
1714                Const::Unevaluated(uv, _) => Some(uv),
1715            };
1716
1717            if let Some(uv) = maybe_uneval {
1718                if uv.promoted.is_none() {
1719                    let tcx = self.tcx();
1720                    let def_id = uv.def;
1721                    if tcx.def_kind(def_id) == DefKind::AnonConst
1722                        && tcx.anon_const_kind(def_id) == ty::AnonConstKind::NonTypeSystemInline
1723                    {
1724                        let def_id = def_id.expect_local();
1725                        let predicates = self.prove_closure_bounds(tcx, def_id, uv.args, location);
1726                        self.normalize_and_prove_instantiated_predicates(
1727                            def_id.to_def_id(),
1728                            predicates,
1729                            location.to_locations(),
1730                        );
1731                    }
1732                }
1733            }
1734        }
1735    }
1736
1737    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("visit_const_operand",
                                    "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1737u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("constant")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("constant");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("location")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("location");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&constant)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&location)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            self.super_const_operand(constant, location);
            let ty = constant.const_.ty();
            self.infcx.tcx.for_each_free_region(&ty,
                |live_region|
                    {
                        let live_region_vid =
                            self.universal_regions.to_region_vid(live_region);
                        self.constraints.liveness_constraints.add_location(live_region_vid,
                            location);
                    });
            let locations = location.to_locations();
            if let Some(annotation_index) = constant.user_ty {
                if let Err(terr) =
                        self.relate_type_and_user_type(constant.const_.ty(),
                            ty::Invariant,
                            &UserTypeProjection {
                                    base: annotation_index,
                                    projs: ::alloc::vec::Vec::new(),
                                }, locations,
                            ConstraintCategory::TypeAnnotation(AnnotationSource::GenericArg))
                    {
                    let annotation =
                        &self.user_type_annotations[annotation_index];
                    {
                        crate::type_check::mirbug(self.tcx(), self.last_span,
                            ::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                            self.body().source.def_id(), constant,
                                            format_args!("bad constant user type {0:?} vs {1:?}: {2:?}",
                                                annotation, constant.const_.ty(), terr)))
                                }))
                    };
                }
            } else {
                let tcx = self.tcx();
                let maybe_uneval =
                    match constant.const_ {
                        Const::Ty(_, ct) =>
                            match ct.kind() {
                                ty::ConstKind::Alias(_, alias_const) =>
                                    match alias_const.kind {
                                        ty::AliasConstKind::Projection { def_id } |
                                            ty::AliasConstKind::Inherent { def_id } |
                                            ty::AliasConstKind::Free { def_id } |
                                            ty::AliasConstKind::Anon { def_id } =>
                                            Some(UnevaluatedConst {
                                                    def: def_id,
                                                    args: alias_const.args,
                                                    promoted: None,
                                                }),
                                    },
                                _ => None,
                            },
                        Const::Unevaluated(uv, _) => Some(uv),
                        _ => None,
                    };
                if let Some(uv) = maybe_uneval {
                    if let Some(promoted) = uv.promoted {
                        let promoted_body = &self.promoted[promoted];
                        self.check_promoted(promoted_body, location);
                        let promoted_ty = promoted_body.return_ty();
                        if let Err(terr) =
                                self.eq_types(ty, promoted_ty, locations,
                                    ConstraintCategory::Boring) {
                            {
                                crate::type_check::mirbug(self.tcx(), self.last_span,
                                    ::alloc::__export::must_use({
                                            ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                    self.body().source.def_id(), promoted,
                                                    format_args!("bad promoted type ({0:?}: {1:?}): {2:?}", ty,
                                                        promoted_ty, terr)))
                                        }))
                            };
                        };
                    } else {
                        self.ascribe_user_type(constant.const_.ty(),
                            ty::UserType::new(ty::UserTypeKind::TypeOf(uv.def,
                                    UserArgs { args: uv.args, user_self_ty: None })),
                            locations.span(self.body));
                    }
                } else if let Some(static_def_id) =
                        constant.check_static_ptr(tcx) {
                    let unnormalized_ty =
                        tcx.type_of(static_def_id).instantiate_identity();
                    let normalized_ty =
                        self.normalize(unnormalized_ty, locations);
                    let literal_ty =
                        constant.const_.ty().builtin_deref(true).unwrap();
                    if let Err(terr) =
                            self.eq_types(literal_ty, normalized_ty, locations,
                                ConstraintCategory::Boring) {
                        {
                            crate::type_check::mirbug(self.tcx(), self.last_span,
                                ::alloc::__export::must_use({
                                        ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                                self.body().source.def_id(), constant,
                                                format_args!("bad static type {0:?} ({1:?})", constant,
                                                    terr)))
                                    }))
                        };
                    }
                } else if let Const::Ty(_, ct) = constant.const_ &&
                        let ty::ConstKind::Param(p) = ct.kind() {
                    let body_def_id =
                        self.universal_regions.defining_ty.def_id();
                    let const_param =
                        tcx.generics_of(body_def_id).const_param(p, tcx);
                    self.ascribe_user_type(constant.const_.ty(),
                        ty::UserType::new(ty::UserTypeKind::TypeOf(const_param.def_id,
                                UserArgs {
                                    args: self.universal_regions.defining_ty.args(),
                                    user_self_ty: None,
                                })), locations.span(self.body));
                }
                if let ty::FnDef(def_id, args) = *constant.const_.ty().kind()
                    {
                    let args = args.no_bound_vars().unwrap();
                    let instantiated_predicates =
                        tcx.predicates_of(def_id).instantiate(tcx, args);
                    self.normalize_and_prove_instantiated_predicates(def_id,
                        instantiated_predicates, locations);
                    {
                        match (&tcx.trait_impl_of_assoc(def_id), &None) {
                            (left_val, right_val) => {
                                if !(*left_val == *right_val) {
                                    let kind = ::core::panicking::AssertKind::Eq;
                                    ::core::panicking::assert_failed(kind, &*left_val,
                                        &*right_val, ::core::option::Option::None);
                                }
                            }
                        }
                    };
                    self.prove_clauses(args.types().map(|ty|
                                ty::ClauseKind::WellFormed(ty.into())), locations,
                        ConstraintCategory::Boring);
                }
            }
        }
    }
}#[instrument(level = "debug", skip(self))]
1738    fn visit_const_operand(&mut self, constant: &ConstOperand<'tcx>, location: Location) {
1739        self.super_const_operand(constant, location);
1740        let ty = constant.const_.ty();
1741
1742        self.infcx.tcx.for_each_free_region(&ty, |live_region| {
1743            let live_region_vid = self.universal_regions.to_region_vid(live_region);
1744            self.constraints.liveness_constraints.add_location(live_region_vid, location);
1745        });
1746
1747        let locations = location.to_locations();
1748        if let Some(annotation_index) = constant.user_ty {
1749            if let Err(terr) = self.relate_type_and_user_type(
1750                constant.const_.ty(),
1751                ty::Invariant,
1752                &UserTypeProjection { base: annotation_index, projs: vec![] },
1753                locations,
1754                ConstraintCategory::TypeAnnotation(AnnotationSource::GenericArg),
1755            ) {
1756                let annotation = &self.user_type_annotations[annotation_index];
1757                span_mirbug!(
1758                    self,
1759                    constant,
1760                    "bad constant user type {:?} vs {:?}: {:?}",
1761                    annotation,
1762                    constant.const_.ty(),
1763                    terr,
1764                );
1765            }
1766        } else {
1767            let tcx = self.tcx();
1768            let maybe_uneval = match constant.const_ {
1769                Const::Ty(_, ct) => match ct.kind() {
1770                    ty::ConstKind::Alias(_, alias_const) => match alias_const.kind {
1771                        ty::AliasConstKind::Projection { def_id }
1772                        | ty::AliasConstKind::Inherent { def_id }
1773                        | ty::AliasConstKind::Free { def_id }
1774                        | ty::AliasConstKind::Anon { def_id } => Some(UnevaluatedConst {
1775                            def: def_id,
1776                            args: alias_const.args,
1777                            promoted: None,
1778                        }),
1779                    },
1780                    _ => None,
1781                },
1782                Const::Unevaluated(uv, _) => Some(uv),
1783                _ => None,
1784            };
1785
1786            if let Some(uv) = maybe_uneval {
1787                if let Some(promoted) = uv.promoted {
1788                    let promoted_body = &self.promoted[promoted];
1789                    self.check_promoted(promoted_body, location);
1790                    let promoted_ty = promoted_body.return_ty();
1791                    if let Err(terr) =
1792                        self.eq_types(ty, promoted_ty, locations, ConstraintCategory::Boring)
1793                    {
1794                        span_mirbug!(
1795                            self,
1796                            promoted,
1797                            "bad promoted type ({:?}: {:?}): {:?}",
1798                            ty,
1799                            promoted_ty,
1800                            terr
1801                        );
1802                    };
1803                } else {
1804                    self.ascribe_user_type(
1805                        constant.const_.ty(),
1806                        ty::UserType::new(ty::UserTypeKind::TypeOf(
1807                            uv.def,
1808                            UserArgs { args: uv.args, user_self_ty: None },
1809                        )),
1810                        locations.span(self.body),
1811                    );
1812                }
1813            } else if let Some(static_def_id) = constant.check_static_ptr(tcx) {
1814                let unnormalized_ty = tcx.type_of(static_def_id).instantiate_identity();
1815                let normalized_ty = self.normalize(unnormalized_ty, locations);
1816                let literal_ty = constant.const_.ty().builtin_deref(true).unwrap();
1817
1818                if let Err(terr) =
1819                    self.eq_types(literal_ty, normalized_ty, locations, ConstraintCategory::Boring)
1820                {
1821                    span_mirbug!(self, constant, "bad static type {:?} ({:?})", constant, terr);
1822                }
1823            } else if let Const::Ty(_, ct) = constant.const_
1824                && let ty::ConstKind::Param(p) = ct.kind()
1825            {
1826                let body_def_id = self.universal_regions.defining_ty.def_id();
1827                let const_param = tcx.generics_of(body_def_id).const_param(p, tcx);
1828                self.ascribe_user_type(
1829                    constant.const_.ty(),
1830                    ty::UserType::new(ty::UserTypeKind::TypeOf(
1831                        const_param.def_id,
1832                        UserArgs {
1833                            args: self.universal_regions.defining_ty.args(),
1834                            user_self_ty: None,
1835                        },
1836                    )),
1837                    locations.span(self.body),
1838                );
1839            }
1840
1841            if let ty::FnDef(def_id, args) = *constant.const_.ty().kind() {
1842                let args = args.no_bound_vars().unwrap();
1843                let instantiated_predicates = tcx.predicates_of(def_id).instantiate(tcx, args);
1844                self.normalize_and_prove_instantiated_predicates(
1845                    def_id,
1846                    instantiated_predicates,
1847                    locations,
1848                );
1849
1850                assert_eq!(tcx.trait_impl_of_assoc(def_id), None);
1851                self.prove_clauses(
1852                    args.types().map(|ty| ty::ClauseKind::WellFormed(ty.into())),
1853                    locations,
1854                    ConstraintCategory::Boring,
1855                );
1856            }
1857        }
1858    }
1859
1860    fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
1861        self.super_place(place, context, location);
1862        let tcx = self.tcx();
1863        let place_ty = place.ty(self.body, tcx);
1864        if let PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) = context {
1865            let trait_ref = ty::TraitRef::new(
1866                tcx,
1867                tcx.require_lang_item(LangItem::Copy, self.last_span),
1868                [place_ty.ty],
1869            );
1870
1871            // To have a `Copy` operand, the type `T` of the
1872            // value must be `Copy`. Note that we prove that `T: Copy`,
1873            // rather than using the `is_copy_modulo_regions`
1874            // test. This is important because
1875            // `is_copy_modulo_regions` ignores the resulting region
1876            // obligations and assumes they pass. This can result in
1877            // bounds from `Copy` impls being unsoundly ignored (e.g.,
1878            // #29149). Note that we decide to use `Copy` before knowing
1879            // whether the bounds fully apply: in effect, the rule is
1880            // that if a value of some type could implement `Copy`, then
1881            // it must.
1882            self.prove_trait_ref(trait_ref, location.to_locations(), ConstraintCategory::CopyBound);
1883        }
1884    }
1885
1886    fn visit_projection_elem(
1887        &mut self,
1888        place: PlaceRef<'tcx>,
1889        elem: PlaceElem<'tcx>,
1890        context: PlaceContext,
1891        location: Location,
1892    ) {
1893        let tcx = self.tcx();
1894        let base_ty = place.ty(self.body(), tcx);
1895        match elem {
1896            // All these projections don't add any constraints, so there's nothing to
1897            // do here. We check their invariants in the MIR validator after all.
1898            ProjectionElem::Deref
1899            | ProjectionElem::Index(_)
1900            | ProjectionElem::ConstantIndex { .. }
1901            | ProjectionElem::Subslice { .. }
1902            | ProjectionElem::Downcast(..) => {}
1903            ProjectionElem::Field(field, fty) => {
1904                let fty = self.normalize(ty::Unnormalized::new_wip(fty), location);
1905                let ty = PlaceTy::field_ty(tcx, base_ty.ty, base_ty.variant_index, field);
1906                let ty = self.normalize(ty, location);
1907                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/type_check/mod.rs:1907",
                        "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(1907u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                        ::tracing_core::field::FieldSet::new(&[{
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("fty")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("fty");
                                            NAME.as_str()
                                        },
                                        {
                                            const NAME:
                                                ::tracing::__macro_support::FieldName<{
                                                    ::tracing::__macro_support::FieldName::len("ty")
                                                }> =
                                                ::tracing::__macro_support::FieldName::new("ty");
                                            NAME.as_str()
                                        }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fty)
                                            as &dyn ::tracing::field::Value)),
                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&ty)
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(?fty, ?ty);
1908
1909                if let Err(terr) = self.relate_types(
1910                    ty,
1911                    context.ambient_variance(),
1912                    fty,
1913                    location.to_locations(),
1914                    ConstraintCategory::Boring,
1915                ) {
1916                    {
    crate::type_check::mirbug(self.tcx(), self.last_span,
        ::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                        self.body().source.def_id(), place,
                        format_args!("bad field access ({0:?}: {1:?}): {2:?}", ty,
                            fty, terr)))
            }))
};span_mirbug!(self, place, "bad field access ({:?}: {:?}): {:?}", ty, fty, terr);
1917                }
1918            }
1919            ProjectionElem::OpaqueCast(ty) => {
1920                let ty = self.normalize(ty::Unnormalized::new_wip(ty), location);
1921                self.relate_types(
1922                    ty,
1923                    context.ambient_variance(),
1924                    base_ty.ty,
1925                    location.to_locations(),
1926                    ConstraintCategory::TypeAnnotation(AnnotationSource::OpaqueCast),
1927                )
1928                .unwrap();
1929            }
1930            ProjectionElem::UnwrapUnsafeBinder(ty) => {
1931                let ty::UnsafeBinder(binder_ty) = *base_ty.ty.kind() else {
1932                    ::core::panicking::panic("internal error: entered unreachable code");unreachable!();
1933                };
1934                let found_ty = self.infcx.instantiate_binder_with_fresh_vars(
1935                    self.body.source_info(location).span,
1936                    BoundRegionConversionTime::HigherRankedType,
1937                    binder_ty.into(),
1938                );
1939                self.relate_types(
1940                    ty,
1941                    context.ambient_variance(),
1942                    found_ty,
1943                    location.to_locations(),
1944                    ConstraintCategory::Boring,
1945                )
1946                .unwrap();
1947            }
1948        }
1949    }
1950}
1951
1952impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
1953    fn check_call_dest(
1954        &mut self,
1955        term: &Terminator<'tcx>,
1956        sig: &ty::FnSig<'tcx>,
1957        destination: Place<'tcx>,
1958        is_diverging: bool,
1959        term_location: Location,
1960    ) {
1961        let tcx = self.tcx();
1962        if is_diverging {
1963            // The signature in this call can reference region variables,
1964            // so erase them before calling a query.
1965            let output_ty = self.tcx().erase_and_anonymize_regions(sig.output());
1966            if !output_ty
1967                .is_privately_uninhabited(self.tcx(), self.infcx.typing_env(self.infcx.param_env))
1968            {
1969                {
    crate::type_check::mirbug(self.tcx(), self.last_span,
        ::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                        self.body().source.def_id(), term,
                        format_args!("call to non-diverging function {0:?} w/o dest",
                            sig)))
            }))
};span_mirbug!(self, term, "call to non-diverging function {:?} w/o dest", sig);
1970            }
1971        } else {
1972            let dest_ty = destination.ty(self.body, tcx).ty;
1973            let dest_ty = self.normalize(ty::Unnormalized::new_wip(dest_ty), term_location);
1974            let category = match destination.as_local() {
1975                Some(RETURN_PLACE) => {
1976                    if let DefiningTy::Const(def_id, _) | DefiningTy::InlineConst(def_id, _) =
1977                        self.universal_regions.defining_ty
1978                    {
1979                        if tcx.is_static(def_id) {
1980                            ConstraintCategory::UseAsStatic
1981                        } else {
1982                            ConstraintCategory::UseAsConst
1983                        }
1984                    } else {
1985                        ConstraintCategory::Return(ReturnConstraint::Normal)
1986                    }
1987                }
1988                Some(l) if !self.body.local_decls[l].is_user_variable() => {
1989                    ConstraintCategory::Boring
1990                }
1991                // The return type of a call is interesting for diagnostics.
1992                _ => ConstraintCategory::Assignment,
1993            };
1994
1995            let locations = term_location.to_locations();
1996
1997            if let Err(terr) = self.sub_types(sig.output(), dest_ty, locations, category) {
1998                {
    crate::type_check::mirbug(self.tcx(), self.last_span,
        ::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                        self.body().source.def_id(), term,
                        format_args!("call dest mismatch ({0:?} <- {1:?}): {2:?}",
                            dest_ty, sig.output(), terr)))
            }))
};span_mirbug!(
1999                    self,
2000                    term,
2001                    "call dest mismatch ({:?} <- {:?}): {:?}",
2002                    dest_ty,
2003                    sig.output(),
2004                    terr
2005                );
2006            }
2007
2008            // When `unsized_fn_params` is not enabled,
2009            // this check is done at `visit_local_decl`.
2010            if self.tcx().features().unsized_fn_params() {
2011                let span = term.source_info.span;
2012                self.ensure_place_sized(dest_ty, span);
2013            }
2014        }
2015    }
2016
2017    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("check_call_inputs",
                                    "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2017u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("sig")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("sig");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("args")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("args");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&sig)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&args)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if args.len() < sig.inputs().len() ||
                    (args.len() > sig.inputs().len() && !sig.c_variadic()) {
                {
                    crate::type_check::mirbug(self.tcx(), self.last_span,
                        ::alloc::__export::must_use({
                                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                        self.body().source.def_id(), term,
                                        format_args!("call to {0:?} with wrong # of args", sig)))
                            }))
                };
            }
            let func_ty = func.ty(self.body, self.infcx.tcx);
            if let ty::FnDef(def_id, _) = *func_ty.kind() {
                if let Some(name @
                        (sym::simd_shuffle | sym::simd_insert | sym::simd_extract))
                        = self.tcx().intrinsic(def_id).map(|i| i.name) {
                    let idx = match name { sym::simd_shuffle => 2, _ => 1, };
                    if !#[allow(non_exhaustive_omitted_patterns)] match args[idx]
                                {
                                Spanned { node: Operand::Constant(_), .. } => true,
                                _ => false,
                            } {
                        self.tcx().dcx().emit_err(SimdIntrinsicArgConst {
                                span: term.source_info.span,
                                arg: idx + 1,
                                intrinsic: name.to_string(),
                            });
                    }
                }
            }
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/type_check/mod.rs:2053",
                                    "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(2053u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("func_ty")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("func_ty");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&func_ty)
                                                        as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            for (n, (fn_arg, op_arg)) in
                iter::zip(sig.inputs(), args).enumerate() {
                let op_arg_ty = op_arg.node.ty(self.body, self.tcx());
                let op_arg_ty =
                    self.normalize(ty::Unnormalized::new_wip(op_arg_ty),
                        term_location);
                let category =
                    if call_source.from_hir_call() {
                        ConstraintCategory::CallArgument(Some(self.infcx.tcx.erase_and_anonymize_regions(func_ty)))
                    } else { ConstraintCategory::Boring };
                if let Err(terr) =
                        self.sub_types(op_arg_ty, *fn_arg,
                            term_location.to_locations(), category) {
                    {
                        crate::type_check::mirbug(self.tcx(), self.last_span,
                            ::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                                            self.body().source.def_id(), term,
                                            format_args!("bad arg #{0:?} ({1:?} <- {2:?}): {3:?}", n,
                                                fn_arg, op_arg_ty, terr)))
                                }))
                    };
                }
            }
        }
    }
}#[instrument(level = "debug", skip(self, term, func, term_location, call_source))]
2018    fn check_call_inputs(
2019        &mut self,
2020        term: &Terminator<'tcx>,
2021        func: &Operand<'tcx>,
2022        sig: &ty::FnSig<'tcx>,
2023        args: &[Spanned<Operand<'tcx>>],
2024        term_location: Location,
2025        call_source: CallSource,
2026    ) {
2027        if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.c_variadic())
2028        {
2029            span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
2030        }
2031
2032        let func_ty = func.ty(self.body, self.infcx.tcx);
2033        if let ty::FnDef(def_id, _) = *func_ty.kind() {
2034            // Some of the SIMD intrinsics are special: they need a particular argument to be a
2035            // constant. (Eventually this should use const-generics, but those are not up for the
2036            // task yet: https://github.com/rust-lang/rust/issues/85229.)
2037            if let Some(name @ (sym::simd_shuffle | sym::simd_insert | sym::simd_extract)) =
2038                self.tcx().intrinsic(def_id).map(|i| i.name)
2039            {
2040                let idx = match name {
2041                    sym::simd_shuffle => 2,
2042                    _ => 1,
2043                };
2044                if !matches!(args[idx], Spanned { node: Operand::Constant(_), .. }) {
2045                    self.tcx().dcx().emit_err(SimdIntrinsicArgConst {
2046                        span: term.source_info.span,
2047                        arg: idx + 1,
2048                        intrinsic: name.to_string(),
2049                    });
2050                }
2051            }
2052        }
2053        debug!(?func_ty);
2054
2055        for (n, (fn_arg, op_arg)) in iter::zip(sig.inputs(), args).enumerate() {
2056            let op_arg_ty = op_arg.node.ty(self.body, self.tcx());
2057
2058            let op_arg_ty = self.normalize(ty::Unnormalized::new_wip(op_arg_ty), term_location);
2059            let category = if call_source.from_hir_call() {
2060                ConstraintCategory::CallArgument(Some(
2061                    self.infcx.tcx.erase_and_anonymize_regions(func_ty),
2062                ))
2063            } else {
2064                ConstraintCategory::Boring
2065            };
2066            if let Err(terr) =
2067                self.sub_types(op_arg_ty, *fn_arg, term_location.to_locations(), category)
2068            {
2069                span_mirbug!(
2070                    self,
2071                    term,
2072                    "bad arg #{:?} ({:?} <- {:?}): {:?}",
2073                    n,
2074                    fn_arg,
2075                    op_arg_ty,
2076                    terr
2077                );
2078            }
2079        }
2080    }
2081
2082    fn check_iscleanup(&mut self, block_data: &BasicBlockData<'tcx>) {
2083        let is_cleanup = block_data.is_cleanup;
2084        match block_data.terminator().kind {
2085            TerminatorKind::Goto { target } => {
2086                self.assert_iscleanup(block_data, target, is_cleanup)
2087            }
2088            TerminatorKind::SwitchInt { ref targets, .. } => {
2089                for target in targets.all_targets() {
2090                    self.assert_iscleanup(block_data, *target, is_cleanup);
2091                }
2092            }
2093            TerminatorKind::UnwindResume => {
2094                if !is_cleanup {
2095                    {
    crate::type_check::mirbug(self.tcx(), self.last_span,
        ::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                        self.body().source.def_id(), block_data,
                        format_args!("resume on non-cleanup block!")))
            }))
}span_mirbug!(self, block_data, "resume on non-cleanup block!")
2096                }
2097            }
2098            TerminatorKind::UnwindTerminate(_) => {
2099                if !is_cleanup {
2100                    {
    crate::type_check::mirbug(self.tcx(), self.last_span,
        ::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                        self.body().source.def_id(), block_data,
                        format_args!("terminate on non-cleanup block!")))
            }))
}span_mirbug!(self, block_data, "terminate on non-cleanup block!")
2101                }
2102            }
2103            TerminatorKind::Return => {
2104                if is_cleanup {
2105                    {
    crate::type_check::mirbug(self.tcx(), self.last_span,
        ::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                        self.body().source.def_id(), block_data,
                        format_args!("return on cleanup block")))
            }))
}span_mirbug!(self, block_data, "return on cleanup block")
2106                }
2107            }
2108            TerminatorKind::TailCall { .. } => {
2109                if is_cleanup {
2110                    {
    crate::type_check::mirbug(self.tcx(), self.last_span,
        ::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                        self.body().source.def_id(), block_data,
                        format_args!("tailcall on cleanup block")))
            }))
}span_mirbug!(self, block_data, "tailcall on cleanup block")
2111                }
2112            }
2113            TerminatorKind::CoroutineDrop { .. } => {
2114                if is_cleanup {
2115                    {
    crate::type_check::mirbug(self.tcx(), self.last_span,
        ::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                        self.body().source.def_id(), block_data,
                        format_args!("coroutine_drop in cleanup block")))
            }))
}span_mirbug!(self, block_data, "coroutine_drop in cleanup block")
2116                }
2117            }
2118            TerminatorKind::Yield { resume, drop, .. } => {
2119                if is_cleanup {
2120                    {
    crate::type_check::mirbug(self.tcx(), self.last_span,
        ::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                        self.body().source.def_id(), block_data,
                        format_args!("yield in cleanup block")))
            }))
}span_mirbug!(self, block_data, "yield in cleanup block")
2121                }
2122                self.assert_iscleanup(block_data, resume, is_cleanup);
2123                if let Some(drop) = drop {
2124                    self.assert_iscleanup(block_data, drop, is_cleanup);
2125                }
2126            }
2127            TerminatorKind::Unreachable => {}
2128            TerminatorKind::Drop { target, unwind, drop, .. } => {
2129                self.assert_iscleanup(block_data, target, is_cleanup);
2130                self.assert_iscleanup_unwind(block_data, unwind, is_cleanup);
2131                if let Some(drop) = drop {
2132                    self.assert_iscleanup(block_data, drop, is_cleanup);
2133                }
2134            }
2135            TerminatorKind::Assert { target, unwind, .. } => {
2136                self.assert_iscleanup(block_data, target, is_cleanup);
2137                self.assert_iscleanup_unwind(block_data, unwind, is_cleanup);
2138            }
2139            TerminatorKind::Call { ref target, unwind, .. } => {
2140                if let &Some(target) = target {
2141                    self.assert_iscleanup(block_data, target, is_cleanup);
2142                }
2143                self.assert_iscleanup_unwind(block_data, unwind, is_cleanup);
2144            }
2145            TerminatorKind::FalseEdge { real_target, imaginary_target } => {
2146                self.assert_iscleanup(block_data, real_target, is_cleanup);
2147                self.assert_iscleanup(block_data, imaginary_target, is_cleanup);
2148            }
2149            TerminatorKind::FalseUnwind { real_target, unwind } => {
2150                self.assert_iscleanup(block_data, real_target, is_cleanup);
2151                self.assert_iscleanup_unwind(block_data, unwind, is_cleanup);
2152            }
2153            TerminatorKind::InlineAsm { ref targets, unwind, .. } => {
2154                for &target in targets {
2155                    self.assert_iscleanup(block_data, target, is_cleanup);
2156                }
2157                self.assert_iscleanup_unwind(block_data, unwind, is_cleanup);
2158            }
2159        }
2160    }
2161
2162    fn assert_iscleanup(&mut self, ctxt: &dyn fmt::Debug, bb: BasicBlock, iscleanuppad: bool) {
2163        if self.body[bb].is_cleanup != iscleanuppad {
2164            {
    crate::type_check::mirbug(self.tcx(), self.last_span,
        ::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                        self.body().source.def_id(), ctxt,
                        format_args!("cleanuppad mismatch: {0:?} should be {1:?}",
                            bb, iscleanuppad)))
            }))
};span_mirbug!(self, ctxt, "cleanuppad mismatch: {:?} should be {:?}", bb, iscleanuppad);
2165        }
2166    }
2167
2168    fn assert_iscleanup_unwind(
2169        &mut self,
2170        ctxt: &dyn fmt::Debug,
2171        unwind: UnwindAction,
2172        is_cleanup: bool,
2173    ) {
2174        match unwind {
2175            UnwindAction::Cleanup(unwind) => {
2176                if is_cleanup {
2177                    {
    crate::type_check::mirbug(self.tcx(), self.last_span,
        ::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                        self.body().source.def_id(), ctxt,
                        format_args!("unwind on cleanup block")))
            }))
}span_mirbug!(self, ctxt, "unwind on cleanup block")
2178                }
2179                self.assert_iscleanup(ctxt, unwind, true);
2180            }
2181            UnwindAction::Continue => {
2182                if is_cleanup {
2183                    {
    crate::type_check::mirbug(self.tcx(), self.last_span,
        ::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                        self.body().source.def_id(), ctxt,
                        format_args!("unwind on cleanup block")))
            }))
}span_mirbug!(self, ctxt, "unwind on cleanup block")
2184                }
2185            }
2186            UnwindAction::Unreachable | UnwindAction::Terminate(_) => (),
2187        }
2188    }
2189
2190    fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
2191        let tcx = self.tcx();
2192
2193        // Erase the regions from `ty` to get a global type. The
2194        // `Sized` bound in no way depends on precise regions, so this
2195        // shouldn't affect `is_sized`.
2196        let erased_ty = tcx.erase_and_anonymize_regions(ty);
2197        // FIXME(#132279): Using `Ty::is_sized` causes us to incorrectly handle opaques here.
2198        if !erased_ty.is_sized(tcx, self.infcx.typing_env(self.infcx.param_env)) {
2199            // in current MIR construction, all non-control-flow rvalue
2200            // expressions evaluate through `as_temp` or `into` a return
2201            // slot or local, so to find all unsized rvalues it is enough
2202            // to check all temps, return slots and locals.
2203            if self.reported_errors.replace((ty, span)).is_none() {
2204                // While this is located in `nll::typeck` this error is not
2205                // an NLL error, it's a required check to prevent creation
2206                // of unsized rvalues in a call expression.
2207                self.tcx().dcx().emit_err(MoveUnsized { ty, span });
2208            }
2209        }
2210    }
2211
2212    fn aggregate_field_ty(
2213        &mut self,
2214        ak: &AggregateKind<'tcx>,
2215        field_index: FieldIdx,
2216        location: Location,
2217    ) -> Result<Ty<'tcx>, FieldAccessError> {
2218        let tcx = self.tcx();
2219
2220        match *ak {
2221            AggregateKind::Adt(adt_did, variant_index, args, _, active_field_index) => {
2222                let def = tcx.adt_def(adt_did);
2223                let variant = &def.variant(variant_index);
2224                let adj_field_index = active_field_index.unwrap_or(field_index);
2225                if let Some(field) = variant.fields.get(adj_field_index) {
2226                    Ok(self.normalize(field.ty(tcx, args), location))
2227                } else {
2228                    Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() })
2229                }
2230            }
2231            AggregateKind::Closure(_, args) => {
2232                match args.as_closure().upvar_tys().get(field_index.as_usize()) {
2233                    Some(ty) => Ok(*ty),
2234                    None => Err(FieldAccessError::OutOfRange {
2235                        field_count: args.as_closure().upvar_tys().len(),
2236                    }),
2237                }
2238            }
2239            AggregateKind::Coroutine(_, args) => {
2240                // It doesn't make sense to look at a field beyond the captured
2241                // upvars.
2242                // Otherwise it require a variant index, and are not initialized
2243                // in aggregate rvalues.
2244                let upvar_tys = &args.as_coroutine().upvar_tys();
2245                if let Some(ty) = upvar_tys.get(field_index.as_usize()) {
2246                    Ok(*ty)
2247                } else {
2248                    Err(FieldAccessError::OutOfRange { field_count: upvar_tys.len() })
2249                }
2250            }
2251            AggregateKind::CoroutineClosure(_, args) => {
2252                match args.as_coroutine_closure().upvar_tys().get(field_index.as_usize()) {
2253                    Some(ty) => Ok(*ty),
2254                    None => Err(FieldAccessError::OutOfRange {
2255                        field_count: args.as_coroutine_closure().upvar_tys().len(),
2256                    }),
2257                }
2258            }
2259            AggregateKind::Array(ty) => Ok(ty),
2260            AggregateKind::Tuple | AggregateKind::RawPtr(..) => {
2261                {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("This should have been covered in check_rvalues")));
};unreachable!("This should have been covered in check_rvalues");
2262            }
2263        }
2264    }
2265
2266    /// If this rvalue supports a user-given type annotation, then
2267    /// extract and return it. This represents the final type of the
2268    /// rvalue and will be unified with the inferred type.
2269    fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotationIndex> {
2270        match rvalue {
2271            Rvalue::Use(..)
2272            | Rvalue::ThreadLocalRef(..)
2273            | Rvalue::Repeat(..)
2274            | Rvalue::Ref(..)
2275            | Rvalue::Reborrow(..)
2276            | Rvalue::RawPtr(..)
2277            | Rvalue::Cast(..)
2278            | Rvalue::BinaryOp(..)
2279            | Rvalue::CopyForDeref(..)
2280            | Rvalue::UnaryOp(..)
2281            | Rvalue::Discriminant(..)
2282            | Rvalue::WrapUnsafeBinder(..) => None,
2283
2284            Rvalue::Aggregate(aggregate, _) => match **aggregate {
2285                AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
2286                AggregateKind::Array(_) => None,
2287                AggregateKind::Tuple => None,
2288                AggregateKind::Closure(_, _) => None,
2289                AggregateKind::Coroutine(_, _) => None,
2290                AggregateKind::CoroutineClosure(_, _) => None,
2291                AggregateKind::RawPtr(_, _) => None,
2292            },
2293        }
2294    }
2295
2296    fn check_aggregate_rvalue(
2297        &mut self,
2298        rvalue: &Rvalue<'tcx>,
2299        aggregate_kind: &AggregateKind<'tcx>,
2300        operands: &IndexSlice<FieldIdx, Operand<'tcx>>,
2301        location: Location,
2302    ) {
2303        let tcx = self.tcx();
2304
2305        self.prove_aggregate_predicates(aggregate_kind, location);
2306
2307        if *aggregate_kind == AggregateKind::Tuple {
2308            // tuple rvalue field type is always the type of the op. Nothing to check here.
2309            return;
2310        }
2311
2312        if let AggregateKind::RawPtr(..) = aggregate_kind {
2313            ::rustc_middle::util::bug::bug_fmt(format_args!("RawPtr should only be in runtime MIR"));bug!("RawPtr should only be in runtime MIR");
2314        }
2315
2316        for (i, operand) in operands.iter_enumerated() {
2317            let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
2318                Ok(field_ty) => field_ty,
2319                Err(FieldAccessError::OutOfRange { field_count }) => {
2320                    {
    crate::type_check::mirbug(self.tcx(), self.last_span,
        ::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                        self.body().source.def_id(), rvalue,
                        format_args!("accessed field #{0} but variant only has {1}",
                            i.as_u32(), field_count)))
            }))
};span_mirbug!(
2321                        self,
2322                        rvalue,
2323                        "accessed field #{} but variant only has {}",
2324                        i.as_u32(),
2325                        field_count,
2326                    );
2327                    continue;
2328                }
2329            };
2330            let operand_ty = operand.ty(self.body, tcx);
2331            let operand_ty = self.normalize(ty::Unnormalized::new_wip(operand_ty), location);
2332
2333            if let Err(terr) = self.sub_types(
2334                operand_ty,
2335                field_ty,
2336                location.to_locations(),
2337                ConstraintCategory::Boring,
2338            ) {
2339                {
    crate::type_check::mirbug(self.tcx(), self.last_span,
        ::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                        self.body().source.def_id(), rvalue,
                        format_args!("{0:?} is not a subtype of {1:?}: {2:?}",
                            operand_ty, field_ty, terr)))
            }))
};span_mirbug!(
2340                    self,
2341                    rvalue,
2342                    "{:?} is not a subtype of {:?}: {:?}",
2343                    operand_ty,
2344                    field_ty,
2345                    terr
2346                );
2347            }
2348        }
2349    }
2350
2351    /// Adds the constraints that arise from a borrow expression `&'a P` at the location `L`.
2352    ///
2353    /// # Parameters
2354    ///
2355    /// - `location`: the location `L` where the borrow expression occurs
2356    /// - `borrow_region`: the region `'a` associated with the borrow
2357    /// - `borrowed_place`: the place `P` being borrowed
2358    fn add_reborrow_constraint(
2359        &mut self,
2360        location: Location,
2361        borrow_region: ty::Region<'tcx>,
2362        borrowed_place: &Place<'tcx>,
2363    ) {
2364        // These constraints are only meaningful during borrowck:
2365        let Self { borrow_set, location_table, polonius_facts, constraints, .. } = self;
2366
2367        // In Polonius mode, we also push a `loan_issued_at` fact
2368        // linking the loan to the region (in some cases, though,
2369        // there is no loan associated with this borrow expression --
2370        // that occurs when we are borrowing an unsafe place, for
2371        // example).
2372        if let Some(polonius_facts) = polonius_facts {
2373            let _prof_timer = self.infcx.tcx.prof.generic_activity("polonius_fact_generation");
2374            if let Some(idxs) = borrow_set.borrows_at_location(&location) {
2375                let region_vid = borrow_region.as_var();
2376                for borrow_index in idxs {
2377                    polonius_facts.loan_issued_at.push((
2378                        region_vid.into(),
2379                        *borrow_index,
2380                        location_table.mid_index(location),
2381                    ));
2382                }
2383            }
2384        }
2385
2386        // If we are reborrowing the referent of another reference, we
2387        // need to add outlives relationships. In a case like `&mut
2388        // *p`, where the `p` has type `&'b mut Foo`, for example, we
2389        // need to ensure that `'b: 'a`.
2390
2391        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/type_check/mod.rs:2391",
                        "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(2391u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("add_reborrow_constraint({0:?}, {1:?}, {2:?})",
                                                    location, borrow_region, borrowed_place) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
2392            "add_reborrow_constraint({:?}, {:?}, {:?})",
2393            location, borrow_region, borrowed_place
2394        );
2395
2396        let tcx = self.infcx.tcx;
2397        let def = self.body.source.def_id().expect_local();
2398        let upvars = tcx.closure_captures(def);
2399        let field =
2400            path_utils::is_upvar_field_projection(tcx, upvars, borrowed_place.as_ref(), self.body);
2401        let category = if let Some(field) = field {
2402            ConstraintCategory::ClosureUpvar(field)
2403        } else {
2404            ConstraintCategory::Boring
2405        };
2406
2407        for (base, elem) in borrowed_place.as_ref().iter_projections().rev() {
2408            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/type_check/mod.rs:2408",
                        "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(2408u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("add_reborrow_constraint - iteration {0:?}",
                                                    elem) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("add_reborrow_constraint - iteration {:?}", elem);
2409
2410            match elem {
2411                ProjectionElem::Deref => {
2412                    let base_ty = base.ty(self.body, tcx).ty;
2413
2414                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/type_check/mod.rs:2414",
                        "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(2414u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("add_reborrow_constraint - base_ty = {0:?}",
                                                    base_ty) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
2415                    match base_ty.kind() {
2416                        ty::Ref(ref_region, _, mutbl) => {
2417                            constraints.outlives_constraints.push(OutlivesConstraint {
2418                                sup: ref_region.as_var(),
2419                                sub: borrow_region.as_var(),
2420                                locations: location.to_locations(),
2421                                span: location.to_locations().span(self.body),
2422                                category,
2423                                variance_info: ty::VarianceDiagInfo::default(),
2424                                from_closure: false,
2425                            });
2426
2427                            match mutbl {
2428                                hir::Mutability::Not => {
2429                                    // Immutable reference. We don't need the base
2430                                    // to be valid for the entire lifetime of
2431                                    // the borrow.
2432                                    break;
2433                                }
2434                                hir::Mutability::Mut => {
2435                                    // Mutable reference. We *do* need the base
2436                                    // to be valid, because after the base becomes
2437                                    // invalid, someone else can use our mutable deref.
2438
2439                                    // This is in order to make the following function
2440                                    // illegal:
2441                                    // ```
2442                                    // fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
2443                                    //     &mut *x
2444                                    // }
2445                                    // ```
2446                                    //
2447                                    // As otherwise you could clone `&mut T` using the
2448                                    // following function:
2449                                    // ```
2450                                    // fn bad(x: &mut T) -> (&mut T, &mut T) {
2451                                    //     let my_clone = unsafe_deref(&'a x);
2452                                    //     ENDREGION 'a;
2453                                    //     (my_clone, x)
2454                                    // }
2455                                    // ```
2456                                }
2457                            }
2458                        }
2459                        ty::RawPtr(..) => {
2460                            // deref of raw pointer, guaranteed to be valid
2461                            break;
2462                        }
2463                        ty::Adt(def, _) if def.is_box() => {
2464                            // deref of `Box`, need the base to be valid - propagate
2465                        }
2466                        _ => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected deref ty {0:?} in {1:?}",
        base_ty, borrowed_place))bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
2467                    }
2468                }
2469                ProjectionElem::Field(..)
2470                | ProjectionElem::Downcast(..)
2471                | ProjectionElem::OpaqueCast(..)
2472                | ProjectionElem::Index(..)
2473                | ProjectionElem::ConstantIndex { .. }
2474                | ProjectionElem::Subslice { .. }
2475                | ProjectionElem::UnwrapUnsafeBinder(_) => {
2476                    // other field access
2477                }
2478            }
2479        }
2480    }
2481
2482    fn add_generic_reborrow_constraint(
2483        &mut self,
2484        mutability: Mutability,
2485        location: Location,
2486        borrowed_place: &Place<'tcx>,
2487        dest_ty: Ty<'tcx>,
2488    ) {
2489        let Self { borrow_set, location_table, polonius_facts, constraints, infcx, body, .. } =
2490            self;
2491
2492        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/type_check/mod.rs:2492",
                        "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(2492u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("add_generic_reborrow_constraint({0:?}, {1:?}, {2:?}, {3:?})",
                                                    mutability, location, borrowed_place, dest_ty) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
2493            "add_generic_reborrow_constraint({:?}, {:?}, {:?}, {:?})",
2494            mutability, location, borrowed_place, dest_ty
2495        );
2496
2497        let tcx = infcx.tcx;
2498        let def = body.source.def_id().expect_local();
2499        let upvars = tcx.closure_captures(def);
2500        let field =
2501            path_utils::is_upvar_field_projection(tcx, upvars, borrowed_place.as_ref(), body);
2502        let category = if let Some(field) = field {
2503            ConstraintCategory::ClosureUpvar(field)
2504        } else {
2505            ConstraintCategory::Boring
2506        };
2507
2508        let borrowed_ty = borrowed_place.ty(self.body, tcx).ty;
2509
2510        let ty::Adt(dest_adt, dest_args) = dest_ty.kind() else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2511        let [dest_arg, ..] = ***dest_args else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2512        let ty::GenericArgKind::Lifetime(dest_region) = dest_arg.kind() else { ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!() };
2513        constraints.liveness_constraints.add_location(dest_region.as_var(), location);
2514
2515        // In Polonius mode, we also push a `loan_issued_at` fact
2516        // linking the loan to the region.
2517        if let Some(polonius_facts) = polonius_facts {
2518            let _prof_timer = infcx.tcx.prof.generic_activity("polonius_fact_generation");
2519            if let Some(borrows) = borrow_set.borrows_at_location(&location) {
2520                let region_vid = dest_region.as_var();
2521                for borrow_index in borrows {
2522                    polonius_facts.loan_issued_at.push((
2523                        region_vid.into(),
2524                        *borrow_index,
2525                        location_table.mid_index(location),
2526                    ));
2527                }
2528            }
2529        }
2530
2531        if mutability.is_not() {
2532            // FIXME(reborrow): for CoerceShared we need to relate the types manually, field by
2533            // field. We cannot just attempt to relate `T` and `<T as CoerceShared>::Target` by
2534            // calling relate_types as they are (generally) two unrelated user-defined ADTs, such as
2535            // `CustomMut<'a>` and `CustomRef<'a>`, or `CustomMut<'a, T>` and `CustomRef<'a, T>`.
2536            // Field-by-field relate_types is expected to work based on the wf-checks that the
2537            // CoerceShared trait performs.
2538            let ty::Adt(borrowed_adt, borrowed_args) = borrowed_ty.kind() else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
2539            let borrowed_fields = borrowed_adt.all_fields().collect::<Vec<_>>();
2540            for dest_field in dest_adt.all_fields() {
2541                let Some(borrowed_field) =
2542                    borrowed_fields.iter().find(|f| f.name == dest_field.name)
2543                else {
2544                    continue;
2545                };
2546                let dest_ty = dest_field.ty(tcx, dest_args).skip_norm_wip();
2547                let borrowed_ty = borrowed_field.ty(tcx, borrowed_args).skip_norm_wip();
2548                if let (
2549                    ty::Ref(borrow_region, _, Mutability::Mut),
2550                    ty::Ref(ref_region, _, Mutability::Not),
2551                ) = (borrowed_ty.kind(), dest_ty.kind())
2552                {
2553                    self.relate_types(
2554                        borrowed_ty.peel_refs(),
2555                        ty::Variance::Covariant,
2556                        dest_ty.peel_refs(),
2557                        location.to_locations(),
2558                        category,
2559                    )
2560                    .unwrap();
2561                    self.constraints.outlives_constraints.push(OutlivesConstraint {
2562                        sup: ref_region.as_var(),
2563                        sub: borrow_region.as_var(),
2564                        locations: location.to_locations(),
2565                        span: location.to_locations().span(self.body),
2566                        category,
2567                        variance_info: ty::VarianceDiagInfo::default(),
2568                        from_closure: false,
2569                    });
2570                } else {
2571                    self.relate_types(
2572                        borrowed_ty,
2573                        ty::Variance::Covariant,
2574                        dest_ty,
2575                        location.to_locations(),
2576                        category,
2577                    )
2578                    .unwrap();
2579                }
2580            }
2581        } else {
2582            // Exclusive reborrow
2583            self.relate_types(
2584                borrowed_ty,
2585                ty::Variance::Covariant,
2586                dest_ty,
2587                location.to_locations(),
2588                category,
2589            )
2590            .unwrap();
2591        }
2592    }
2593
2594    fn prove_aggregate_predicates(
2595        &mut self,
2596        aggregate_kind: &AggregateKind<'tcx>,
2597        location: Location,
2598    ) {
2599        let tcx = self.tcx();
2600
2601        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_borrowck/src/type_check/mod.rs:2601",
                        "rustc_borrowck::type_check", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_borrowck/src/type_check/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(2601u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_borrowck::type_check"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("prove_aggregate_predicates(aggregate_kind={0:?}, location={1:?})",
                                                    aggregate_kind, location) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!(
2602            "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
2603            aggregate_kind, location
2604        );
2605
2606        let (def_id, instantiated_predicates) = match *aggregate_kind {
2607            AggregateKind::Adt(adt_did, _, args, _, _) => {
2608                (adt_did, tcx.predicates_of(adt_did).instantiate(tcx, args))
2609            }
2610
2611            // For closures, we have some **extra requirements** we
2612            // have to check. In particular, in their upvars and
2613            // signatures, closures often reference various regions
2614            // from the surrounding function -- we call those the
2615            // closure's free regions. When we borrow-check (and hence
2616            // region-check) closures, we may find that the closure
2617            // requires certain relationships between those free
2618            // regions. However, because those free regions refer to
2619            // portions of the CFG of their caller, the closure is not
2620            // in a position to verify those relationships. In that
2621            // case, the requirements get "propagated" to us, and so
2622            // we have to solve them here where we instantiate the
2623            // closure.
2624            //
2625            // Despite the opacity of the previous paragraph, this is
2626            // actually relatively easy to understand in terms of the
2627            // desugaring. A closure gets desugared to a struct, and
2628            // these extra requirements are basically like where
2629            // clauses on the struct.
2630            AggregateKind::Closure(def_id, args)
2631            | AggregateKind::CoroutineClosure(def_id, args)
2632            | AggregateKind::Coroutine(def_id, args) => {
2633                (def_id, self.prove_closure_bounds(tcx, def_id.expect_local(), args, location))
2634            }
2635
2636            AggregateKind::Array(_) | AggregateKind::Tuple | AggregateKind::RawPtr(..) => {
2637                (CRATE_DEF_ID.to_def_id(), ty::InstantiatedPredicates::empty())
2638            }
2639        };
2640
2641        self.normalize_and_prove_instantiated_predicates(
2642            def_id,
2643            instantiated_predicates,
2644            location.to_locations(),
2645        );
2646    }
2647
2648    fn prove_closure_bounds(
2649        &mut self,
2650        tcx: TyCtxt<'tcx>,
2651        def_id: LocalDefId,
2652        args: GenericArgsRef<'tcx>,
2653        location: Location,
2654    ) -> ty::InstantiatedPredicates<'tcx> {
2655        let root_def_id = self.root_cx.root_def_id();
2656        // We will have to handle propagated closure requirements for this closure,
2657        // but need to defer this until the nested body has been fully borrow checked.
2658        self.deferred_closure_requirements.push((def_id, args, location.to_locations()));
2659
2660        // Equate closure args to regions inherited from `root_def_id`. Fixes #98589.
2661        let typeck_root_args = ty::GenericArgs::identity_for_item(tcx, root_def_id);
2662
2663        let parent_args = match tcx.def_kind(def_id) {
2664            // We don't want to dispatch on 3 different kind of closures here, so take
2665            // advantage of the fact that the `parent_args` is the same length as the
2666            // `typeck_root_args`.
2667            DefKind::Closure => {
2668                // FIXME(async_closures): It may be useful to add a debug assert here
2669                // to actually call `type_of` and check the `parent_args` are the same
2670                // length as the `typeck_root_args`.
2671                &args[..typeck_root_args.len()]
2672            }
2673            DefKind::AnonConst
2674                if tcx.anon_const_kind(def_id) == ty::AnonConstKind::NonTypeSystemInline =>
2675            {
2676                args.as_inline_const().parent_args()
2677            }
2678            other => ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected item {0:?}",
        other))bug!("unexpected item {:?}", other),
2679        };
2680        let parent_args = tcx.mk_args(parent_args);
2681
2682        {
    match (&typeck_root_args.len(), &parent_args.len()) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(typeck_root_args.len(), parent_args.len());
2683        if let Err(_) = self.eq_args(
2684            typeck_root_args,
2685            parent_args,
2686            location.to_locations(),
2687            ConstraintCategory::BoringNoLocation,
2688        ) {
2689            {
    crate::type_check::mirbug(self.tcx(), self.last_span,
        ::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("broken MIR in {0:?} ({1:?}): {2}",
                        self.body().source.def_id(), def_id,
                        format_args!("could not relate closure to parent {0:?} != {1:?}",
                            typeck_root_args, parent_args)))
            }))
};span_mirbug!(
2690                self,
2691                def_id,
2692                "could not relate closure to parent {:?} != {:?}",
2693                typeck_root_args,
2694                parent_args
2695            );
2696        }
2697
2698        tcx.predicates_of(def_id).instantiate(tcx, args)
2699    }
2700}
2701
2702trait NormalizeLocation: fmt::Debug + Copy {
2703    fn to_locations(self) -> Locations;
2704}
2705
2706impl NormalizeLocation for Locations {
2707    fn to_locations(self) -> Locations {
2708        self
2709    }
2710}
2711
2712impl NormalizeLocation for Location {
2713    fn to_locations(self) -> Locations {
2714        Locations::Single(self)
2715    }
2716}
2717
2718/// Runs `infcx.instantiate_opaque_types`. Unlike other `TypeOp`s,
2719/// this is not canonicalized - it directly affects the main `InferCtxt`
2720/// that we use during MIR borrowchecking.
2721#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for InstantiateOpaqueType<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field3_finish(f,
            "InstantiateOpaqueType", "base_universe", &self.base_universe,
            "region_constraints", &self.region_constraints, "obligations",
            &&self.obligations)
    }
}Debug)]
2722pub(super) struct InstantiateOpaqueType<'tcx> {
2723    pub base_universe: Option<ty::UniverseIndex>,
2724    pub region_constraints: Option<RegionConstraintData<'tcx>>,
2725    pub obligations: PredicateObligations<'tcx>,
2726}
2727
2728impl<'tcx> TypeOp<'tcx> for InstantiateOpaqueType<'tcx> {
2729    type Output = ();
2730    /// We use this type itself to store the information used
2731    /// when reporting errors. Since this is not a query, we don't
2732    /// re-run anything during error reporting - we just use the information
2733    /// we saved to help extract an error from the already-existing region
2734    /// constraints in our `InferCtxt`
2735    type ErrorInfo = InstantiateOpaqueType<'tcx>;
2736
2737    fn fully_perform(
2738        mut self,
2739        infcx: &InferCtxt<'tcx>,
2740        root_def_id: LocalDefId,
2741        span: Span,
2742    ) -> Result<TypeOpOutput<'tcx, Self>, ErrorGuaranteed> {
2743        let (mut output, region_constraints) =
2744            scrape_region_constraints(infcx, root_def_id, "InstantiateOpaqueType", span, |ocx| {
2745                ocx.register_obligations(self.obligations.clone());
2746                Ok(())
2747            })?;
2748        self.region_constraints = Some(region_constraints);
2749        output.error_info = Some(self);
2750        Ok(output)
2751    }
2752}