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_query_system::ich::StableHashingContext<'__ctx>>
            for Statement<'tcx> {
            #[inline]
            fn hash_stable(&self,
                __hcx:
                    &mut ::rustc_query_system::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> {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_receiver_is_total_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    pub fn ty_from<D>(
436        local: Local,
437        projection: &[PlaceElem<'tcx>],
438        local_decls: &D,
439        tcx: TyCtxt<'tcx>,
440    ) -> PlaceTy<'tcx>
441    where
442        D: ?Sized + HasLocalDecls<'tcx>,
443    {
444        PlaceTy::from_ty(local_decls.local_decls()[local].ty).multi_projection_ty(tcx, projection)
445    }
446
447    pub fn ty<D: ?Sized>(&self, local_decls: &D, tcx: TyCtxt<'tcx>) -> PlaceTy<'tcx>
448    where
449        D: HasLocalDecls<'tcx>,
450    {
451        Place::ty_from(self.local, self.projection, local_decls, tcx)
452    }
453}
454
455impl From<Local> for Place<'_> {
456    #[inline]
457    fn from(local: Local) -> Self {
458        Place { local, projection: List::empty() }
459    }
460}
461
462impl<'tcx> PlaceRef<'tcx> {
463    /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or
464    /// a single deref of a local.
465    pub fn local_or_deref_local(&self) -> Option<Local> {
466        match *self {
467            PlaceRef { local, projection: [] }
468            | PlaceRef { local, projection: [ProjectionElem::Deref] } => Some(local),
469            _ => None,
470        }
471    }
472
473    /// Returns `true` if this `Place` contains a `Deref` projection.
474    ///
475    /// If `Place::is_indirect` returns false, the caller knows that the `Place` refers to the
476    /// same region of memory as its base.
477    pub fn is_indirect(&self) -> bool {
478        self.projection.iter().any(|elem| elem.is_indirect())
479    }
480
481    /// Returns `true` if this `Place`'s first projection is `Deref`.
482    ///
483    /// This is useful because for MIR phases `AnalysisPhase::PostCleanup` and later,
484    /// `Deref` projections can only occur as the first projection. In that case this method
485    /// is equivalent to `is_indirect`, but faster.
486    pub fn is_indirect_first_projection(&self) -> bool {
487        // To make sure this is not accidentally used in wrong mir phase
488        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!(
489            self.projection.is_empty() || !self.projection[1..].contains(&PlaceElem::Deref)
490        );
491        self.projection.first() == Some(&PlaceElem::Deref)
492    }
493
494    /// If this place represents a local variable like `_X` with no
495    /// projections, return `Some(_X)`.
496    #[inline]
497    pub fn as_local(&self) -> Option<Local> {
498        match *self {
499            PlaceRef { local, projection: [] } => Some(local),
500            _ => None,
501        }
502    }
503
504    #[inline]
505    pub fn to_place(&self, tcx: TyCtxt<'tcx>) -> Place<'tcx> {
506        Place { local: self.local, projection: tcx.mk_place_elems(self.projection) }
507    }
508
509    #[inline]
510    pub fn last_projection(&self) -> Option<(PlaceRef<'tcx>, PlaceElem<'tcx>)> {
511        if let &[ref proj_base @ .., elem] = self.projection {
512            Some((PlaceRef { local: self.local, projection: proj_base }, elem))
513        } else {
514            None
515        }
516    }
517
518    /// Iterate over the projections in evaluation order, i.e., the first element is the base with
519    /// its projection and then subsequently more projections are added.
520    /// As a concrete example, given the place a.b.c, this would yield:
521    /// - (a, .b)
522    /// - (a.b, .c)
523    ///
524    /// Given a place without projections, the iterator is empty.
525    #[inline]
526    pub fn iter_projections(
527        self,
528    ) -> impl Iterator<Item = (PlaceRef<'tcx>, PlaceElem<'tcx>)> + DoubleEndedIterator {
529        self.projection.iter().enumerate().map(move |(i, proj)| {
530            let base = PlaceRef { local: self.local, projection: &self.projection[..i] };
531            (base, *proj)
532        })
533    }
534
535    /// Return the place accessed locals that include the base local.
536    pub fn accessed_locals(self) -> impl Iterator<Item = Local> {
537        std::iter::once(self.local).chain(self.projection.iter().filter_map(|proj| match proj {
538            ProjectionElem::Index(local) => Some(*local),
539            ProjectionElem::Deref
540            | ProjectionElem::Field(_, _)
541            | ProjectionElem::ConstantIndex { .. }
542            | ProjectionElem::Subslice { .. }
543            | ProjectionElem::Downcast(_, _)
544            | ProjectionElem::OpaqueCast(_)
545            | ProjectionElem::UnwrapUnsafeBinder(_) => None,
546        }))
547    }
548
549    /// Generates a new place by appending `more_projections` to the existing ones
550    /// and interning the result.
551    pub fn project_deeper(
552        self,
553        more_projections: &[PlaceElem<'tcx>],
554        tcx: TyCtxt<'tcx>,
555    ) -> Place<'tcx> {
556        let mut v: Vec<PlaceElem<'tcx>>;
557
558        let new_projections = if self.projection.is_empty() {
559            more_projections
560        } else {
561            v = Vec::with_capacity(self.projection.len() + more_projections.len());
562            v.extend(self.projection);
563            v.extend(more_projections);
564            &v
565        };
566
567        Place { local: self.local, projection: tcx.mk_place_elems(new_projections) }
568    }
569
570    pub fn ty<D>(&self, local_decls: &D, tcx: TyCtxt<'tcx>) -> PlaceTy<'tcx>
571    where
572        D: ?Sized + HasLocalDecls<'tcx>,
573    {
574        Place::ty_from(self.local, self.projection, local_decls, tcx)
575    }
576}
577
578impl From<Local> for PlaceRef<'_> {
579    #[inline]
580    fn from(local: Local) -> Self {
581        PlaceRef { local, projection: &[] }
582    }
583}
584
585///////////////////////////////////////////////////////////////////////////
586// Operands
587
588impl<'tcx> Operand<'tcx> {
589    /// Convenience helper to make a constant that refers to the fn
590    /// with given `DefId` and args. Since this is used to synthesize
591    /// MIR, assumes `user_ty` is None.
592    pub fn function_handle(
593        tcx: TyCtxt<'tcx>,
594        def_id: DefId,
595        args: impl IntoIterator<Item = GenericArg<'tcx>>,
596        span: Span,
597    ) -> Self {
598        let ty = Ty::new_fn_def(tcx, def_id, args);
599        Operand::Constant(Box::new(ConstOperand {
600            span,
601            user_ty: None,
602            const_: Const::Val(ConstValue::ZeroSized, ty),
603        }))
604    }
605
606    /// Convenience helper to make a constant that refers to the given `DefId` and args. Since this
607    /// is used to synthesize MIR, assumes `user_ty` is None.
608    pub fn unevaluated_constant(
609        tcx: TyCtxt<'tcx>,
610        def_id: DefId,
611        args: &[GenericArg<'tcx>],
612        span: Span,
613    ) -> Self {
614        let const_ = Const::from_unevaluated(tcx, def_id).instantiate(tcx, args);
615        Operand::Constant(Box::new(ConstOperand { span, user_ty: None, const_ }))
616    }
617
618    pub fn is_move(&self) -> bool {
619        #[allow(non_exhaustive_omitted_patterns)] match self {
    Operand::Move(..) => true,
    _ => false,
}matches!(self, Operand::Move(..))
620    }
621
622    /// Convenience helper to make a literal-like constant from a given scalar value.
623    /// Since this is used to synthesize MIR, assumes `user_ty` is None.
624    pub fn const_from_scalar(
625        tcx: TyCtxt<'tcx>,
626        ty: Ty<'tcx>,
627        val: Scalar,
628        span: Span,
629    ) -> Operand<'tcx> {
630        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!({
631            let typing_env = ty::TypingEnv::fully_monomorphized();
632            let type_size = tcx
633                .layout_of(typing_env.as_query_input(ty))
634                .unwrap_or_else(|e| panic!("could not compute layout for {ty:?}: {e:?}"))
635                .size;
636            let scalar_size = match val {
637                Scalar::Int(int) => int.size(),
638                _ => panic!("Invalid scalar type {val:?}"),
639            };
640            scalar_size == type_size
641        });
642        Operand::Constant(Box::new(ConstOperand {
643            span,
644            user_ty: None,
645            const_: Const::Val(ConstValue::Scalar(val), ty),
646        }))
647    }
648
649    pub fn to_copy(&self) -> Self {
650        match *self {
651            Operand::Copy(_) | Operand::Constant(_) | Operand::RuntimeChecks(_) => self.clone(),
652            Operand::Move(place) => Operand::Copy(place),
653        }
654    }
655
656    /// Returns the `Place` that is the target of this `Operand`, or `None` if this `Operand` is a
657    /// constant.
658    pub fn place(&self) -> Option<Place<'tcx>> {
659        match self {
660            Operand::Copy(place) | Operand::Move(place) => Some(*place),
661            Operand::Constant(_) | Operand::RuntimeChecks(_) => None,
662        }
663    }
664
665    /// Returns the `ConstOperand` that is the target of this `Operand`, or `None` if this `Operand` is a
666    /// place.
667    pub fn constant(&self) -> Option<&ConstOperand<'tcx>> {
668        match self {
669            Operand::Constant(x) => Some(&**x),
670            Operand::Copy(_) | Operand::Move(_) | Operand::RuntimeChecks(_) => None,
671        }
672    }
673
674    /// Gets the `ty::FnDef` from an operand if it's a constant function item.
675    ///
676    /// While this is unlikely in general, it's the normal case of what you'll
677    /// find as the `func` in a [`TerminatorKind::Call`].
678    pub fn const_fn_def(&self) -> Option<(DefId, GenericArgsRef<'tcx>)> {
679        let const_ty = self.constant()?.const_.ty();
680        if let ty::FnDef(def_id, args) = *const_ty.kind() { Some((def_id, args)) } else { None }
681    }
682
683    pub fn ty<D>(&self, local_decls: &D, tcx: TyCtxt<'tcx>) -> Ty<'tcx>
684    where
685        D: ?Sized + HasLocalDecls<'tcx>,
686    {
687        match self {
688            &Operand::Copy(ref l) | &Operand::Move(ref l) => l.ty(local_decls, tcx).ty,
689            Operand::Constant(c) => c.const_.ty(),
690            Operand::RuntimeChecks(_) => tcx.types.bool,
691        }
692    }
693
694    pub fn span<D>(&self, local_decls: &D) -> Span
695    where
696        D: ?Sized + HasLocalDecls<'tcx>,
697    {
698        match self {
699            &Operand::Copy(ref l) | &Operand::Move(ref l) => {
700                local_decls.local_decls()[l.local].source_info.span
701            }
702            Operand::Constant(c) => c.span,
703            // User code should not contain this operand, so we should not need this span.
704            Operand::RuntimeChecks(_) => DUMMY_SP,
705        }
706    }
707}
708
709impl<'tcx> ConstOperand<'tcx> {
710    pub fn check_static_ptr(&self, tcx: TyCtxt<'_>) -> Option<DefId> {
711        match self.const_.try_to_scalar() {
712            Some(Scalar::Ptr(ptr, _size)) => match tcx.global_alloc(ptr.provenance.alloc_id()) {
713                GlobalAlloc::Static(def_id) => {
714                    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));
715                    Some(def_id)
716                }
717                _ => None,
718            },
719            _ => None,
720        }
721    }
722
723    #[inline]
724    pub fn ty(&self) -> Ty<'tcx> {
725        self.const_.ty()
726    }
727}
728
729///////////////////////////////////////////////////////////////////////////
730// Rvalues
731
732pub enum RvalueInitializationState {
733    Shallow,
734    Deep,
735}
736
737impl<'tcx> Rvalue<'tcx> {
738    /// Returns true if rvalue can be safely removed when the result is unused.
739    #[inline]
740    pub fn is_safe_to_remove(&self) -> bool {
741        match self {
742            // Pointer to int casts may be side-effects due to exposing the provenance.
743            // While the model is undecided, we should be conservative. See
744            // <https://www.ralfj.de/blog/2022/04/11/provenance-exposed.html>
745            Rvalue::Cast(CastKind::PointerExposeProvenance, _, _) => false,
746
747            Rvalue::Use(_)
748            | Rvalue::CopyForDeref(_)
749            | Rvalue::Repeat(_, _)
750            | Rvalue::Ref(_, _, _)
751            | Rvalue::ThreadLocalRef(_)
752            | Rvalue::RawPtr(_, _)
753            | Rvalue::Cast(
754                CastKind::IntToInt
755                | CastKind::FloatToInt
756                | CastKind::FloatToFloat
757                | CastKind::IntToFloat
758                | CastKind::FnPtrToPtr
759                | CastKind::PtrToPtr
760                | CastKind::PointerCoercion(_, _)
761                | CastKind::PointerWithExposedProvenance
762                | CastKind::Transmute
763                | CastKind::Subtype,
764                _,
765                _,
766            )
767            | Rvalue::BinaryOp(_, _)
768            | Rvalue::UnaryOp(_, _)
769            | Rvalue::Discriminant(_)
770            | Rvalue::Aggregate(_, _)
771            | Rvalue::ShallowInitBox(_, _)
772            | Rvalue::WrapUnsafeBinder(_, _) => true,
773        }
774    }
775
776    pub fn ty<D>(&self, local_decls: &D, tcx: TyCtxt<'tcx>) -> Ty<'tcx>
777    where
778        D: ?Sized + HasLocalDecls<'tcx>,
779    {
780        match *self {
781            Rvalue::Use(ref operand) => operand.ty(local_decls, tcx),
782            Rvalue::Repeat(ref operand, count) => {
783                Ty::new_array_with_const_len(tcx, operand.ty(local_decls, tcx), count)
784            }
785            Rvalue::ThreadLocalRef(did) => tcx.thread_local_ptr_ty(did),
786            Rvalue::Ref(reg, bk, ref place) => {
787                let place_ty = place.ty(local_decls, tcx).ty;
788                Ty::new_ref(tcx, reg, place_ty, bk.to_mutbl_lossy())
789            }
790            Rvalue::RawPtr(kind, ref place) => {
791                let place_ty = place.ty(local_decls, tcx).ty;
792                Ty::new_ptr(tcx, place_ty, kind.to_mutbl_lossy())
793            }
794            Rvalue::Cast(.., ty) => ty,
795            Rvalue::BinaryOp(op, box (ref lhs, ref rhs)) => {
796                let lhs_ty = lhs.ty(local_decls, tcx);
797                let rhs_ty = rhs.ty(local_decls, tcx);
798                op.ty(tcx, lhs_ty, rhs_ty)
799            }
800            Rvalue::UnaryOp(op, ref operand) => {
801                let arg_ty = operand.ty(local_decls, tcx);
802                op.ty(tcx, arg_ty)
803            }
804            Rvalue::Discriminant(ref place) => place.ty(local_decls, tcx).ty.discriminant_ty(tcx),
805            Rvalue::Aggregate(ref ak, ref ops) => match **ak {
806                AggregateKind::Array(ty) => Ty::new_array(tcx, ty, ops.len() as u64),
807                AggregateKind::Tuple => {
808                    Ty::new_tup_from_iter(tcx, ops.iter().map(|op| op.ty(local_decls, tcx)))
809                }
810                AggregateKind::Adt(did, _, args, _, _) => tcx.type_of(did).instantiate(tcx, args),
811                AggregateKind::Closure(did, args) => Ty::new_closure(tcx, did, args),
812                AggregateKind::Coroutine(did, args) => Ty::new_coroutine(tcx, did, args),
813                AggregateKind::CoroutineClosure(did, args) => {
814                    Ty::new_coroutine_closure(tcx, did, args)
815                }
816                AggregateKind::RawPtr(ty, mutability) => Ty::new_ptr(tcx, ty, mutability),
817            },
818            Rvalue::ShallowInitBox(_, ty) => Ty::new_box(tcx, ty),
819            Rvalue::CopyForDeref(ref place) => place.ty(local_decls, tcx).ty,
820            Rvalue::WrapUnsafeBinder(_, ty) => ty,
821        }
822    }
823
824    #[inline]
825    /// Returns `true` if this rvalue is deeply initialized (most rvalues) or
826    /// whether its only shallowly initialized (`Rvalue::Box`).
827    pub fn initialization_state(&self) -> RvalueInitializationState {
828        match *self {
829            Rvalue::ShallowInitBox(_, _) => RvalueInitializationState::Shallow,
830            _ => RvalueInitializationState::Deep,
831        }
832    }
833}
834
835impl BorrowKind {
836    pub fn mutability(&self) -> Mutability {
837        match *self {
838            BorrowKind::Shared | BorrowKind::Fake(_) => Mutability::Not,
839            BorrowKind::Mut { .. } => Mutability::Mut,
840        }
841    }
842
843    /// Returns whether borrows represented by this kind are allowed to be split into separate
844    /// Reservation and Activation phases.
845    pub fn is_two_phase_borrow(&self) -> bool {
846        match *self {
847            BorrowKind::Shared
848            | BorrowKind::Fake(_)
849            | BorrowKind::Mut { kind: MutBorrowKind::Default | MutBorrowKind::ClosureCapture } => {
850                false
851            }
852            BorrowKind::Mut { kind: MutBorrowKind::TwoPhaseBorrow } => true,
853        }
854    }
855
856    pub fn to_mutbl_lossy(self) -> hir::Mutability {
857        match self {
858            BorrowKind::Mut { .. } => hir::Mutability::Mut,
859            BorrowKind::Shared => hir::Mutability::Not,
860
861            // We have no type corresponding to a shallow borrow, so use
862            // `&` as an approximation.
863            BorrowKind::Fake(_) => hir::Mutability::Not,
864        }
865    }
866}
867
868impl<'tcx> UnOp {
869    pub fn ty(&self, tcx: TyCtxt<'tcx>, arg_ty: Ty<'tcx>) -> Ty<'tcx> {
870        match self {
871            UnOp::Not | UnOp::Neg => arg_ty,
872            UnOp::PtrMetadata => arg_ty.pointee_metadata_ty_or_projection(tcx),
873        }
874    }
875}
876
877impl<'tcx> BinOp {
878    pub fn ty(&self, tcx: TyCtxt<'tcx>, lhs_ty: Ty<'tcx>, rhs_ty: Ty<'tcx>) -> Ty<'tcx> {
879        // FIXME: handle SIMD correctly
880        match self {
881            &BinOp::Add
882            | &BinOp::AddUnchecked
883            | &BinOp::Sub
884            | &BinOp::SubUnchecked
885            | &BinOp::Mul
886            | &BinOp::MulUnchecked
887            | &BinOp::Div
888            | &BinOp::Rem
889            | &BinOp::BitXor
890            | &BinOp::BitAnd
891            | &BinOp::BitOr => {
892                // these should be integers or floats of the same size.
893                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);
894                lhs_ty
895            }
896            &BinOp::AddWithOverflow | &BinOp::SubWithOverflow | &BinOp::MulWithOverflow => {
897                // these should be integers of the same size.
898                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);
899                Ty::new_tup(tcx, &[lhs_ty, tcx.types.bool])
900            }
901            &BinOp::Shl
902            | &BinOp::ShlUnchecked
903            | &BinOp::Shr
904            | &BinOp::ShrUnchecked
905            | &BinOp::Offset => {
906                lhs_ty // lhs_ty can be != rhs_ty
907            }
908            &BinOp::Eq | &BinOp::Lt | &BinOp::Le | &BinOp::Ne | &BinOp::Ge | &BinOp::Gt => {
909                tcx.types.bool
910            }
911            &BinOp::Cmp => {
912                // these should be integer-like types of the same size.
913                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);
914                tcx.ty_ordering_enum(DUMMY_SP)
915            }
916        }
917    }
918    pub(crate) fn to_hir_binop(self) -> hir::BinOpKind {
919        match self {
920            // HIR `+`/`-`/`*` can map to either of these MIR BinOp, depending
921            // on whether overflow checks are enabled or not.
922            BinOp::Add | BinOp::AddWithOverflow => hir::BinOpKind::Add,
923            BinOp::Sub | BinOp::SubWithOverflow => hir::BinOpKind::Sub,
924            BinOp::Mul | BinOp::MulWithOverflow => hir::BinOpKind::Mul,
925            BinOp::Div => hir::BinOpKind::Div,
926            BinOp::Rem => hir::BinOpKind::Rem,
927            BinOp::BitXor => hir::BinOpKind::BitXor,
928            BinOp::BitAnd => hir::BinOpKind::BitAnd,
929            BinOp::BitOr => hir::BinOpKind::BitOr,
930            BinOp::Shl => hir::BinOpKind::Shl,
931            BinOp::Shr => hir::BinOpKind::Shr,
932            BinOp::Eq => hir::BinOpKind::Eq,
933            BinOp::Ne => hir::BinOpKind::Ne,
934            BinOp::Lt => hir::BinOpKind::Lt,
935            BinOp::Gt => hir::BinOpKind::Gt,
936            BinOp::Le => hir::BinOpKind::Le,
937            BinOp::Ge => hir::BinOpKind::Ge,
938            // We don't have HIR syntax for these.
939            BinOp::Cmp
940            | BinOp::AddUnchecked
941            | BinOp::SubUnchecked
942            | BinOp::MulUnchecked
943            | BinOp::ShlUnchecked
944            | BinOp::ShrUnchecked
945            | BinOp::Offset => {
946                ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
947            }
948        }
949    }
950
951    /// If this is a `FooWithOverflow`, return `Some(Foo)`.
952    pub fn overflowing_to_wrapping(self) -> Option<BinOp> {
953        Some(match self {
954            BinOp::AddWithOverflow => BinOp::Add,
955            BinOp::SubWithOverflow => BinOp::Sub,
956            BinOp::MulWithOverflow => BinOp::Mul,
957            _ => return None,
958        })
959    }
960
961    /// Returns whether this is a `FooWithOverflow`
962    pub fn is_overflowing(self) -> bool {
963        self.overflowing_to_wrapping().is_some()
964    }
965
966    /// If this is a `Foo`, return `Some(FooWithOverflow)`.
967    pub fn wrapping_to_overflowing(self) -> Option<BinOp> {
968        Some(match self {
969            BinOp::Add => BinOp::AddWithOverflow,
970            BinOp::Sub => BinOp::SubWithOverflow,
971            BinOp::Mul => BinOp::MulWithOverflow,
972            _ => return None,
973        })
974    }
975}
976
977impl From<Mutability> for RawPtrKind {
978    fn from(other: Mutability) -> Self {
979        match other {
980            Mutability::Mut => RawPtrKind::Mut,
981            Mutability::Not => RawPtrKind::Const,
982        }
983    }
984}
985
986impl RawPtrKind {
987    pub fn is_fake(self) -> bool {
988        match self {
989            RawPtrKind::Mut | RawPtrKind::Const => false,
990            RawPtrKind::FakeForPtrMetadata => true,
991        }
992    }
993
994    pub fn to_mutbl_lossy(self) -> Mutability {
995        match self {
996            RawPtrKind::Mut => Mutability::Mut,
997            RawPtrKind::Const => Mutability::Not,
998
999            // We have no type corresponding to a fake borrow, so use
1000            // `*const` as an approximation.
1001            RawPtrKind::FakeForPtrMetadata => Mutability::Not,
1002        }
1003    }
1004
1005    pub fn ptr_str(self) -> &'static str {
1006        match self {
1007            RawPtrKind::Mut => "mut",
1008            RawPtrKind::Const => "const",
1009            RawPtrKind::FakeForPtrMetadata => "const (fake)",
1010        }
1011    }
1012}
1013
1014#[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_query_system::ich::StableHashingContext<'__ctx>>
            for StmtDebugInfos<'tcx> {
            #[inline]
            fn hash_stable(&self,
                __hcx:
                    &mut ::rustc_query_system::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)]
