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