Skip to main content

rustc_middle/mir/
statement.rs

1//! Functionality for statements, operands, places, and things that appear in them.
2
3use std::ops;
4
5use tracing::{debug, instrument};
6
7use super::interpret::GlobalAlloc;
8use super::*;
9use crate::ty::CoroutineArgsExt;
10
11///////////////////////////////////////////////////////////////////////////
12// Statements
13
14/// A statement in a basic block, including information about its source code.
15#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for Statement<'tcx> {
    #[inline]
    fn clone(&self) -> Statement<'tcx> {
        Statement {
            source_info: ::core::clone::Clone::clone(&self.source_info),
            kind: ::core::clone::Clone::clone(&self.kind),
            debuginfos: ::core::clone::Clone::clone(&self.debuginfos),
        }
    }
}Clone, const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for Statement<'tcx> {
            fn encode(&self, __encoder: &mut __E) {
                match *self {
                    Statement {
                        source_info: ref __binding_0,
                        kind: ref __binding_1,
                        debuginfos: ref __binding_2 } => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_2,
                            __encoder);
                    }
                }
            }
        }
    };TyEncodable, const _: () =
    {
        impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
            ::rustc_serialize::Decodable<__D> for Statement<'tcx> {
            fn decode(__decoder: &mut __D) -> Self {
                Statement {
                    source_info: ::rustc_serialize::Decodable::decode(__decoder),
                    kind: ::rustc_serialize::Decodable::decode(__decoder),
                    debuginfos: ::rustc_serialize::Decodable::decode(__decoder),
                }
            }
        }
    };TyDecodable, const _: () =
    {
        impl<'tcx, '__ctx>
            ::rustc_data_structures::stable_hasher::HashStable<::rustc_middle::ich::StableHashingContext<'__ctx>>
            for Statement<'tcx> {
            #[inline]
            fn hash_stable(&self,
                __hcx: &mut ::rustc_middle::ich::StableHashingContext<'__ctx>,
                __hasher:
                    &mut ::rustc_data_structures::stable_hasher::StableHasher) {
                match *self {
                    Statement {
                        source_info: ref __binding_0,
                        kind: ref __binding_1,
                        debuginfos: ref __binding_2 } => {
                        { __binding_0.hash_stable(__hcx, __hasher); }
                        { __binding_1.hash_stable(__hcx, __hasher); }
                        { __binding_2.hash_stable(__hcx, __hasher); }
                    }
                }
            }
        }
    };HashStable, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            for Statement<'tcx> {
            fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Result<Self, __F::Error> {
                Ok(match self {
                        Statement {
                            source_info: __binding_0,
                            kind: __binding_1,
                            debuginfos: __binding_2 } => {
                            Statement {
                                source_info: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                                kind: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?,
                                debuginfos: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_2,
                                        __folder)?,
                            }
                        }
                    })
            }
            fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Self {
                match self {
                    Statement {
                        source_info: __binding_0,
                        kind: __binding_1,
                        debuginfos: __binding_2 } => {
                        Statement {
                            source_info: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder),
                            kind: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
                                __folder),
                            debuginfos: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_2,
                                __folder),
                        }
                    }
                }
            }
        }
    };TypeFoldable, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for Statement<'tcx> {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    Statement {
                        source_info: ref __binding_0,
                        kind: ref __binding_1,
                        debuginfos: ref __binding_2 } => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_2,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                }
                <__V::Result as ::rustc_middle::ty::VisitorResult>::output()
            }
        }
    };TypeVisitable)]
16#[non_exhaustive]
17pub struct Statement<'tcx> {
18    pub source_info: SourceInfo,
19    pub kind: StatementKind<'tcx>,
20    /// Some debuginfos appearing before the primary statement.
21    pub debuginfos: StmtDebugInfos<'tcx>,
22}
23
24impl<'tcx> Statement<'tcx> {
25    /// Changes a statement to a nop. This is both faster than deleting instructions and avoids
26    /// invalidating statement indices in `Location`s.
27    pub fn make_nop(&mut self, drop_debuginfo: bool) {
28        if self.kind == StatementKind::Nop {
29            return;
30        }
31        let replaced_stmt = std::mem::replace(&mut self.kind, StatementKind::Nop);
32        if !drop_debuginfo {
33            let Some(debuginfo) = replaced_stmt.as_debuginfo() else {
34                crate::util::bug::bug_fmt(format_args!("debuginfo is not yet supported."))bug!("debuginfo is not yet supported.")
35            };
36            self.debuginfos.push(debuginfo);
37        }
38    }
39
40    pub fn new(source_info: SourceInfo, kind: StatementKind<'tcx>) -> Self {
41        Statement { source_info, kind, debuginfos: StmtDebugInfos::default() }
42    }
43}
44
45impl<'tcx> StatementKind<'tcx> {
46    /// Returns a simple string representation of a `StatementKind` variant, independent of any
47    /// values it might hold (e.g. `StatementKind::Assign` always returns `"Assign"`).
48    pub const fn name(&self) -> &'static str {
49        match self {
50            StatementKind::Assign(..) => "Assign",
51            StatementKind::FakeRead(..) => "FakeRead",
52            StatementKind::SetDiscriminant { .. } => "SetDiscriminant",
53            StatementKind::StorageLive(..) => "StorageLive",
54            StatementKind::StorageDead(..) => "StorageDead",
55            StatementKind::Retag(..) => "Retag",
56            StatementKind::PlaceMention(..) => "PlaceMention",
57            StatementKind::AscribeUserType(..) => "AscribeUserType",
58            StatementKind::Coverage(..) => "Coverage",
59            StatementKind::Intrinsic(..) => "Intrinsic",
60            StatementKind::ConstEvalCounter => "ConstEvalCounter",
61            StatementKind::Nop => "Nop",
62            StatementKind::BackwardIncompatibleDropHint { .. } => "BackwardIncompatibleDropHint",
63        }
64    }
65    pub fn as_assign_mut(&mut self) -> Option<&mut (Place<'tcx>, Rvalue<'tcx>)> {
66        match self {
67            StatementKind::Assign(x) => Some(x),
68            _ => None,
69        }
70    }
71
72    pub fn as_assign(&self) -> Option<&(Place<'tcx>, Rvalue<'tcx>)> {
73        match self {
74            StatementKind::Assign(x) => Some(x),
75            _ => None,
76        }
77    }
78
79    pub fn as_debuginfo(&self) -> Option<StmtDebugInfo<'tcx>> {
80        match self {
81            StatementKind::Assign(box (place, Rvalue::Ref(_, _, ref_place)))
82                if let Some(local) = place.as_local() =>
83            {
84                Some(StmtDebugInfo::AssignRef(local, *ref_place))
85            }
86            _ => None,
87        }
88    }
89}
90
91///////////////////////////////////////////////////////////////////////////
92// Places
93
94#[derive(#[automatically_derived]
impl<'tcx> ::core::marker::Copy for PlaceTy<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for PlaceTy<'tcx> {
    #[inline]
    fn clone(&self) -> PlaceTy<'tcx> {
        let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
        let _: ::core::clone::AssertParamIsClone<Option<VariantIdx>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for PlaceTy<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "PlaceTy", "ty",
            &self.ty, "variant_index", &&self.variant_index)
    }
}Debug, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            for PlaceTy<'tcx> {
            fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Result<Self, __F::Error> {
                Ok(match self {
                        PlaceTy { ty: __binding_0, variant_index: __binding_1 } => {
                            PlaceTy {
                                ty: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                                variant_index: ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?,
                            }
                        }
                    })
            }
            fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Self {
                match self {
                    PlaceTy { ty: __binding_0, variant_index: __binding_1 } => {
                        PlaceTy {
                            ty: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder),
                            variant_index: ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
                                __folder),
                        }
                    }
                }
            }
        }
    };TypeFoldable, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for PlaceTy<'tcx> {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    PlaceTy {
                        ty: ref __binding_0, variant_index: ref __binding_1 } => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                }
                <__V::Result as ::rustc_middle::ty::VisitorResult>::output()
            }
        }
    };TypeVisitable)]