1015pub struct StmtDebugInfos<'tcx>(Vec<StmtDebugInfo<'tcx>>);
1016
1017impl<'tcx> StmtDebugInfos<'tcx> {
1018    pub fn push(&mut self, debuginfo: StmtDebugInfo<'tcx>) {
1019        self.0.push(debuginfo);
1020    }
1021
1022    pub fn drop_debuginfo(&mut self) {
1023        self.0.clear();
1024    }
1025
1026    pub fn is_empty(&self) -> bool {
1027        self.0.is_empty()
1028    }
1029
1030    pub fn prepend(&mut self, debuginfos: &mut Self) {
1031        if debuginfos.is_empty() {
1032            return;
1033        };
1034        debuginfos.0.append(self);
1035        std::mem::swap(debuginfos, self);
1036    }
1037
1038    pub fn append(&mut self, debuginfos: &mut Self) {
1039        if debuginfos.is_empty() {
1040            return;
1041        };
1042        self.0.append(debuginfos);
1043    }
1044
1045    pub fn extend(&mut self, debuginfos: &Self) {
1046        if debuginfos.is_empty() {
1047            return;
1048        };
1049        self.0.extend_from_slice(debuginfos);
1050    }
1051
1052    pub fn retain<F>(&mut self, f: F)
1053    where
1054        F: FnMut(&StmtDebugInfo<'tcx>) -> bool,
1055    {
1056        self.0.retain(f);
1057    }
1058}
1059
1060impl<'tcx> ops::Deref for StmtDebugInfos<'tcx> {
1061    type Target = Vec<StmtDebugInfo<'tcx>>;
1062
1063    #[inline]
1064    fn deref(&self) -> &Vec<StmtDebugInfo<'tcx>> {
1065        &self.0
1066    }
1067}
1068
1069impl<'tcx> ops::DerefMut for StmtDebugInfos<'tcx> {
1070    #[inline]
1071    fn deref_mut(&mut self) -> &mut Vec<StmtDebugInfo<'tcx>> {
1072        &mut self.0
1073    }
1074}
1075
1076#[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_query_system::ich::StableHashingContext<'__ctx>>
            for StmtDebugInfo<'tcx> {
            #[inline]
            fn hash_stable(&self,
                __hcx:
                    &mut ::rustc_query_system::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)]
1077pub enum StmtDebugInfo<'tcx> {
1078    AssignRef(Local, Place<'tcx>),
1079    InvalidAssign(Local),
1080}