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