95pub struct PlaceTy<'tcx> {
96    pub ty: Ty<'tcx>,
97    /// Downcast to a particular variant of an enum or a coroutine, if included.
98    pub variant_index: Option<VariantIdx>,
99}
100
101// At least on 64 bit systems, `PlaceTy` should not be larger than two or three pointers.
102#[cfg(target_pointer_width = "64")]
103const _: [(); 16] = [(); ::std::mem::size_of::<PlaceTy<'_>>()];rustc_data_structures::static_assert_size!(PlaceTy<'_>, 16);
104
105impl<'tcx> PlaceTy<'tcx> {
106    #[inline]
107    pub fn from_ty(ty: Ty<'tcx>) -> PlaceTy<'tcx> {
108        PlaceTy { ty, variant_index: None }
109    }
110
111    /// `place_ty.field_ty(tcx, f)` computes the type of a given field.
112    ///
113    /// Most clients of `PlaceTy` can instead just extract the relevant type
114    /// directly from their `PlaceElem`, but some instances of `ProjectionElem<V, T>`
115    /// do not carry a `Ty` for `T`.
116    ///
117    /// Note that the resulting type has not been normalized.
118    x;#[instrument(level = "debug", skip(tcx), ret)]
119    pub fn field_ty(
120        tcx: TyCtxt<'tcx>,
121        self_ty: Ty<'tcx>,
122        variant_idx: Option<VariantIdx>,
123        f: FieldIdx,
124    ) -> Ty<'tcx> {
125        if let Some(variant_index) = variant_idx {
126            match *self_ty.kind() {
127                ty::Adt(adt_def, args) if adt_def.is_enum() => {
128                    adt_def.variant(variant_index).fields[f].ty(tcx, args)
129                }
130                ty::Coroutine(def_id, args) => {
131                    let mut variants = args.as_coroutine().state_tys(def_id, tcx);
132                    let Some(mut variant) = variants.nth(variant_index.into()) else {
133                        bug!("variant {variant_index:?} of coroutine out of range: {self_ty:?}");
134                    };
135
136                    variant.nth(f.index()).unwrap_or_else(|| {
137                        bug!("field {f:?} out of range of variant: {self_ty:?} {variant_idx:?}")
138                    })
139                }
140                _ => bug!("can't downcast non-adt non-coroutine type: {self_ty:?}"),
141            }
142        } else {
143            match self_ty.kind() {
144                ty::Adt(adt_def, args) if !adt_def.is_enum() => {
145                    adt_def.non_enum_variant().fields[f].ty(tcx, args)
146                }
147                ty::Closure(_, args) => args
148                    .as_closure()
149                    .upvar_tys()
150                    .get(f.index())
151                    .copied()
152                    .unwrap_or_else(|| bug!("field {f:?} out of range: {self_ty:?}")),
153                ty::CoroutineClosure(_, args) => args
154                    .as_coroutine_closure()
155                    .upvar_tys()
156                    .get(f.index())
157                    .copied()
158                    .unwrap_or_else(|| bug!("field {f:?} out of range: {self_ty:?}")),
159                // Only prefix fields (upvars and current state) are
160                // accessible without a variant index.
161                ty::Coroutine(_, args) => {
162                    args.as_coroutine().prefix_tys().get(f.index()).copied().unwrap_or_else(|| {
163                        bug!("field {f:?} out of range of prefixes for {self_ty}")
164                    })
165                }
166                ty::Tuple(tys) => tys
167                    .get(f.index())
168                    .copied()
169                    .unwrap_or_else(|| bug!("field {f:?} out of range: {self_ty:?}")),
170                _ => bug!("can't project out of {self_ty:?}"),
171            }
172        }
173    }
174
175    pub fn multi_projection_ty(
176        self,
177        tcx: TyCtxt<'tcx>,
178        elems: &[PlaceElem<'tcx>],
179    ) -> PlaceTy<'tcx> {
180        elems.iter().fold(self, |place_ty, &elem| place_ty.projection_ty(tcx, elem))
181    }
182
183    /// Convenience wrapper around `projection_ty_core` for `PlaceElem`,
184    /// where we can just use the `Ty` that is already stored inline on
185    /// field projection elems.
186    pub fn projection_ty<V: ::std::fmt::Debug>(
187        self,
188        tcx: TyCtxt<'tcx>,
189        elem: ProjectionElem<V, Ty<'tcx>>,
190    ) -> PlaceTy<'tcx> {
191        self.projection_ty_core(tcx, &elem, |ty| ty, |_, _, _, ty| ty, |ty| ty)
192    }
193
194    /// `place_ty.projection_ty_core(tcx, elem, |...| { ... })`
195    /// projects `place_ty` onto `elem`, returning the appropriate
196    /// `Ty` or downcast variant corresponding to that projection.
197    /// The `handle_field` callback must map a `FieldIdx` to its `Ty`,
198    /// (which should be trivial when `T` = `Ty`).
199    pub fn projection_ty_core<V, T>(
200        self,
201        tcx: TyCtxt<'tcx>,
202        elem: &ProjectionElem<V, T>,
203        mut structurally_normalize: impl FnMut(Ty<'tcx>) -> Ty<'tcx>,
204        mut handle_field: impl FnMut(Ty<'tcx>, Option<VariantIdx>, FieldIdx, T) -> Ty<'tcx>,
205        mut handle_opaque_cast_and_subtype: impl FnMut(T) -> Ty<'tcx>,
206    ) -> PlaceTy<'tcx>
207    where
208        V: ::std::fmt::Debug,
209        T: ::std::fmt::Debug + Copy,
210    {
211        if self.variant_index.is_some() && !#[allow(non_exhaustive_omitted_patterns)] match elem {
    ProjectionElem::Field(..) => true,
    _ => false,
}matches!(elem, ProjectionElem::Field(..)) {
212            crate::util::bug::bug_fmt(format_args!("cannot use non field projection on downcasted place"))bug!("cannot use non field projection on downcasted place")
213        }
214        let answer = match *elem {
215            ProjectionElem::Deref => {
216                let ty = structurally_normalize(self.ty).builtin_deref(true).unwrap_or_else(|| {
217                    crate::util::bug::bug_fmt(format_args!("deref projection of non-dereferenceable ty {0:?}",
        self))bug!("deref projection of non-dereferenceable ty {:?}", self)
218                });
219                PlaceTy::from_ty(ty)
220            }
221            ProjectionElem::Index(_) | ProjectionElem::ConstantIndex { .. } => {
222                PlaceTy::from_ty(structurally_normalize(self.ty).builtin_index().unwrap())
223            }
224            ProjectionElem::Subslice { from, to, from_end } => {
225                PlaceTy::from_ty(match structurally_normalize(self.ty).kind() {
226                    ty::Slice(..) => self.ty,
227                    ty::Array(inner, _) if !from_end => Ty::new_array(tcx, *inner, to - from),
228                    ty::Array(inner, size) if from_end => {
229                        let size = size
230                            .try_to_target_usize(tcx)
231                            .expect("expected subslice projection on fixed-size array");
232                        let len = size - from - to;
233                        Ty::new_array(tcx, *inner, len)
234                    }
235                    _ => crate::util::bug::bug_fmt(format_args!("cannot subslice non-array type: `{0:?}`",
        self))bug!("cannot subslice non-array type: `{:?}`", self),
236                })
237            }
238            ProjectionElem::Downcast(_name, index) => {
239                PlaceTy { ty: self.ty, variant_index: Some(index) }
240            }
241            ProjectionElem::Field(f, fty) => PlaceTy::from_ty(handle_field(
242                structurally_normalize(self.ty),
243                self.variant_index,
244                f,
245                fty,
246            )),
247            ProjectionElem::OpaqueCast(ty) => PlaceTy::from_ty(handle_opaque_cast_and_subtype(ty)),
248
249            // FIXME(unsafe_binders): Rename `handle_opaque_cast_and_subtype` to be more general.
250            ProjectionElem::UnwrapUnsafeBinder(ty) => {
251                PlaceTy::from_ty(handle_opaque_cast_and_subtype(ty))
252            }
253        };
254        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_middle/src/mir/statement.rs:254",
                        "rustc_middle::mir::statement", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_middle/src/mir/statement.rs"),
                        ::tracing_core::__macro_support::Option::Some(254u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_middle::mir::statement"),
                        ::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!("projection_ty self: {0:?} elem: {1:?} yields: {2:?}",
                                                    self, elem, answer) as &dyn Value))])
            });
    } else { ; }
};debug!("projection_ty self: {:?} elem: {:?} yields: {:?}", self, elem, answer);
255        answer
256    }
257}
258
259impl<V, T> ProjectionElem<V, T> {
260    /// Returns `true` if the target of this projection may refer to a different region of memory
261    /// than the base.
262    pub fn is_indirect(&self) -> bool {
263        match self {
264            Self::Deref => true,
265
266            Self::Field(_, _)
267            | Self::Index(_)
268            | Self::OpaqueCast(_)
269            | Self::ConstantIndex { .. }
270            | Self::Subslice { .. }
271            | Self::Downcast(_, _)
272            | Self::UnwrapUnsafeBinder(..) => false,
273        }
274    }
275
276    /// Returns `true` if the target of this projection always refers to the same memory region
277    /// whatever the state of the program.
278    pub fn is_stable_offset(&self) -> bool {
279        match self {
280            Self::Deref | Self::Index(_) => false,
281            Self::Field(_, _)
282            | Self::OpaqueCast(_)
283            | Self::ConstantIndex { .. }
284            | Self::Subslice { .. }
285            | Self::Downcast(_, _)
286            | Self::UnwrapUnsafeBinder(..) => true,
287        }
288    }
289
290    /// Returns `true` if this is a `Downcast` projection with the given `VariantIdx`.
291    pub fn is_downcast_to(&self, v: VariantIdx) -> bool {
292        #[allow(non_exhaustive_omitted_patterns)] match *self {
    Self::Downcast(_, x) if x == v => true,
    _ => false,
}matches!(*self, Self::Downcast(_, x) if x == v)
293    }
294
295    /// Returns `true` if this is a `Field` projection with the given index.
296    pub fn is_field_to(&self, f: FieldIdx) -> bool {
297        #[allow(non_exhaustive_omitted_patterns)] match *self {
    Self::Field(x, _) if x == f => true,
    _ => false,
}matches!(*self, Self::Field(x, _) if x == f)
298    }
299
300    /// Returns `true` if this is accepted inside `VarDebugInfoContents::Place`.
301    pub fn can_use_in_debuginfo(&self) -> bool {
302        match self {
303            Self::ConstantIndex { from_end: false, .. }
304            | Self::Deref
305            | Self::Downcast(_, _)
306            | Self::Field(_, _) => true,
307            Self::ConstantIndex { from_end: true, .. }
308            | Self::Index(_)
309            | Self::OpaqueCast(_)
310            | Self::Subslice { .. } => false,
311
312            // FIXME(unsafe_binders): Figure this out.
313            Self::UnwrapUnsafeBinder(..) => false,
314        }
315    }
316
317    /// Returns the `ProjectionKind` associated to this projection.
318    pub fn kind(self) -> ProjectionKind {
319        self.try_map(|_| Some(()), |_| ()).unwrap()
320    }
321
322    /// Apply functions to types and values in this projection and return the result.
323    pub fn try_map<V2, T2>(
324        self,
325        v: impl FnOnce(V) -> Option<V2>,
326        t: impl FnOnce(T) -> T2,
327    ) -> Option<ProjectionElem<V2, T2>> {
328        Some(match self {
329            ProjectionElem::Deref => ProjectionElem::Deref,
330            ProjectionElem::Downcast(name, read_variant) => {
331                ProjectionElem::Downcast(name, read_variant)
332            }
333            ProjectionElem::Field(f, ty) => ProjectionElem::Field(f, t(ty)),
334            ProjectionElem::ConstantIndex { offset, min_length, from_end } => {
335                ProjectionElem::ConstantIndex { offset, min_length, from_end }
336            }
337            ProjectionElem::Subslice { from, to, from_end } => {
338                ProjectionElem::Subslice { from, to, from_end }
339            }
340            ProjectionElem::OpaqueCast(ty) => ProjectionElem::OpaqueCast(t(ty)),
341            ProjectionElem::UnwrapUnsafeBinder(ty) => ProjectionElem::UnwrapUnsafeBinder(t(ty)),
342            ProjectionElem::Index(val) => ProjectionElem::Index(v(val)?),
343        })
344    }
345}
346
347/// Alias for projections as they appear in `UserTypeProjection`, where we
348/// need neither the `V` parameter for `Index` nor the `T` for `Field`.
349pub type ProjectionKind = ProjectionElem<(), ()>;
350
351#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for PlaceRef<'tcx> {
    #[inline]
    fn clone(&self) -> PlaceRef<'tcx> {
        let _: ::core::clone::AssertParamIsClone<Local>;
        let _: ::core::clone::AssertParamIsClone<&'tcx [PlaceElem<'tcx>]>;
        *self
    }
}Clone, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for PlaceRef<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::cmp::PartialEq for PlaceRef<'tcx> {
    #[inline]
    fn eq(&self, other: &PlaceRef<'tcx>) -> bool {
        self.local == other.local && self.projection == other.projection
    }
}PartialEq, #[automatically_derived]
impl<'tcx> ::core::cmp::Eq for PlaceRef<'tcx> {
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Local>;
        let _: ::core::cmp::AssertParamIsEq<&'tcx [PlaceElem<'tcx>]>;
    }
}Eq, #[automatically_derived]
impl<'tcx> ::core::hash::Hash for PlaceRef<'tcx> {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.local, state);
        ::core::hash::Hash::hash(&self.projection, state)
    }
}Hash)]
352pub struct PlaceRef<'tcx> {
353    pub local: Local,
354    pub projection: &'tcx [PlaceElem<'tcx>],
355}
356
357// Once we stop implementing `Ord` for `DefId`,
358// this impl will be unnecessary. Until then, we'll
359// leave this impl in place to prevent re-adding a
360// dependency on the `Ord` impl for `DefId`
361impl<'tcx> !PartialOrd for PlaceRef<'tcx> {}
362
363impl<'tcx> Place<'tcx> {
364    // FIXME change this to a const fn by also making List::empty a const fn.
365    pub fn return_place() -> Place<'tcx> {
366        Place { local: RETURN_PLACE, projection: List::empty() }
367    }
368
369    /// Returns `true` if this `Place` contains a `Deref` projection.
370    ///
371    /// If `Place::is_indirect` returns false, the caller knows that the `Place` refers to the
372    /// same region of memory as its base.
373    pub fn is_indirect(&self) -> bool {
374        self.projection.iter().any(|elem| elem.is_indirect())
375    }
376
377    /// Returns `true` if the `Place` always refers to the same memory region
378    /// whatever the state of the program.
379    pub fn is_stable_offset(&self) -> bool {
380        self.projection.iter().all(|elem| elem.is_stable_offset())
381    }
382
383    /// Returns `true` if this `Place`'s first projection is `Deref`.
384    ///
385    /// This is useful because for MIR phases `AnalysisPhase::PostCleanup` and later,
386    /// `Deref` projections can only occur as the first projection. In that case this method
387    /// is equivalent to `is_indirect`, but faster.
388    pub fn is_indirect_first_projection(&self) -> bool {
389        self.as_ref().is_indirect_first_projection()
390    }
391
392    /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
393    /// a single deref of a local.
394    #[inline(always)]
395    pub fn local_or_deref_local(&self) -> Option<Local> {
396        self.as_ref().local_or_deref_local()
397    }
398
399    /// If this place represents a local variable like `_X` with no
400    /// projections, return `Some(_X)`.
401    #[inline(always)]
402    pub fn as_local(&self) -> Option<Local> {
403        self.as_ref().as_local()
404    }
405
406    #[inline]
407    pub fn as_ref(&self) -> PlaceRef<'tcx> {
408        PlaceRef { local: self.local, projection: self.projection }
409    }
410
411    /// Iterate over the projections in evaluation order, i.e., the first element is the base with
412    /// its projection and then subsequently more projections are added.
413    /// As a concrete example, given the place a.b.c, this would yield:
414    /// - (a, .b)
415    /// - (a.b, .c)
416    ///
417    /// Given a place without projections, the iterator is empty.
418    #[inline]
419    pub fn iter_projections(
420        self,
421    ) -> impl Iterator<Item = (PlaceRef<'tcx>, PlaceElem<'tcx>)> + DoubleEndedIterator {
422        self.as_ref().iter_projections()
423    }
424
425    /// Generates a new place by appending `more_projections` to the existing ones
426    /// and interning the result.
427    pub fn project_deeper(self, more_projections: &[PlaceElem<'tcx>], tcx: TyCtxt<'tcx>) -> Self {
428        if more_projections.is_empty() {
429            return self;
430        }
431
432        self.as_ref().project_deeper(more_projections, tcx)
433    }
434
435    /// Return a place that projects to a field of the current place.
436    ///
437    /// The type of the current place must be an ADT.
438    pub fn project_to_field(
439        self,
440        idx: FieldIdx,
441        local_decls: &impl HasLocalDecls<'tcx>,
442        tcx: TyCtxt<'tcx>,
443    ) -> Self {
444        let ty = self.ty(local_decls, tcx).ty;
445        let ty::Adt(adt, args) = ty.kind() else { {
    ::core::panicking::panic_fmt(format_args!("projecting to field of non-ADT {0}",
            ty));
}panic!("projecting to field of non-ADT {ty}") };
446        let field = &adt.non_enum_variant().fields[idx];
447        let field_ty = field.ty(tcx, args);
448        self.project_deeper(&[ProjectionElem::Field(idx, field_ty)], tcx)
449    }
450
451    pub fn ty_from<D>(
452        local: Local,
453        projection: &[PlaceElem<'tcx>],
454        local_decls: &D,
455        tcx: TyCtxt<'tcx>,
456    ) -> PlaceTy<'tcx>
457    where
458        D: ?Sized + HasLocalDecls<'tcx>,
459    {
460        // If there's a field projection element in `projection`, we *could* skip everything
461        // before that, but on 2026-01-31 a perf experiment showed no benefit from doing so.
462        PlaceTy::from_ty(local_decls.local_decls()[local].ty).multi_projection_ty(tcx, projection)
463    }
464
465    pub fn ty<D: ?Sized>(&self, local_decls: &D, tcx: TyCtxt<'tcx>) -> PlaceTy<'tcx>
466    where
467        D: HasLocalDecls<'tcx>,
468    {
469        Place::ty_from(self.local, self.projection, local_decls, tcx)
470    }
471}
472
473impl From<Local> for Place<'_> {
474    #[inline]
475    fn from(local: Local) -> Self {
476        Place { local, projection: List::empty() }
477    }
478}
479
480impl<'tcx> PlaceRef<'tcx> {
481    /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
482    /// a single deref of a local.
483    pub fn local_or_deref_local(&self) -> Option<Local> {
484        match *self {
485            PlaceRef { local, projection: [] }
486            | PlaceRef { local, projection: [ProjectionElem::Deref] } => Some(local),
487            _ => None,
488        }
489    }
490
491    /// Returns `true` if this `Place` contains a `Deref` projection.
492    ///
493    /// If `Place::is_indirect` returns false, the caller knows that the `Place` refers to the
494    /// same region of memory as its base.
495    pub fn is_indirect(&self) -> bool {
496        self.projection.iter().any(|elem| elem.is_indirect())
497    }
498
499    /// Returns `true` if this `Place`'s first projection is `Deref`.
500    ///
501    /// This is useful because for MIR phases `AnalysisPhase::PostCleanup` and later,
502    /// `Deref` projections can only occur as the first projection. In that case this method
503    /// is equivalent to `is_indirect`, but faster.
504    pub fn is_indirect_first_projection(&self) -> bool {
505        // To make sure this is not accidentally used in wrong mir phase
506        if true {
    if !(self.projection.is_empty() ||
                !self.projection[1..].contains(&PlaceElem::Deref)) {
        ::core::panicking::panic("assertion failed: self.projection.is_empty() ||\n    !self.projection[1..].contains(&PlaceElem::Deref)")
    };
};debug_assert!(
507            self.projection.is_empty() || !self.projection[1..].contains(&PlaceElem::Deref)
508        );
509        self.projection.first() == Some(&PlaceElem::Deref)
510    }
511
512    /// If this place represents a local variable like `_X` with no
513    /// projections, return `Some(_X)`.
514    #[inline]
515    pub fn as_local(&self) -> Option<Local> {
516        match *self {
517            PlaceRef { local, projection: [] } => Some(local),
518            _ => None,
519        }
520    }
521
522    #[inline]
523    pub fn to_place(&self, tcx: TyCtxt<'tcx>) -> Place<'tcx> {
524        Place { local: self.local, projection: tcx.mk_place_elems(self.projection) }
525    }
526
527    #[inline]
528    pub fn last_projection(&self) -> Option<(PlaceRef<'tcx>, PlaceElem<'tcx>)> {
529        if let &[ref proj_base @ .., elem] = self.projection {
530            Some((PlaceRef { local: self.local, projection: proj_base }, elem))
531        } else {
532            None
533        }
534    }
535
536    /// Iterate over the projections in evaluation order, i.e., the first element is the base with
537    /// its projection and then subsequently more projections are added.
538    /// As a concrete example, given the place a.b.c, this would yield:
539    /// - (a, .b)
540    /// - (a.b, .c)
541    ///
542    /// Given a place without projections, the iterator is empty.
543    #[inline]
544    pub fn iter_projections(
545        self,
546    ) -> impl Iterator<Item = (PlaceRef<'tcx>, PlaceElem<'tcx>)> + DoubleEndedIterator {
547        self.projection.iter().enumerate().map(move |(i, proj)| {
548            let base = PlaceRef { local: self.local, projection: &self.projection[..i] };
549            (base, *proj)
550        })
551    }
552
553    /// Return the place accessed locals that include the base local.
554    pub fn accessed_locals(self) -> impl Iterator<Item = Local> {
555        std::iter::once(self.local).chain(self.projection.iter().filter_map(|proj| match proj {
556            ProjectionElem::Index(local) => Some(*local),
557            ProjectionElem::Deref
558            | ProjectionElem::Field(_, _)
559            | ProjectionElem::ConstantIndex { .. }
560            | ProjectionElem::Subslice { .. }
561            | ProjectionElem::Downcast(_, _)
562            | ProjectionElem::OpaqueCast(_)
563            | ProjectionElem::UnwrapUnsafeBinder(_) => None,
564        }))
565    }
566
567    /// Generates a new place by appending `more_projections` to the existing ones
568    /// and interning the result.
569    pub fn project_deeper(
570        self,
571        more_projections: &[PlaceElem<'tcx>],
572        tcx: TyCtxt<'tcx>,
573    ) -> Place<'tcx> {
574        let mut v: Vec<PlaceElem<'tcx>>;
575
576        let new_projections = if self.projection.is_empty() {
577            more_projections
578        } else {
579            v = Vec::with_capacity(self.projection.len() + more_projections.len());
580            v.extend(self.projection);
581            v.extend(more_projections);
582            &v
583        };
584
585        Place { local: self.local, projection: tcx.mk_place_elems(new_projections) }
586    }
587
588    pub fn ty<D>(&self, local_decls: &D, tcx: TyCtxt<'tcx>) -> PlaceTy<'tcx>
589    where
590        D: ?Sized + HasLocalDecls<'tcx>,
591    {
592        Place::ty_from(self.local, self.projection, local_decls, tcx)
593    }
594}
595
596impl From<Local> for PlaceRef<'_> {
597    #[inline]
598    fn from(local: Local) -> Self {
599        PlaceRef { local, projection: &[] }
600    }
601}
602
603///////////////////////////////////////////////////////////////////////////
604// Operands
605
606impl<'tcx> Operand<'tcx> {
607    /// Convenience helper to make a constant that refers to the fn
608    /// with given `DefId` and args. Since this is used to synthesize
609    /// MIR, assumes `user_ty` is None.
610    pub fn function_handle(
611        tcx: TyCtxt<'tcx>,
612        def_id: DefId,
613        args: impl IntoIterator<Item = GenericArg<'tcx>>,
614        span: Span,
615    ) -> Self {
616        let ty = Ty::new_fn_def(tcx, def_id, args);
617        Operand::Constant(Box::new(ConstOperand {
618            span,
619            user_ty: None,
620            const_: Const::Val(ConstValue::ZeroSized, ty),
621        }))
622    }
623
624    /// Convenience helper to make a constant that refers to the given `DefId` and args. Since this
625    /// is used to synthesize MIR, assumes `user_ty` is None.
626    pub fn unevaluated_constant(
627        tcx: TyCtxt<'tcx>,
628        def_id: DefId,
629        args: &[GenericArg<'tcx>],
630        span: Span,
631    ) -> Self {
632        let const_ = Const::from_unevaluated(tcx, def_id).instantiate(tcx, args);
633        Operand::Constant(Box::new(ConstOperand { span, user_ty: None, const_ }))
634    }
635
636    pub fn is_move(&self) -> bool {
637        #[allow(non_exhaustive_omitted_patterns)] match self {
    Operand::Move(..) => true,
    _ => false,
}matches!(self, Operand::Move(..))
638    }
639
640    /// Convenience helper to make a literal-like constant from a given scalar value.
641    /// Since this is used to synthesize MIR, assumes `user_ty` is None.
642    pub fn const_from_scalar(
643        tcx: TyCtxt<'tcx>,
644        ty: Ty<'tcx>,
645        val: Scalar,
646        span: Span,
647    ) -> Operand<'tcx> {
648        if true {
    if !{
                let typing_env = ty::TypingEnv::fully_monomorphized();
                let type_size =
                    tcx.layout_of(typing_env.as_query_input(ty)).unwrap_or_else(|e|
                                {
                                    ::core::panicking::panic_fmt(format_args!("could not compute layout for {0:?}: {1:?}",
                                            ty, e));
                                }).size;
                let scalar_size =
                    match val {
                        Scalar::Int(int) => int.size(),
                        _ => {
                            ::core::panicking::panic_fmt(format_args!("Invalid scalar type {0:?}",
                                    val));
                        }
                    };
                scalar_size == type_size
            } {
        ::core::panicking::panic("assertion failed: {\n    let typing_env = ty::TypingEnv::fully_monomorphized();\n    let type_size =\n        tcx.layout_of(typing_env.as_query_input(ty)).unwrap_or_else(|e|\n                    panic!(\"could not compute layout for {ty:?}: {e:?}\")).size;\n    let scalar_size =\n        match val {\n            Scalar::Int(int) => int.size(),\n            _ => panic!(\"Invalid scalar type {val:?}\"),\n        };\n    scalar_size == type_size\n}")
    };
};debug_assert!({
649            let typing_env = ty::TypingEnv::fully_monomorphized();
650            let type_size = tcx
651                .layout_of(typing_env.as_query_input(ty))
652                .unwrap_or_else(|e| panic!("could not compute layout for {ty:?}: {e:?}"))
653                .size;
654            let scalar_size = match val {
655                Scalar::Int(int) => int.size(),
656                _ => panic!("Invalid scalar type {val:?}"),
657            };
658            scalar_size == type_size
659        });
660        Operand::Constant(Box::new(ConstOperand {
661            span,
662            user_ty: None,
663            const_: Const::Val(ConstValue::Scalar(val), ty),
664        }))
665    }
666
667    pub fn to_copy(&self) -> Self {
668        match *self {
669            Operand::Copy(_) | Operand::Constant(_) | Operand::RuntimeChecks(_) => self.clone(),
670            Operand::Move(place) => Operand::Copy(place),
671        }
672    }
673
674    /// Returns the `Place` that is the target of this `Operand`, or `None` if this `Operand` is a
675    /// constant.
676    pub fn place(&self) -> Option<Place<'tcx>> {
677        match self {
678            Operand::Copy(place) | Operand::Move(place) => Some(*place),
679            Operand::Constant(_) | Operand::RuntimeChecks(_) => None,
680        }
681    }
682
683    /// Returns the `ConstOperand` that is the target of this `Operand`, or `None` if this `Operand` is a
684    /// place.
685    pub fn constant(&self) -> Option<&ConstOperand<'tcx>> {
686        match self {
687            Operand::Constant(x) => Some(&**x),
688            Operand::Copy(_) | Operand::Move(_) | Operand::RuntimeChecks(_) => None,
689        }
690    }
691
692    /// Gets the `ty::FnDef` from an operand if it's a constant function item.
693    ///
694    /// While this is unlikely in general, it's the normal case of what you'll
695    /// find as the `func` in a [`TerminatorKind::Call`].
696    pub fn const_fn_def(&self) -> Option<(DefId, GenericArgsRef<'tcx>)> {
697        let const_ty = self.constant()?.const_.ty();
698        if let ty::FnDef(def_id, args) = *const_ty.kind() { Some((def_id, args)) } else { None }
699    }
700
701    pub fn ty<D>(&self, local_decls: &D, tcx: TyCtxt<'tcx>) -> Ty<'tcx>
702    where
703        D: ?Sized + HasLocalDecls<'tcx>,
704    {
705        match self {
706            &Operand::Copy(ref l) | &Operand::Move(ref l) => l.ty(local_decls, tcx).ty,
707            Operand::Constant(c) => c.const_.ty(),
708            Operand::RuntimeChecks(_) => tcx.types.bool,
709        }
710    }
711
712    pub fn span<D>(&self, local_decls: &D) -> Span
713    where
714        D: ?Sized + HasLocalDecls<'tcx>,
715    {
716        match self {
717            &Operand::Copy(ref l) | &Operand::Move(ref l) => {
718                local_decls.local_decls()[l.local].source_info.span
719            }
720            Operand::Constant(c) => c.span,
721            // User code should not contain this operand, so we should not need this span.
722            Operand::RuntimeChecks(_) => DUMMY_SP,
723        }
724    }
725}
726
727impl<'tcx> ConstOperand<'tcx> {
728    pub fn check_static_ptr(&self, tcx: TyCtxt<'_>) -> Option<DefId> {
729        match self.const_.try_to_scalar() {
730            Some(Scalar::Ptr(ptr, _size)) => match tcx.global_alloc(ptr.provenance.alloc_id()) {
731                GlobalAlloc::Static(def_id) => {
732                    if !!tcx.is_thread_local_static(def_id) {
    ::core::panicking::panic("assertion failed: !tcx.is_thread_local_static(def_id)")
};assert!(!tcx.is_thread_local_static(def_id));
733                    Some(def_id)
734                }
735                _ => None,
736            },
737            _ => None,
738        }
739    }
740
741    #[inline]
742    pub fn ty(&self) -> Ty<'tcx> {
743        self.const_.ty()
744    }
745}
746
747///////////////////////////////////////////////////////////////////////////
748// Rvalues
749
750impl<'tcx> Rvalue<'tcx> {
751    /// Returns true if rvalue can be safely removed when the result is unused.
752    #[inline]
753    pub fn is_safe_to_remove(&self) -> bool {
754        match self {
755            // Pointer to int casts may be side-effects due to exposing the provenance.
756            // While the model is undecided, we should be conservative. See
757            // <https://www.ralfj.de/blog/2022/04/11/provenance-exposed.html>
758            Rvalue::Cast(CastKind::PointerExposeProvenance, _, _) => false,
759
760            Rvalue::Use(_)
761            | Rvalue::CopyForDeref(_)
762            | Rvalue::Repeat(_, _)
763            | Rvalue::Ref(_, _, _)
764            | Rvalue::ThreadLocalRef(_)
765            | Rvalue::RawPtr(_, _)
766            | Rvalue::Cast(
767                CastKind::IntToInt
768                | CastKind::FloatToInt
769                | CastKind::FloatToFloat
770                | CastKind::IntToFloat
771                | CastKind::FnPtrToPtr
772                | CastKind::PtrToPtr
773                | CastKind::PointerCoercion(_, _)
774                | CastKind::PointerWithExposedProvenance
775                | CastKind::Transmute
776                | CastKind::Subtype,
777                _,
778                _,
779            )
780            | Rvalue::BinaryOp(_, _)
781            | Rvalue::UnaryOp(_, _)
782            | Rvalue::Discriminant(_)
783            | Rvalue::Aggregate(_, _)
784            | Rvalue::WrapUnsafeBinder(_, _) => true,
785        }
786    }
787
788    pub fn ty<D>(&self, local_decls: &D, tcx: TyCtxt<'tcx>) -> Ty<'tcx>
789    where
790        D: ?Sized + HasLocalDecls<'tcx>,
791    {
792        match *self {
793            Rvalue::Use(ref operand) => operand.ty(local_decls, tcx),
794            Rvalue::Repeat(ref operand, count) => {
795                Ty::new_array_with_const_len(tcx, operand.ty(local_decls, tcx), count)
796            }
797            Rvalue::ThreadLocalRef(did) => tcx.thread_local_ptr_ty(did),
798            Rvalue::Ref(reg, bk, ref place) => {
799                let place_ty = place.ty(local_decls, tcx).ty;
800                Ty::new_ref(tcx, reg, place_ty, bk.to_mutbl_lossy())
801            }
802            Rvalue::RawPtr(kind, ref place) => {
803                let place_ty = place.ty(local_decls, tcx).ty;
804                Ty::new_ptr(tcx, place_ty, kind.to_mutbl_lossy())
805            }
806            Rvalue::Cast(.., ty) => ty,
807            Rvalue::BinaryOp(op, box (ref lhs, ref rhs)) => {
808                let lhs_ty = lhs.ty(local_decls, tcx);
809                let rhs_ty = rhs.ty(local_decls, tcx);
810                op.ty(tcx, lhs_ty, rhs_ty)
811            }
812            Rvalue::UnaryOp(op, ref operand) => {
813                let arg_ty = operand.ty(local_decls, tcx);
814                op.ty(tcx, arg_ty)
815            }
816            Rvalue::Discriminant(ref place) => place.ty(local_decls, tcx).ty.discriminant_ty(tcx),
817            Rvalue::Aggregate(ref ak, ref ops) => match **ak {
818                AggregateKind::Array(ty) => Ty::new_array(tcx, ty, ops.len() as u64),
819                AggregateKind::Tuple => {
820                    Ty::new_tup_from_iter(tcx, ops.iter().map(|op| op.ty(local_decls, tcx)))
821                }
822                AggregateKind::Adt(did, _, args, _, _) => tcx.type_of(did).instantiate(tcx, args),
823                AggregateKind::Closure(did, args) => Ty::new_closure(tcx, did, args),
824                AggregateKind::Coroutine(did, args) => Ty::new_coroutine(tcx, did, args),
825                AggregateKind::CoroutineClosure(did, args) => {
826                    Ty::new_coroutine_closure(tcx, did, args)
827                }
828                AggregateKind::RawPtr(ty, mutability) => Ty::new_ptr(tcx, ty, mutability),
829            },
830            Rvalue::CopyForDeref(ref place) => place.ty(local_decls, tcx).ty,
831            Rvalue::WrapUnsafeBinder(_, ty) => ty,
832        }
833    }
834}
835
836impl BorrowKind {
837    pub fn mutability(&self) -> Mutability {
838        match *self {
839            BorrowKind::Shared | BorrowKind::Fake(_) => Mutability::Not,
840            BorrowKind::Mut { .. } => Mutability::Mut,
841        }
842    }
843
844    /// Returns whether borrows represented by this kind are allowed to be split into separate
845    /// Reservation and Activation phases.
846    pub fn is_two_phase_borrow(&self) -> bool {
847        match *self {
848            BorrowKind::Shared
849            | BorrowKind::Fake(_)
850            | BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::ClosureCapture } => {
851                false
852            }
853            BorrowKind::Mut { kind: MutBorrowKind::TwoPhaseBorrow } => true,
854        }
855    }
856
857    pub fn to_mutbl_lossy(self) -> hir::Mutability {
858        match self {
859            BorrowKind::Mut { .. } => hir::Mutability::Mut,
860            BorrowKind::Shared => hir::Mutability::Not,
861
862            // We have no type corresponding to a shallow borrow, so use
863            // `&` as an approximation.
864            BorrowKind::Fake(_) => hir::Mutability::Not,
865        }
866    }
867}
868
869impl<'tcx> UnOp {
870    pub fn ty(&self, tcx: TyCtxt<'tcx>, arg_ty: Ty<'tcx>) -> Ty<'tcx> {
871        match self {
872            UnOp::Not | UnOp::Neg => arg_ty,
873            UnOp::PtrMetadata => arg_ty.pointee_metadata_ty_or_projection(tcx),
874        }
875    }
876}
877
878impl<'tcx> BinOp {
879    pub fn ty(&self, tcx: TyCtxt<'tcx>, lhs_ty: Ty<'tcx>, rhs_ty: Ty<'tcx>) -> Ty<'tcx> {
880        // FIXME: handle SIMD correctly
881        match self {
882            &BinOp::Add
883            | &BinOp::AddUnchecked
884            | &BinOp::Sub
885            | &BinOp::SubUnchecked
886            | &BinOp::Mul
887            | &BinOp::MulUnchecked
888            | &BinOp::Div
889            | &BinOp::Rem
890            | &BinOp::BitXor
891            | &BinOp::BitAnd
892            | &BinOp::BitOr => {
893                // these should be integers or floats of the same size.
894                match (&lhs_ty, &rhs_ty) {
    (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!(lhs_ty, rhs_ty);
895                lhs_ty
896            }
897            &BinOp::AddWithOverflow | &BinOp::SubWithOverflow | &BinOp::MulWithOverflow => {
898                // these should be integers of the same size.
899                match (&lhs_ty, &rhs_ty) {
    (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!(lhs_ty, rhs_ty);
900                Ty::new_tup(tcx, &[lhs_ty, tcx.types.bool])
901            }
902            &BinOp::Shl
903            | &BinOp::ShlUnchecked
904            | &BinOp::Shr
905            | &BinOp::ShrUnchecked
906            | &BinOp::Offset => {
907                lhs_ty // lhs_ty can be != rhs_ty
908            }
909            &BinOp::Eq | &BinOp::Lt | &BinOp::Le | &BinOp::Ne | &BinOp::Ge | &BinOp::Gt => {
910                tcx.types.bool
911            }
912            &BinOp::Cmp => {
913                // these should be integer-like types of the same size.
914                match (&lhs_ty, &rhs_ty) {
    (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!(lhs_ty, rhs_ty);
915                tcx.ty_ordering_enum(DUMMY_SP)
916            }
917        }
918    }
919    pub(crate) fn to_hir_binop(self) -> hir::BinOpKind {
920        match self {
921            // HIR `+`/`-`/`*` can map to either of these MIR BinOp, depending
922            // on whether overflow checks are enabled or not.
923            BinOp::Add | BinOp::AddWithOverflow => hir::BinOpKind::Add,
924            BinOp::Sub | BinOp::SubWithOverflow => hir::BinOpKind::Sub,
925            BinOp::Mul | BinOp::MulWithOverflow => hir::BinOpKind::Mul,
926            BinOp::Div => hir::BinOpKind::Div,
927            BinOp::Rem => hir::BinOpKind::Rem,
928            BinOp::BitXor => hir::BinOpKind::BitXor,
929            BinOp::BitAnd => hir::BinOpKind::BitAnd,
930            BinOp::BitOr => hir::BinOpKind::BitOr,
931            BinOp::Shl => hir::BinOpKind::Shl,
932            BinOp::Shr => hir::BinOpKind::Shr,
933            BinOp::Eq => hir::BinOpKind::Eq,
934            BinOp::Ne => hir::BinOpKind::Ne,
935            BinOp::Lt => hir::BinOpKind::Lt,
936            BinOp::Gt => hir::BinOpKind::Gt,
937            BinOp::Le => hir::BinOpKind::Le,
938            BinOp::Ge => hir::BinOpKind::Ge,
939            // We don't have HIR syntax for these.
940            BinOp::Cmp
941            | BinOp::AddUnchecked
942            | BinOp::SubUnchecked
943            | BinOp::MulUnchecked
944            | BinOp::ShlUnchecked
945            | BinOp::ShrUnchecked
946            | BinOp::Offset => {
947                ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
948            }
949        }
950    }
951
952    /// If this is a `FooWithOverflow`, return `Some(Foo)`.
953    pub fn overflowing_to_wrapping(self) -> Option<BinOp> {
954        Some(match self {
955            BinOp::AddWithOverflow => BinOp::Add,
956            BinOp::SubWithOverflow => BinOp::Sub,
957            BinOp::MulWithOverflow => BinOp::Mul,
958            _ => return None,
959        })
960    }
961
962    /// Returns whether this is a `FooWithOverflow`
963    pub fn is_overflowing(self) -> bool {
964        self.overflowing_to_wrapping().is_some()
965    }
966
967    /// If this is a `Foo`, return `Some(FooWithOverflow)`.
968    pub fn wrapping_to_overflowing(self) -> Option<BinOp> {
969        Some(match self {
970            BinOp::Add => BinOp::AddWithOverflow,
971            BinOp::Sub => BinOp::SubWithOverflow,
972            BinOp::Mul => BinOp::MulWithOverflow,
973            _ => return None,
974        })
975    }
976}
977
978impl From<Mutability> for RawPtrKind {
979    fn from(other: Mutability) -> Self {
980        match other {
981            Mutability::Mut => RawPtrKind::Mut,
982            Mutability::Not => RawPtrKind::Const,
983        }
984    }
985}
986
987impl RawPtrKind {
988    pub fn is_fake(self) -> bool {
989        match self {
990            RawPtrKind::Mut | RawPtrKind::Const => false,
991            RawPtrKind::FakeForPtrMetadata => true,
992        }
993    }
994
995    pub fn to_mutbl_lossy(self) -> Mutability {
996        match self {
997            RawPtrKind::Mut => Mutability::Mut,
998            RawPtrKind::Const => Mutability::Not,
999
1000            // We have no type corresponding to a fake borrow, so use
1001            // `*const` as an approximation.
1002            RawPtrKind::FakeForPtrMetadata => Mutability::Not,
1003        }
1004    }
1005
1006    pub fn ptr_str(self) -> &'static str {
1007        match self {
1008            RawPtrKind::Mut => "mut",
1009            RawPtrKind::Const => "const",
1010            RawPtrKind::FakeForPtrMetadata => "const (fake)",
1011        }
1012    }
1013}
1014
1015#[derive(#[automatically_derived]
impl<'tcx> ::core::default::Default for StmtDebugInfos<'tcx> {
    #[inline]
    fn default() -> StmtDebugInfos<'tcx> {
        StmtDebugInfos(::core::default::Default::default())
    }
}Default, #[automatically_derived]
impl<'tcx> ::core::fmt::Debug for StmtDebugInfos<'tcx> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_tuple_field1_finish(f, "StmtDebugInfos",
            &&self.0)
    }
}Debug, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for StmtDebugInfos<'tcx> {
    #[inline]
    fn clone(&self) -> StmtDebugInfos<'tcx> {
        StmtDebugInfos(::core::clone::Clone::clone(&self.0))
    }
}Clone, const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for StmtDebugInfos<'tcx> {
            fn encode(&self, __encoder: &mut __E) {
                match *self {
                    StmtDebugInfos(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                }
            }
        }
    };TyEncodable, const _: () =
    {
        impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
            ::rustc_serialize::Decodable<__D> for StmtDebugInfos<'tcx> {
            fn decode(__decoder: &mut __D) -> Self {
                StmtDebugInfos(::rustc_serialize::Decodable::decode(__decoder))
            }
        }
    };TyDecodable, const _: () =
    {
        impl<'tcx, '__ctx>
            ::rustc_data_structures::stable_hasher::HashStable<::rustc_middle::ich::StableHashingContext<'__ctx>>
            for StmtDebugInfos<'tcx> {
            #[inline]
            fn hash_stable(&self,
                __hcx: &mut ::rustc_middle::ich::StableHashingContext<'__ctx>,
                __hasher:
                    &mut ::rustc_data_structures::stable_hasher::StableHasher) {
                match *self {
                    StmtDebugInfos(ref __binding_0) => {
                        { __binding_0.hash_stable(__hcx, __hasher); }
                    }
                }
            }
        }
    };HashStable, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            for StmtDebugInfos<'tcx> {
            fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Result<Self, __F::Error> {
                Ok(match self {
                        StmtDebugInfos(__binding_0) => {
                            StmtDebugInfos(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?)
                        }
                    })
            }
            fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Self {
                match self {
                    StmtDebugInfos(__binding_0) => {
                        StmtDebugInfos(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder))
                    }
                }
            }
        }
    };TypeFoldable, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for StmtDebugInfos<'tcx> {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    StmtDebugInfos(ref __binding_0) => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                }
                <__V::Result as ::rustc_middle::ty::VisitorResult>::output()
            }
        }
    };TypeVisitable)]
1016pub struct StmtDebugInfos<'tcx>(Vec<StmtDebugInfo<'tcx>>);
1017
1018impl<'tcx> StmtDebugInfos<'tcx> {
1019    pub fn push(&mut self, debuginfo: StmtDebugInfo<'tcx>) {
1020        self.0.push(debuginfo);
1021    }
1022
1023    pub fn drop_debuginfo(&mut self) {
1024        self.0.clear();
1025    }
1026
1027    pub fn is_empty(&self) -> bool {
1028        self.0.is_empty()
1029    }
1030
1031    pub fn prepend(&mut self, debuginfos: &mut Self) {
1032        if debuginfos.is_empty() {
1033            return;
1034        };
1035        debuginfos.0.append(self);
1036        std::mem::swap(debuginfos, self);
1037    }
1038
1039    pub fn append(&mut self, debuginfos: &mut Self) {
1040        if debuginfos.is_empty() {
1041            return;
1042        };
1043        self.0.append(debuginfos);
1044    }
1045
1046    pub fn extend(&mut self, debuginfos: &Self) {
1047        if debuginfos.is_empty() {
1048            return;
1049        };
1050        self.0.extend_from_slice(debuginfos);
1051    }
1052
1053    pub fn retain<F>(&mut self, f: F)
1054    where
1055        F: FnMut(&StmtDebugInfo<'tcx>) -> bool,
1056    {
1057        self.0.retain(f);
1058    }
1059}
1060
1061impl<'tcx> ops::Deref for StmtDebugInfos<'tcx> {
1062    type Target = Vec<StmtDebugInfo<'tcx>>;
1063
1064    #[inline]
1065    fn deref(&self) -> &Vec<StmtDebugInfo<'tcx>> {
1066        &self.0
1067    }
1068}
1069
1070impl<'tcx> ops::DerefMut for StmtDebugInfos<'tcx> {
1071    #[inline]
1072    fn deref_mut(&mut self) -> &mut Vec<StmtDebugInfo<'tcx>> {
1073        &mut self.0
1074    }
1075}
1076
1077#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for StmtDebugInfo<'tcx> {
    #[inline]
    fn clone(&self) -> StmtDebugInfo<'tcx> {
        match self {
            StmtDebugInfo::AssignRef(__self_0, __self_1) =>
                StmtDebugInfo::AssignRef(::core::clone::Clone::clone(__self_0),
                    ::core::clone::Clone::clone(__self_1)),
            StmtDebugInfo::InvalidAssign(__self_0) =>
                StmtDebugInfo::InvalidAssign(::core::clone::Clone::clone(__self_0)),
        }
    }
}Clone, const _: () =
    {
        impl<'tcx, __E: ::rustc_middle::ty::codec::TyEncoder<'tcx>>
            ::rustc_serialize::Encodable<__E> for StmtDebugInfo<'tcx> {
            fn encode(&self, __encoder: &mut __E) {
                let disc =
                    match *self {
                        StmtDebugInfo::AssignRef(ref __binding_0, ref __binding_1)
                            => {
                            0usize
                        }
                        StmtDebugInfo::InvalidAssign(ref __binding_0) => { 1usize }
                    };
                ::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
                match *self {
                    StmtDebugInfo::AssignRef(ref __binding_0, ref __binding_1)
                        => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_1,
                            __encoder);
                    }
                    StmtDebugInfo::InvalidAssign(ref __binding_0) => {
                        ::rustc_serialize::Encodable::<__E>::encode(__binding_0,
                            __encoder);
                    }
                }
            }
        }
    };TyEncodable, const _: () =
    {
        impl<'tcx, __D: ::rustc_middle::ty::codec::TyDecoder<'tcx>>
            ::rustc_serialize::Decodable<__D> for StmtDebugInfo<'tcx> {
            fn decode(__decoder: &mut __D) -> Self {
                match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
                    {
                    0usize => {
                        StmtDebugInfo::AssignRef(::rustc_serialize::Decodable::decode(__decoder),
                            ::rustc_serialize::Decodable::decode(__decoder))
                    }
                    1usize => {
                        StmtDebugInfo::InvalidAssign(::rustc_serialize::Decodable::decode(__decoder))
                    }
                    n => {
                        ::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `StmtDebugInfo`, expected 0..2, actual {0}",
                                n));
                    }
                }
            }
        }
    };TyDecodable, const _: () =
    {
        impl<'tcx, '__ctx>
            ::rustc_data_structures::stable_hasher::HashStable<::rustc_middle::ich::StableHashingContext<'__ctx>>
            for StmtDebugInfo<'tcx> {
            #[inline]
            fn hash_stable(&self,
                __hcx: &mut ::rustc_middle::ich::StableHashingContext<'__ctx>,
                __hasher:
                    &mut ::rustc_data_structures::stable_hasher::StableHasher) {
                ::std::mem::discriminant(self).hash_stable(__hcx, __hasher);
                match *self {
                    StmtDebugInfo::AssignRef(ref __binding_0, ref __binding_1)
                        => {
                        { __binding_0.hash_stable(__hcx, __hasher); }
                        { __binding_1.hash_stable(__hcx, __hasher); }
                    }
                    StmtDebugInfo::InvalidAssign(ref __binding_0) => {
                        { __binding_0.hash_stable(__hcx, __hasher); }
                    }
                }
            }
        }
    };HashStable, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeFoldable<::rustc_middle::ty::TyCtxt<'tcx>>
            for StmtDebugInfo<'tcx> {
            fn try_fold_with<__F: ::rustc_middle::ty::FallibleTypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Result<Self, __F::Error> {
                Ok(match self {
                        StmtDebugInfo::AssignRef(__binding_0, __binding_1) => {
                            StmtDebugInfo::AssignRef(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?,
                                ::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_1,
                                        __folder)?)
                        }
                        StmtDebugInfo::InvalidAssign(__binding_0) => {
                            StmtDebugInfo::InvalidAssign(::rustc_middle::ty::TypeFoldable::try_fold_with(__binding_0,
                                        __folder)?)
                        }
                    })
            }
            fn fold_with<__F: ::rustc_middle::ty::TypeFolder<::rustc_middle::ty::TyCtxt<'tcx>>>(self,
                __folder: &mut __F) -> Self {
                match self {
                    StmtDebugInfo::AssignRef(__binding_0, __binding_1) => {
                        StmtDebugInfo::AssignRef(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder),
                            ::rustc_middle::ty::TypeFoldable::fold_with(__binding_1,
                                __folder))
                    }
                    StmtDebugInfo::InvalidAssign(__binding_0) => {
                        StmtDebugInfo::InvalidAssign(::rustc_middle::ty::TypeFoldable::fold_with(__binding_0,
                                __folder))
                    }
                }
            }
        }
    };TypeFoldable, const _: () =
    {
        impl<'tcx>
            ::rustc_middle::ty::TypeVisitable<::rustc_middle::ty::TyCtxt<'tcx>>
            for StmtDebugInfo<'tcx> {
            fn visit_with<__V: ::rustc_middle::ty::TypeVisitor<::rustc_middle::ty::TyCtxt<'tcx>>>(&self,
                __visitor: &mut __V) -> __V::Result {
                match *self {
                    StmtDebugInfo::AssignRef(ref __binding_0, ref __binding_1)
                        => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_1,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                    StmtDebugInfo::InvalidAssign(ref __binding_0) => {
                        {
                            match ::rustc_middle::ty::VisitorResult::branch(::rustc_middle::ty::TypeVisitable::visit_with(__binding_0,
                                        __visitor)) {
                                ::core::ops::ControlFlow::Continue(()) => {}
                                ::core::ops::ControlFlow::Break(r) => {
                                    return ::rustc_middle::ty::VisitorResult::from_residual(r);
                                }
                            }
                        }
                    }
                }
                <__V::Result as ::rustc_middle::ty::VisitorResult>::output()
            }
        }
    };TypeVisitable)]
1078pub enum StmtDebugInfo<'tcx> {
1079    AssignRef(Local, Place<'tcx>),
1080    InvalidAssign(Local),
1081}