Skip to main content

rustc_codegen_ssa/mir/
operand.rs

1use std::fmt;
2
3use itertools::Either;
4use rustc_abi as abi;
5use rustc_abi::{
6    Align, BackendRepr, FIRST_VARIANT, FieldIdx, Primitive, Size, TagEncoding, VariantIdx, Variants,
7};
8use rustc_hir::LangItem;
9use rustc_middle::mir::interpret::{Pointer, Scalar, alloc_range};
10use rustc_middle::mir::{self, ConstValue};
11use rustc_middle::ty::layout::{LayoutOf, TyAndLayout};
12use rustc_middle::ty::{self, Ty};
13use rustc_middle::{bug, span_bug};
14use rustc_session::config::{AnnotateMoves, DebugInfo, OptLevel};
15use tracing::{debug, instrument};
16
17use super::place::{PlaceRef, PlaceValue};
18use super::rvalue::transmute_scalar;
19use super::{FunctionCx, LocalRef};
20use crate::MemFlags;
21use crate::common::IntPredicate;
22use crate::traits::*;
23
24/// The representation of a Rust value. The enum variant is in fact
25/// uniquely determined by the value's type, but is kept as a
26/// safety check.
27#[derive(#[automatically_derived]
impl<V: ::core::marker::Copy> ::core::marker::Copy for OperandValue<V> { }Copy, #[automatically_derived]
impl<V: ::core::clone::Clone> ::core::clone::Clone for OperandValue<V> {
    #[inline]
    fn clone(&self) -> OperandValue<V> {
        match self {
            OperandValue::Ref(__self_0) =>
                OperandValue::Ref(::core::clone::Clone::clone(__self_0)),
            OperandValue::Immediate(__self_0) =>
                OperandValue::Immediate(::core::clone::Clone::clone(__self_0)),
            OperandValue::Pair(__self_0, __self_1) =>
                OperandValue::Pair(::core::clone::Clone::clone(__self_0),
                    ::core::clone::Clone::clone(__self_1)),
            OperandValue::ZeroSized => OperandValue::ZeroSized,
        }
    }
}Clone, #[automatically_derived]
impl<V: ::core::fmt::Debug> ::core::fmt::Debug for OperandValue<V> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            OperandValue::Ref(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Ref",
                    &__self_0),
            OperandValue::Immediate(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Immediate", &__self_0),
            OperandValue::Pair(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f, "Pair",
                    __self_0, &__self_1),
            OperandValue::ZeroSized =>
                ::core::fmt::Formatter::write_str(f, "ZeroSized"),
        }
    }
}Debug)]
28pub enum OperandValue<V> {
29    /// A reference to the actual operand. The data is guaranteed
30    /// to be valid for the operand's lifetime.
31    /// The second value, if any, is the extra data (vtable or length)
32    /// which indicates that it refers to an unsized rvalue.
33    ///
34    /// An `OperandValue` *must* be this variant for any type for which
35    /// [`LayoutTypeCodegenMethods::is_backend_ref`] returns `true`.
36    /// (That basically amounts to "isn't one of the other variants".)
37    ///
38    /// This holds a [`PlaceValue`] (like a [`PlaceRef`] does) with a pointer
39    /// to the location holding the value. The type behind that pointer is the
40    /// one returned by [`LayoutTypeCodegenMethods::backend_type`].
41    Ref(PlaceValue<V>),
42    /// A single LLVM immediate value.
43    ///
44    /// An `OperandValue` *must* be this variant for any type for which
45    /// [`LayoutTypeCodegenMethods::is_backend_immediate`] returns `true`.
46    /// The backend value in this variant must be the *immediate* backend type,
47    /// as returned by [`LayoutTypeCodegenMethods::immediate_backend_type`].
48    Immediate(V),
49    /// A pair of immediate LLVM values. Used by wide pointers too.
50    ///
51    /// # Invariants
52    /// - For `Pair(a, b)`, `a` is always at offset 0, but may have `FieldIdx(1..)`
53    /// - `b` is not at offset 0, because `V` is not a 1ZST type.
54    /// - `a` and `b` will have a different FieldIdx, but otherwise `b`'s may be lower
55    ///   or they may not be adjacent, due to arbitrary numbers of 1ZST fields that
56    ///   will not affect the shape of the data which determines if `Pair` will be used.
57    /// - An `OperandValue` *must* be this variant for any type for which
58    /// [`LayoutTypeCodegenMethods::is_backend_scalar_pair`] returns `true`.
59    /// - The backend values in this variant must be the *immediate* backend types,
60    /// as returned by [`LayoutTypeCodegenMethods::scalar_pair_element_backend_type`]
61    /// with `immediate: true`.
62    Pair(V, V),
63    /// A value taking no bytes, and which therefore needs no LLVM value at all.
64    ///
65    /// If you ever need a `V` to pass to something, get a fresh poison value
66    /// from [`ConstCodegenMethods::const_poison`].
67    ///
68    /// An `OperandValue` *must* be this variant for any type for which
69    /// `is_zst` on its `Layout` returns `true`. Note however that
70    /// these values can still require alignment.
71    ZeroSized,
72}
73
74impl<V: CodegenObject> OperandValue<V> {
75    /// Return the data pointer and optional metadata as backend values
76    /// if this value can be treat as a pointer.
77    pub(crate) fn try_pointer_parts(self) -> Option<(V, Option<V>)> {
78        match self {
79            OperandValue::Immediate(llptr) => Some((llptr, None)),
80            OperandValue::Pair(llptr, llextra) => Some((llptr, Some(llextra))),
81            OperandValue::Ref(_) | OperandValue::ZeroSized => None,
82        }
83    }
84
85    /// Treat this value as a pointer and return the data pointer and
86    /// optional metadata as backend values.
87    ///
88    /// If you're making a place, use [`Self::deref`] instead.
89    pub(crate) fn pointer_parts(self) -> (V, Option<V>) {
90        self.try_pointer_parts()
91            .unwrap_or_else(|| ::rustc_middle::util::bug::bug_fmt(format_args!("OperandValue cannot be a pointer: {0:?}",
        self))bug!("OperandValue cannot be a pointer: {self:?}"))
92    }
93
94    /// Treat this value as a pointer and return the place to which it points.
95    ///
96    /// The pointer immediate doesn't inherently know its alignment,
97    /// so you need to pass it in. If you want to get it from a type's ABI
98    /// alignment, then maybe you want [`OperandRef::deref`] instead.
99    ///
100    /// This is the inverse of [`PlaceValue::address`].
101    pub(crate) fn deref(self, align: Align) -> PlaceValue<V> {
102        let (llval, llextra) = self.pointer_parts();
103        PlaceValue { llval, llextra, align }
104    }
105
106    #[must_use]
107    pub(crate) fn is_expected_variant_for_type<'tcx, Cx: LayoutTypeCodegenMethods<'tcx>>(
108        &self,
109        cx: &Cx,
110        ty: TyAndLayout<'tcx>,
111    ) -> bool {
112        match self {
113            OperandValue::ZeroSized => ty.is_zst(),
114            OperandValue::Immediate(_) => cx.is_backend_immediate(ty),
115            OperandValue::Pair(_, _) => cx.is_backend_scalar_pair(ty),
116            OperandValue::Ref(_) => cx.is_backend_ref(ty),
117        }
118    }
119}
120
121/// An `OperandRef` is an "SSA" reference to a Rust value, along with
122/// its type.
123///
124/// NOTE: unless you know a value's type exactly, you should not
125/// generate LLVM opcodes acting on it and instead act via methods,
126/// to avoid nasty edge cases. In particular, using `Builder::store`
127/// directly is sure to cause problems -- use `OperandRef::store`
128/// instead.
129#[derive(#[automatically_derived]
impl<'tcx, V: ::core::marker::Copy> ::core::marker::Copy for
    OperandRef<'tcx, V> {
}Copy, #[automatically_derived]
impl<'tcx, V: ::core::clone::Clone> ::core::clone::Clone for
    OperandRef<'tcx, V> {
    #[inline]
    fn clone(&self) -> OperandRef<'tcx, V> {
        OperandRef {
            val: ::core::clone::Clone::clone(&self.val),
            layout: ::core::clone::Clone::clone(&self.layout),
            move_annotation: ::core::clone::Clone::clone(&self.move_annotation),
        }
    }
}Clone)]
130pub struct OperandRef<'tcx, V> {
131    /// The value.
132    pub val: OperandValue<V>,
133
134    /// The layout of value, based on its Rust type.
135    pub layout: TyAndLayout<'tcx>,
136
137    /// Annotation for profiler visibility of move/copy operations.
138    /// When set, the store operation should appear as an inlined call to this function.
139    pub move_annotation: Option<ty::Instance<'tcx>>,
140}
141
142impl<V: CodegenObject> fmt::Debug for OperandRef<'_, V> {
143    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
144        f.write_fmt(format_args!("OperandRef({0:?} @ {1:?})", self.val, self.layout))write!(f, "OperandRef({:?} @ {:?})", self.val, self.layout)
145    }
146}
147
148impl<'a, 'tcx, V: CodegenObject> OperandRef<'tcx, V> {
149    pub fn zero_sized(layout: TyAndLayout<'tcx>) -> OperandRef<'tcx, V> {
150        if !layout.is_zst() {
    ::core::panicking::panic("assertion failed: layout.is_zst()")
};assert!(layout.is_zst());
151        OperandRef { val: OperandValue::ZeroSized, layout, move_annotation: None }
152    }
153
154    pub(crate) fn from_const<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
155        bx: &mut Bx,
156        val: mir::ConstValue,
157        ty: Ty<'tcx>,
158    ) -> Self {
159        let layout = bx.layout_of(ty);
160
161        let val = match val {
162            ConstValue::Scalar(x) => {
163                let BackendRepr::Scalar(scalar) = layout.backend_repr else {
164                    ::rustc_middle::util::bug::bug_fmt(format_args!("from_const: invalid ByVal layout: {0:#?}",
        layout));bug!("from_const: invalid ByVal layout: {:#?}", layout);
165                };
166                let llval = bx.scalar_to_backend(x, scalar, bx.immediate_backend_type(layout));
167                OperandValue::Immediate(llval)
168            }
169            ConstValue::ZeroSized => return OperandRef::zero_sized(layout),
170            ConstValue::Slice { alloc_id, meta } => {
171                let BackendRepr::ScalarPair { a: a_scalar, b: _, b_offset: _ } =
172                    layout.backend_repr
173                else {
174                    ::rustc_middle::util::bug::bug_fmt(format_args!("from_const: invalid ScalarPair layout: {0:#?}",
        layout));bug!("from_const: invalid ScalarPair layout: {:#?}", layout);
175                };
176                let a = Scalar::from_pointer(Pointer::new(alloc_id.into(), Size::ZERO), &bx.tcx());
177                let a_llval = bx.scalar_to_backend(
178                    a,
179                    a_scalar,
180                    bx.scalar_pair_element_backend_type(layout, 0, true),
181                );
182                let b_llval = bx.const_usize(meta);
183                OperandValue::Pair(a_llval, b_llval)
184            }
185            ConstValue::Indirect { alloc_id, offset } => {
186                let alloc = bx.tcx().global_alloc(alloc_id).unwrap_memory();
187                return Self::from_const_alloc(bx, layout, alloc, offset);
188            }
189        };
190
191        OperandRef { val, layout, move_annotation: None }
192    }
193
194    fn from_const_alloc<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
195        bx: &mut Bx,
196        layout: TyAndLayout<'tcx>,
197        alloc: rustc_middle::mir::interpret::ConstAllocation<'tcx>,
198        offset: Size,
199    ) -> Self {
200        let alloc_align = alloc.inner().align;
201        if !(alloc_align >= layout.align.abi) {
    {
        ::core::panicking::panic_fmt(format_args!("{1:?} < {0:?}",
                layout.align.abi, alloc_align));
    }
};assert!(alloc_align >= layout.align.abi, "{alloc_align:?} < {:?}", layout.align.abi);
202
203        let read_scalar = |start, size, s: abi::Scalar, ty| {
204            match alloc.0.read_scalar(
205                bx,
206                alloc_range(start, size),
207                /*read_provenance*/ #[allow(non_exhaustive_omitted_patterns)] match s.primitive() {
    abi::Primitive::Pointer(_) => true,
    _ => false,
}matches!(s.primitive(), abi::Primitive::Pointer(_)),
208            ) {
209                Ok(val) => bx.scalar_to_backend(val, s, ty),
210                Err(_) => bx.const_poison(ty),
211            }
212        };
213
214        // It may seem like all types with `Scalar` or `ScalarPair` ABI are fair game at this point.
215        // However, `MaybeUninit<u64>` is considered a `Scalar` as far as its layout is concerned --
216        // and yet cannot be represented by an interpreter `Scalar`, since we have to handle the
217        // case where some of the bytes are initialized and others are not. So, we need an extra
218        // check that walks over the type of `mplace` to make sure it is truly correct to treat this
219        // like a `Scalar` (or `ScalarPair`).
220        match layout.backend_repr {
221            BackendRepr::Scalar(s @ abi::Scalar::Initialized { .. }) => {
222                let size = s.size(bx);
223                {
    match (&size, &layout.size) {
        (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::Some(format_args!("abi::Scalar size does not match layout size")));
            }
        }
    }
};assert_eq!(size, layout.size, "abi::Scalar size does not match layout size");
224                let val = read_scalar(offset, size, s, bx.immediate_backend_type(layout));
225                OperandRef { val: OperandValue::Immediate(val), layout, move_annotation: None }
226            }
227            BackendRepr::ScalarPair {
228                a: a @ abi::Scalar::Initialized { .. },
229                b: b @ abi::Scalar::Initialized { .. },
230                b_offset,
231            } => {
232                let (a_size, b_size) = (a.size(bx), b.size(bx));
233                if !(b_offset.bytes() > 0) {
    ::core::panicking::panic("assertion failed: b_offset.bytes() > 0")
};assert!(b_offset.bytes() > 0);
234                let a_val = read_scalar(
235                    offset,
236                    a_size,
237                    a,
238                    bx.scalar_pair_element_backend_type(layout, 0, true),
239                );
240                let b_val = read_scalar(
241                    b_offset,
242                    b_size,
243                    b,
244                    bx.scalar_pair_element_backend_type(layout, 1, true),
245                );
246                OperandRef { val: OperandValue::Pair(a_val, b_val), layout, move_annotation: None }
247            }
248            _ if layout.is_zst() => OperandRef::zero_sized(layout),
249            _ => {
250                // Neither a scalar nor scalar pair. Load from a place
251                let base_addr = bx.static_addr_of(alloc, None);
252
253                let llval = bx.const_ptr_byte_offset(base_addr, offset);
254                bx.load_operand(PlaceRef::new_sized(llval, layout))
255            }
256        }
257    }
258
259    /// Asserts that this operand refers to a scalar and returns
260    /// a reference to its value.
261    pub fn immediate(self) -> V {
262        match self.val {
263            OperandValue::Immediate(s) => s,
264            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("not immediate: {0:?}", self))bug!("not immediate: {:?}", self),
265        }
266    }
267
268    /// Asserts that this operand is a pointer (or reference) and returns
269    /// the place to which it points.  (This requires no code to be emitted
270    /// as we represent places using the pointer to the place.)
271    ///
272    /// This uses [`Ty::builtin_deref`] to include the type of the place and
273    /// assumes the place is aligned to the pointee's usual ABI alignment.
274    ///
275    /// If you don't need the type, see [`OperandValue::pointer_parts`]
276    /// or [`OperandValue::deref`].
277    pub fn deref<Cx: CodegenMethods<'tcx>>(self, cx: &Cx) -> PlaceRef<'tcx, V> {
278        if self.layout.ty.is_box() {
279            // Derefer should have removed all Box derefs
280            ::rustc_middle::util::bug::bug_fmt(format_args!("dereferencing {0:?} in codegen",
        self.layout.ty));bug!("dereferencing {:?} in codegen", self.layout.ty);
281        }
282
283        let projected_ty = self
284            .layout
285            .ty
286            .builtin_deref(true)
287            .unwrap_or_else(|| ::rustc_middle::util::bug::bug_fmt(format_args!("deref of non-pointer {0:?}",
        self))bug!("deref of non-pointer {:?}", self));
288
289        let layout = cx.layout_of(projected_ty);
290        self.val.deref(layout.align.abi).with_type(layout)
291    }
292
293    /// Store this operand into a place, applying move/copy annotation if present.
294    ///
295    /// This is the preferred method for storing operands, as it automatically
296    /// applies profiler annotations for tracked move/copy operations.
297    pub fn store_with_annotation<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
298        self,
299        bx: &mut Bx,
300        dest: PlaceRef<'tcx, V>,
301    ) {
302        self.store_with_annotation_and_flags(bx, dest, MemFlags::empty())
303    }
304
305    /// Same as store_with_annotation(), but also specify flags for the store.
306    pub fn store_with_annotation_and_flags<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
307        self,
308        bx: &mut Bx,
309        dest: PlaceRef<'tcx, V>,
310        flags: MemFlags,
311    ) {
312        if let Some(instance) = self.move_annotation {
313            bx.with_move_annotation(instance, |bx| self.val.store_with_flags(bx, dest, flags))
314        } else {
315            self.val.store_with_flags(bx, dest, flags)
316        }
317    }
318
319    /// If this operand is a `Pair`, we return an aggregate with the two values.
320    /// For other cases, see `immediate`.
321    ///
322    /// Note: The use of this is discouraged outside cg_llvm, as some other backends
323    /// don't natively support packing multiple things into one like this.
324    pub fn immediate_or_packed_pair<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
325        self,
326        bx: &mut Bx,
327    ) -> V {
328        if let OperandValue::Pair(a, b) = self.val {
329            let llty = bx.cx().immediate_backend_type(self.layout);
330            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/operand.rs:330",
                        "rustc_codegen_ssa::mir::operand", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/operand.rs"),
                        ::tracing_core::__macro_support::Option::Some(330u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::operand"),
                        ::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!("Operand::immediate_or_packed_pair: packing {0:?} into {1:?}",
                                                    self, llty) as &dyn Value))])
            });
    } else { ; }
};debug!("Operand::immediate_or_packed_pair: packing {:?} into {:?}", self, llty);
331            // Reconstruct the immediate aggregate.
332            let mut llpair = bx.cx().const_poison(llty);
333            llpair = bx.insert_value(llpair, a, 0);
334            llpair = bx.insert_value(llpair, b, 1);
335            llpair
336        } else {
337            self.immediate()
338        }
339    }
340
341    /// If the type is a pair, we return a `Pair`, otherwise, an `Immediate`.
342    ///
343    /// Note: The use of this is discouraged outside cg_llvm, as some other backends
344    /// don't natively support packing multiple things into one like this.
345    pub fn from_immediate_or_packed_pair<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
346        bx: &mut Bx,
347        llval: V,
348        layout: TyAndLayout<'tcx>,
349    ) -> Self {
350        let val = if let BackendRepr::ScalarPair { .. } = layout.backend_repr {
351            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/operand.rs:351",
                        "rustc_codegen_ssa::mir::operand", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/operand.rs"),
                        ::tracing_core::__macro_support::Option::Some(351u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::operand"),
                        ::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!("Operand::from_immediate_or_packed_pair: unpacking {0:?} @ {1:?}",
                                                    llval, layout) as &dyn Value))])
            });
    } else { ; }
};debug!("Operand::from_immediate_or_packed_pair: unpacking {:?} @ {:?}", llval, layout);
352
353            // Deconstruct the immediate aggregate.
354            let a_llval = bx.extract_value(llval, 0);
355            let b_llval = bx.extract_value(llval, 1);
356            OperandValue::Pair(a_llval, b_llval)
357        } else {
358            OperandValue::Immediate(llval)
359        };
360        OperandRef { val, layout, move_annotation: None }
361    }
362
363    pub(crate) fn extract_field<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
364        &self,
365        fx: &mut FunctionCx<'a, 'tcx, Bx>,
366        bx: &mut Bx,
367        i: usize,
368    ) -> Self {
369        let field = self.layout.field(bx.cx(), i);
370        let offset = self.layout.fields.offset(i);
371
372        if !bx.is_backend_ref(self.layout) && bx.is_backend_ref(field) {
373            // Part of https://github.com/rust-lang/compiler-team/issues/838
374            ::rustc_middle::util::bug::span_bug_fmt(fx.mir.span,
    format_args!("Non-ref type {0:?} cannot project to ref field type {1:?}",
        self, field));span_bug!(
375                fx.mir.span,
376                "Non-ref type {self:?} cannot project to ref field type {field:?}",
377            );
378        }
379
380        let val = if field.is_zst() {
381            OperandValue::ZeroSized
382        } else if field.size == self.layout.size {
383            {
    match (&offset.bytes(), &0) {
        (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!(offset.bytes(), 0);
384            fx.codegen_transmute_operand(bx, *self, field)
385        } else {
386            let (in_scalar, imm) = match (self.val, self.layout.backend_repr) {
387                // Extract a scalar component from a pair.
388                (
389                    OperandValue::Pair(a_llval, b_llval),
390                    BackendRepr::ScalarPair { a, b, b_offset },
391                ) => {
392                    if offset.bytes() == 0 {
393                        {
    match (&field.size, &a.size(bx.cx())) {
        (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!(field.size, a.size(bx.cx()));
394                        (Some(a), a_llval)
395                    } else {
396                        {
    match (&offset, &b_offset) {
        (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!(offset, b_offset);
397                        {
    match (&field.size, &b.size(bx.cx())) {
        (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!(field.size, b.size(bx.cx()));
398                        (Some(b), b_llval)
399                    }
400                }
401
402                _ => {
403                    ::rustc_middle::util::bug::span_bug_fmt(fx.mir.span,
    format_args!("OperandRef::extract_field({0:?}): not applicable", self))span_bug!(fx.mir.span, "OperandRef::extract_field({:?}): not applicable", self)
404                }
405            };
406            OperandValue::Immediate(match field.backend_repr {
407                BackendRepr::SimdVector { .. } => imm,
408                BackendRepr::Scalar(out_scalar) => {
409                    let Some(in_scalar) = in_scalar else {
410                        ::rustc_middle::util::bug::span_bug_fmt(fx.mir.span,
    format_args!("OperandRef::extract_field({0:?}): missing input scalar for output scalar",
        self))span_bug!(
411                            fx.mir.span,
412                            "OperandRef::extract_field({:?}): missing input scalar for output scalar",
413                            self
414                        )
415                    };
416                    if in_scalar != out_scalar {
417                        // If the backend and backend_immediate types might differ,
418                        // flip back to the backend type then to the new immediate.
419                        // This avoids nop truncations, but still handles things like
420                        // Bools in union fields needs to be truncated.
421                        let backend = bx.from_immediate(imm);
422                        bx.to_immediate_scalar(backend, out_scalar)
423                    } else {
424                        imm
425                    }
426                }
427                BackendRepr::ScalarPair { a: _, b: _, b_offset: _ }
428                | BackendRepr::Memory { .. }
429                | BackendRepr::SimdScalableVector { .. } => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
430            })
431        };
432
433        OperandRef { val, layout: field, move_annotation: None }
434    }
435
436    /// Obtain the actual discriminant of a value.
437    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("codegen_get_discr",
                                    "rustc_codegen_ssa::mir::operand", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/operand.rs"),
                                    ::tracing_core::__macro_support::Option::Some(437u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::operand"),
                                    ::tracing_core::field::FieldSet::new(&["self", "cast_to"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&self)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cast_to)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: V = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let dl = &bx.tcx().data_layout;
            let cast_to_layout = bx.cx().layout_of(cast_to);
            let cast_to = bx.cx().immediate_backend_type(cast_to_layout);
            if self.layout.is_uninhabited() {
                return bx.cx().const_poison(cast_to);
            }
            let (tag_scalar, tag_encoding, tag_field) =
                match self.layout.variants {
                    Variants::Empty => {
                        ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
                                format_args!("we already handled uninhabited types")));
                    }
                    Variants::Single { index } => {
                        let discr_val =
                            if let Some(discr) =
                                    self.layout.ty.discriminant_for_variant(bx.tcx(), index) {
                                discr.val
                            } else {
                                {
                                    match (&index, &FIRST_VARIANT) {
                                        (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);
                                            }
                                        }
                                    }
                                };
                                0
                            };
                        return bx.cx().const_uint_big(cast_to, discr_val);
                    }
                    Variants::Multiple { tag, ref tag_encoding, tag_field, .. }
                        => {
                        (tag, tag_encoding, tag_field)
                    }
                };
            let tag_op =
                match self.val {
                    OperandValue::ZeroSized =>
                        ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached")),
                    OperandValue::Immediate(_) | OperandValue::Pair(_, _) => {
                        self.extract_field(fx, bx, tag_field.as_usize())
                    }
                    OperandValue::Ref(place) => {
                        let tag =
                            place.with_type(self.layout).project_field(bx,
                                tag_field.as_usize());
                        bx.load_operand(tag)
                    }
                };
            let tag_imm = tag_op.immediate();
            match *tag_encoding {
                TagEncoding::Direct => {
                    let signed =
                        match tag_scalar.primitive() {
                            Primitive::Int(_, signed) =>
                                !tag_scalar.is_bool() && signed,
                            _ => false,
                        };
                    bx.intcast(tag_imm, cast_to, signed)
                }
                TagEncoding::Niche {
                    untagged_variant, ref niche_variants, niche_start } => {
                    let (tag, tag_llty) =
                        match tag_scalar.primitive() {
                            Primitive::Pointer(_) => {
                                let t = bx.type_from_integer(dl.ptr_sized_integer());
                                let tag = bx.ptrtoint(tag_imm, t);
                                (tag, t)
                            }
                            _ =>
                                (tag_imm, bx.cx().immediate_backend_type(tag_op.layout)),
                        };
                    let relative_max =
                        niche_variants.last.as_u32() -
                            niche_variants.start.as_u32();
                    let niche_start_const =
                        bx.cx().const_uint_big(tag_llty, niche_start);
                    let (is_niche, tagged_discr, delta) =
                        if relative_max == 0 {
                            let is_niche =
                                bx.icmp(IntPredicate::IntEQ, tag, niche_start_const);
                            let tagged_discr =
                                bx.cx().const_uint(cast_to,
                                    niche_variants.start.as_u32() as u64);
                            (is_niche, tagged_discr, 0)
                        } else {
                            if niche_variants.contains(&untagged_variant) &&
                                    bx.cx().sess().opts.optimize != OptLevel::No {
                                let impossible =
                                    niche_start.wrapping_add(u128::from(untagged_variant.as_u32())).wrapping_sub(u128::from(niche_variants.start.as_u32()));
                                let impossible =
                                    bx.cx().const_uint_big(tag_llty, impossible);
                                let ne = bx.icmp(IntPredicate::IntNE, tag, impossible);
                                bx.assume(ne);
                            }
                            let tag_range = tag_scalar.valid_range(&dl);
                            let tag_size = tag_scalar.size(&dl);
                            let niche_end =
                                u128::from(relative_max).wrapping_add(niche_start);
                            let niche_end = tag_size.truncate(niche_end);
                            let relative_discr = bx.sub(tag, niche_start_const);
                            let cast_tag = bx.intcast(relative_discr, cast_to, false);
                            let is_niche =
                                if tag_range.no_unsigned_wraparound(tag_size) == Ok(true) {
                                    if niche_start == tag_range.start {
                                        let niche_end_const =
                                            bx.cx().const_uint_big(tag_llty, niche_end);
                                        bx.icmp(IntPredicate::IntULE, tag, niche_end_const)
                                    } else {
                                        {
                                            match (&niche_end, &tag_range.end) {
                                                (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);
                                                    }
                                                }
                                            }
                                        };
                                        bx.icmp(IntPredicate::IntUGE, tag, niche_start_const)
                                    }
                                } else if tag_range.no_signed_wraparound(tag_size) ==
                                        Ok(true) {
                                    if niche_start == tag_range.start {
                                        let niche_end_const =
                                            bx.cx().const_uint_big(tag_llty, niche_end);
                                        bx.icmp(IntPredicate::IntSLE, tag, niche_end_const)
                                    } else {
                                        {
                                            match (&niche_end, &tag_range.end) {
                                                (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);
                                                    }
                                                }
                                            }
                                        };
                                        bx.icmp(IntPredicate::IntSGE, tag, niche_start_const)
                                    }
                                } else {
                                    bx.icmp(IntPredicate::IntULE, relative_discr,
                                        bx.cx().const_uint(tag_llty, relative_max as u64))
                                };
                            (is_niche, cast_tag, niche_variants.start.as_u32() as u128)
                        };
                    let tagged_discr =
                        if delta == 0 {
                            tagged_discr
                        } else {
                            bx.add(tagged_discr, bx.cx().const_uint_big(cast_to, delta))
                        };
                    let untagged_variant_const =
                        bx.cx().const_uint(cast_to,
                            u64::from(untagged_variant.as_u32()));
                    let discr =
                        bx.select(is_niche, tagged_discr, untagged_variant_const);
                    discr
                }
            }
        }
    }
}#[instrument(level = "trace", skip(fx, bx))]
438    pub fn codegen_get_discr<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
439        self,
440        fx: &mut FunctionCx<'a, 'tcx, Bx>,
441        bx: &mut Bx,
442        cast_to: Ty<'tcx>,
443    ) -> V {
444        let dl = &bx.tcx().data_layout;
445        let cast_to_layout = bx.cx().layout_of(cast_to);
446        let cast_to = bx.cx().immediate_backend_type(cast_to_layout);
447
448        // We check uninhabitedness separately because a type like
449        // `enum Foo { Bar(i32, !) }` is still reported as `Variants::Single`,
450        // *not* as `Variants::Empty`.
451        if self.layout.is_uninhabited() {
452            return bx.cx().const_poison(cast_to);
453        }
454
455        let (tag_scalar, tag_encoding, tag_field) = match self.layout.variants {
456            Variants::Empty => unreachable!("we already handled uninhabited types"),
457            Variants::Single { index } => {
458                let discr_val =
459                    if let Some(discr) = self.layout.ty.discriminant_for_variant(bx.tcx(), index) {
460                        discr.val
461                    } else {
462                        // This arm is for types which are neither enums nor coroutines,
463                        // and thus for which the only possible "variant" should be the first one.
464                        assert_eq!(index, FIRST_VARIANT);
465                        // There's thus no actual discriminant to return, so we return
466                        // what it would have been if this was a single-variant enum.
467                        0
468                    };
469                return bx.cx().const_uint_big(cast_to, discr_val);
470            }
471            Variants::Multiple { tag, ref tag_encoding, tag_field, .. } => {
472                (tag, tag_encoding, tag_field)
473            }
474        };
475
476        // Read the tag/niche-encoded discriminant from memory.
477        let tag_op = match self.val {
478            OperandValue::ZeroSized => bug!(),
479            OperandValue::Immediate(_) | OperandValue::Pair(_, _) => {
480                self.extract_field(fx, bx, tag_field.as_usize())
481            }
482            OperandValue::Ref(place) => {
483                let tag = place.with_type(self.layout).project_field(bx, tag_field.as_usize());
484                bx.load_operand(tag)
485            }
486        };
487        let tag_imm = tag_op.immediate();
488
489        // Decode the discriminant (specifically if it's niche-encoded).
490        match *tag_encoding {
491            TagEncoding::Direct => {
492                let signed = match tag_scalar.primitive() {
493                    // We use `i1` for bytes that are always `0` or `1`,
494                    // e.g., `#[repr(i8)] enum E { A, B }`, but we can't
495                    // let LLVM interpret the `i1` as signed, because
496                    // then `i1 1` (i.e., `E::B`) is effectively `i8 -1`.
497                    Primitive::Int(_, signed) => !tag_scalar.is_bool() && signed,
498                    _ => false,
499                };
500                bx.intcast(tag_imm, cast_to, signed)
501            }
502            TagEncoding::Niche { untagged_variant, ref niche_variants, niche_start } => {
503                // Cast to an integer so we don't have to treat a pointer as a
504                // special case.
505                let (tag, tag_llty) = match tag_scalar.primitive() {
506                    // FIXME(erikdesjardins): handle non-default addrspace ptr sizes
507                    Primitive::Pointer(_) => {
508                        let t = bx.type_from_integer(dl.ptr_sized_integer());
509                        let tag = bx.ptrtoint(tag_imm, t);
510                        (tag, t)
511                    }
512                    _ => (tag_imm, bx.cx().immediate_backend_type(tag_op.layout)),
513                };
514
515                // `layout_sanity_check` ensures that we only get here for cases where the discriminant
516                // value and the variant index match, since that's all `Niche` can encode.
517
518                let relative_max = niche_variants.last.as_u32() - niche_variants.start.as_u32();
519                let niche_start_const = bx.cx().const_uint_big(tag_llty, niche_start);
520
521                // We have a subrange `niche_start..=niche_end` inside `range`.
522                // If the value of the tag is inside this subrange, it's a
523                // "niche value", an increment of the discriminant. Otherwise it
524                // indicates the untagged variant.
525                // A general algorithm to extract the discriminant from the tag
526                // is:
527                // relative_tag = tag - niche_start
528                // is_niche = relative_tag <= (ule) relative_max
529                // discr = if is_niche {
530                //     cast(relative_tag) + niche_variants.start()
531                // } else {
532                //     untagged_variant
533                // }
534                // However, we will likely be able to emit simpler code.
535                let (is_niche, tagged_discr, delta) = if relative_max == 0 {
536                    // Best case scenario: only one tagged variant. This will
537                    // likely become just a comparison and a jump.
538                    // The algorithm is:
539                    // is_niche = tag == niche_start
540                    // discr = if is_niche {
541                    //     niche_start
542                    // } else {
543                    //     untagged_variant
544                    // }
545                    let is_niche = bx.icmp(IntPredicate::IntEQ, tag, niche_start_const);
546                    let tagged_discr =
547                        bx.cx().const_uint(cast_to, niche_variants.start.as_u32() as u64);
548                    (is_niche, tagged_discr, 0)
549                } else {
550                    // Thanks to parameter attributes and load metadata, LLVM already knows
551                    // the general valid range of the tag. It's possible, though, for there
552                    // to be an impossible value *in the middle*, which those ranges don't
553                    // communicate, so it's worth an `assume` to let the optimizer know.
554                    // Most importantly, this means when optimizing a variant test like
555                    // `SELECT(is_niche, complex, CONST) == CONST` it's ok to simplify that
556                    // to `!is_niche` because the `complex` part can't possibly match.
557                    //
558                    // This was previously asserted on `tagged_discr` below, where the
559                    // impossible value is more obvious, but that caused an intermediate
560                    // value to become multi-use and thus not optimize, so instead this
561                    // assumes on the original input which is always multi-use. See
562                    // <https://github.com/llvm/llvm-project/issues/134024#issuecomment-3131782555>
563                    //
564                    // FIXME: If we ever get range assume operand bundles in LLVM (so we
565                    // don't need the `icmp`s in the instruction stream any more), it
566                    // might be worth moving this back to being on the switch argument
567                    // where it's more obviously applicable.
568                    if niche_variants.contains(&untagged_variant)
569                        && bx.cx().sess().opts.optimize != OptLevel::No
570                    {
571                        let impossible = niche_start
572                            .wrapping_add(u128::from(untagged_variant.as_u32()))
573                            .wrapping_sub(u128::from(niche_variants.start.as_u32()));
574                        let impossible = bx.cx().const_uint_big(tag_llty, impossible);
575                        let ne = bx.icmp(IntPredicate::IntNE, tag, impossible);
576                        bx.assume(ne);
577                    }
578
579                    // With multiple niched variants we'll have to actually compute
580                    // the variant index from the stored tag.
581                    //
582                    // However, there's still one small optimization we can often do for
583                    // determining *whether* a tag value is a natural value or a niched
584                    // variant. The general algorithm involves a subtraction that often
585                    // wraps in practice, making it tricky to analyse. However, in cases
586                    // where there are few enough possible values of the tag that it doesn't
587                    // need to wrap around, we can instead just look for the contiguous
588                    // tag values on the end of the range with a single comparison.
589                    //
590                    // For example, take the type `enum Demo { A, B, Untagged(bool) }`.
591                    // The `bool` is {0, 1}, and the two other variants are given the
592                    // tags {2, 3} respectively. That means the `tag_range` is
593                    // `[0, 3]`, which doesn't wrap as unsigned (nor as signed), so
594                    // we can test for the niched variants with just `>= 2`.
595                    //
596                    // That means we're looking either for the niche values *above*
597                    // the natural values of the untagged variant:
598                    //
599                    //             niche_start                  niche_end
600                    //                  |                           |
601                    //                  v                           v
602                    // MIN -------------+---------------------------+---------- MAX
603                    //         ^        |         is niche          |
604                    //         |        +---------------------------+
605                    //         |                                    |
606                    //   tag_range.start                      tag_range.end
607                    //
608                    // Or *below* the natural values:
609                    //
610                    //    niche_start              niche_end
611                    //         |                       |
612                    //         v                       v
613                    // MIN ----+-----------------------+---------------------- MAX
614                    //         |       is niche        |           ^
615                    //         +-----------------------+           |
616                    //         |                                   |
617                    //   tag_range.start                      tag_range.end
618                    //
619                    // With those two options and having the flexibility to choose
620                    // between a signed or unsigned comparison on the tag, that
621                    // covers most realistic scenarios. The tests have a (contrived)
622                    // example of a 1-byte enum with over 128 niched variants which
623                    // wraps both as signed as unsigned, though, and for something
624                    // like that we're stuck with the general algorithm.
625
626                    let tag_range = tag_scalar.valid_range(&dl);
627                    let tag_size = tag_scalar.size(&dl);
628                    let niche_end = u128::from(relative_max).wrapping_add(niche_start);
629                    let niche_end = tag_size.truncate(niche_end);
630
631                    let relative_discr = bx.sub(tag, niche_start_const);
632                    let cast_tag = bx.intcast(relative_discr, cast_to, false);
633                    let is_niche = if tag_range.no_unsigned_wraparound(tag_size) == Ok(true) {
634                        if niche_start == tag_range.start {
635                            let niche_end_const = bx.cx().const_uint_big(tag_llty, niche_end);
636                            bx.icmp(IntPredicate::IntULE, tag, niche_end_const)
637                        } else {
638                            assert_eq!(niche_end, tag_range.end);
639                            bx.icmp(IntPredicate::IntUGE, tag, niche_start_const)
640                        }
641                    } else if tag_range.no_signed_wraparound(tag_size) == Ok(true) {
642                        if niche_start == tag_range.start {
643                            let niche_end_const = bx.cx().const_uint_big(tag_llty, niche_end);
644                            bx.icmp(IntPredicate::IntSLE, tag, niche_end_const)
645                        } else {
646                            assert_eq!(niche_end, tag_range.end);
647                            bx.icmp(IntPredicate::IntSGE, tag, niche_start_const)
648                        }
649                    } else {
650                        bx.icmp(
651                            IntPredicate::IntULE,
652                            relative_discr,
653                            bx.cx().const_uint(tag_llty, relative_max as u64),
654                        )
655                    };
656
657                    (is_niche, cast_tag, niche_variants.start.as_u32() as u128)
658                };
659
660                let tagged_discr = if delta == 0 {
661                    tagged_discr
662                } else {
663                    bx.add(tagged_discr, bx.cx().const_uint_big(cast_to, delta))
664                };
665
666                let untagged_variant_const =
667                    bx.cx().const_uint(cast_to, u64::from(untagged_variant.as_u32()));
668
669                let discr = bx.select(is_niche, tagged_discr, untagged_variant_const);
670
671                // In principle we could insert assumes on the possible range of `discr`, but
672                // currently in LLVM this isn't worth it because the original `tag` will
673                // have either a `range` parameter attribute or `!range` metadata,
674                // or come from a `transmute` that already `assume`d it.
675
676                discr
677            }
678        }
679    }
680}
681
682/// Each of these variants starts out as `Either::Right` when it's uninitialized,
683/// then setting the field changes that to `Either::Left` with the backend value.
684#[derive(#[automatically_derived]
impl<V: ::core::fmt::Debug> ::core::fmt::Debug for OperandValueBuilder<V> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            OperandValueBuilder::ZeroSized =>
                ::core::fmt::Formatter::write_str(f, "ZeroSized"),
            OperandValueBuilder::Immediate(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Immediate", &__self_0),
            OperandValueBuilder::Pair(__self_0, __self_1) =>
                ::core::fmt::Formatter::debug_tuple_field2_finish(f, "Pair",
                    __self_0, &__self_1),
            OperandValueBuilder::Vector(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Vector",
                    &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl<V: ::core::marker::Copy> ::core::marker::Copy for OperandValueBuilder<V>
    {
}Copy, #[automatically_derived]
impl<V: ::core::clone::Clone> ::core::clone::Clone for OperandValueBuilder<V>
    {
    #[inline]
    fn clone(&self) -> OperandValueBuilder<V> {
        match self {
            OperandValueBuilder::ZeroSized => OperandValueBuilder::ZeroSized,
            OperandValueBuilder::Immediate(__self_0) =>
                OperandValueBuilder::Immediate(::core::clone::Clone::clone(__self_0)),
            OperandValueBuilder::Pair(__self_0, __self_1) =>
                OperandValueBuilder::Pair(::core::clone::Clone::clone(__self_0),
                    ::core::clone::Clone::clone(__self_1)),
            OperandValueBuilder::Vector(__self_0) =>
                OperandValueBuilder::Vector(::core::clone::Clone::clone(__self_0)),
        }
    }
}Clone)]
685enum OperandValueBuilder<V> {
686    ZeroSized,
687    Immediate(Either<V, abi::Scalar>),
688    Pair(Either<V, abi::Scalar>, Either<V, abi::Scalar>),
689    /// `repr(simd)` types need special handling because they each have a non-empty
690    /// array field (which uses [`OperandValue::Ref`]) despite the SIMD type itself
691    /// using [`OperandValue::Immediate`] which for any other kind of type would
692    /// mean that its one non-ZST field would also be [`OperandValue::Immediate`].
693    Vector(Either<V, ()>),
694}
695
696/// Allows building up an `OperandRef` by setting fields one at a time.
697#[derive(#[automatically_derived]
impl<'tcx, V: ::core::fmt::Debug> ::core::fmt::Debug for
    OperandRefBuilder<'tcx, V> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "OperandRefBuilder", "val", &self.val, "layout", &&self.layout)
    }
}Debug, #[automatically_derived]
impl<'tcx, V: ::core::marker::Copy> ::core::marker::Copy for
    OperandRefBuilder<'tcx, V> {
}Copy, #[automatically_derived]
impl<'tcx, V: ::core::clone::Clone> ::core::clone::Clone for
    OperandRefBuilder<'tcx, V> {
    #[inline]
    fn clone(&self) -> OperandRefBuilder<'tcx, V> {
        OperandRefBuilder {
            val: ::core::clone::Clone::clone(&self.val),
            layout: ::core::clone::Clone::clone(&self.layout),
        }
    }
}Clone)]
698pub(super) struct OperandRefBuilder<'tcx, V> {
699    val: OperandValueBuilder<V>,
700    layout: TyAndLayout<'tcx>,
701}
702
703impl<'a, 'tcx, V: CodegenObject> OperandRefBuilder<'tcx, V> {
704    /// Creates an uninitialized builder for an instance of the `layout`.
705    ///
706    /// ICEs for [`BackendRepr::Memory`] types (other than ZSTs), which should
707    /// be built up inside a [`PlaceRef`] instead as they need an allocated place
708    /// into which to write the values of the fields.
709    pub(super) fn new(layout: TyAndLayout<'tcx>) -> Self {
710        let val = match layout.backend_repr {
711            BackendRepr::Memory { .. } if layout.is_zst() => OperandValueBuilder::ZeroSized,
712            BackendRepr::Scalar(s) => OperandValueBuilder::Immediate(Either::Right(s)),
713            BackendRepr::ScalarPair { a, b, b_offset: _ } => {
714                OperandValueBuilder::Pair(Either::Right(a), Either::Right(b))
715            }
716            BackendRepr::SimdVector { .. } | BackendRepr::SimdScalableVector { .. } => {
717                OperandValueBuilder::Vector(Either::Right(()))
718            }
719            BackendRepr::Memory { .. } => {
720                ::rustc_middle::util::bug::bug_fmt(format_args!("Cannot use non-ZST Memory-ABI type in operand builder: {0:?}",
        layout));bug!("Cannot use non-ZST Memory-ABI type in operand builder: {layout:?}");
721            }
722        };
723        OperandRefBuilder { val, layout }
724    }
725
726    /// Creates an initialized builder for updating an existing `operand`.
727    ///
728    /// ICEs for [`BackendRepr::Memory`] types (other than ZSTs), which use
729    /// which use [`OperandValue::Ref`]. In this case, updates should be
730    /// performed by writing into the place
731    pub(super) fn from_existing(operand: OperandRef<'tcx, V>) -> Self {
732        let layout = operand.layout;
733        let val = match (operand.val, layout.backend_repr) {
734            (OperandValue::ZeroSized, _) => OperandValueBuilder::ZeroSized,
735            (OperandValue::Immediate(v), BackendRepr::Scalar(_)) => {
736                OperandValueBuilder::Immediate(Either::Left(v))
737            }
738            (OperandValue::Immediate(v), BackendRepr::SimdVector { .. }) => {
739                OperandValueBuilder::Vector(Either::Left(v))
740            }
741            (OperandValue::Pair(a, b), BackendRepr::ScalarPair { a: _, b: _, b_offset: _ }) => {
742                OperandValueBuilder::Pair(Either::Left(a), Either::Left(b))
743            }
744            (_, BackendRepr::Memory { .. }) => {
745                ::rustc_middle::util::bug::bug_fmt(format_args!("Cannot use non-ZST Memory-ABI type in operand builder: {0:?}",
        layout));bug!("Cannot use non-ZST Memory-ABI type in operand builder: {layout:?}");
746            }
747            _ => {
748                ::rustc_middle::util::bug::bug_fmt(format_args!("Operand cannot be used with `from_existing`: {0:?}",
        operand))bug!("Operand cannot be used with `from_existing`: {operand:?}")
749            }
750        };
751        OperandRefBuilder { val, layout }
752    }
753
754    pub(super) fn insert_field<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
755        &mut self,
756        bx: &mut Bx,
757        variant: VariantIdx,
758        field: FieldIdx,
759        field_operand: OperandRef<'tcx, V>,
760    ) {
761        if let OperandValue::ZeroSized = field_operand.val {
762            // A ZST never adds any state, so just ignore it.
763            // This special-casing is worth it because of things like
764            // `Result<!, !>` where `Ok(never)` is legal to write,
765            // but the type shows as FieldShape::Primitive so we can't
766            // actually look at the layout for the field being set.
767            return;
768        }
769
770        let is_zero_offset = if let abi::FieldsShape::Primitive = self.layout.fields {
771            // The other branch looking at field layouts ICEs for primitives,
772            // so we need to handle them separately.
773            // Because we handled ZSTs above (like the metadata in a thin pointer),
774            // the only possibility is that we're setting the one-and-only field.
775            if !!self.layout.is_zst() {
    ::core::panicking::panic("assertion failed: !self.layout.is_zst()")
};assert!(!self.layout.is_zst());
776            {
    match (&variant, &FIRST_VARIANT) {
        (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!(variant, FIRST_VARIANT);
777            {
    match (&field, &FieldIdx::ZERO) {
        (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!(field, FieldIdx::ZERO);
778            true
779        } else {
780            let variant_layout = self.layout.for_variant(bx.cx(), variant);
781            let field_offset = variant_layout.fields.offset(field.as_usize());
782            field_offset == Size::ZERO
783        };
784
785        let mut update = |tgt: &mut Either<V, abi::Scalar>, src, from_scalar| {
786            let to_scalar = tgt.unwrap_right();
787            // We transmute here (rather than just `from_immediate`) because in
788            // `Result<usize, *const ()>` the field of the `Ok` is an integer,
789            // but the corresponding scalar in the enum is a pointer.
790            let imm = transmute_scalar(bx, src, from_scalar, to_scalar);
791            *tgt = Either::Left(imm);
792        };
793
794        match (field_operand.val, field_operand.layout.backend_repr) {
795            (OperandValue::ZeroSized, _) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("Handled above")));
}unreachable!("Handled above"),
796            (OperandValue::Immediate(v), BackendRepr::Scalar(from_scalar)) => match &mut self.val {
797                OperandValueBuilder::Immediate(val @ Either::Right(_)) if is_zero_offset => {
798                    update(val, v, from_scalar);
799                }
800                OperandValueBuilder::Pair(fst @ Either::Right(_), _) if is_zero_offset => {
801                    update(fst, v, from_scalar);
802                }
803                OperandValueBuilder::Pair(_, snd @ Either::Right(_)) if !is_zero_offset => {
804                    update(snd, v, from_scalar);
805                }
806                _ => {
807                    ::rustc_middle::util::bug::bug_fmt(format_args!("Tried to insert {0:?} into {1:?}.{2:?} of {3:?}",
        field_operand, variant, field, self))bug!("Tried to insert {field_operand:?} into {variant:?}.{field:?} of {self:?}")
808                }
809            },
810            (OperandValue::Immediate(v), BackendRepr::SimdVector { .. }) => match &mut self.val {
811                OperandValueBuilder::Vector(val @ Either::Right(())) if is_zero_offset => {
812                    *val = Either::Left(v);
813                }
814                _ => {
815                    ::rustc_middle::util::bug::bug_fmt(format_args!("Tried to insert {0:?} into {1:?}.{2:?} of {3:?}",
        field_operand, variant, field, self))bug!("Tried to insert {field_operand:?} into {variant:?}.{field:?} of {self:?}")
816                }
817            },
818            (
819                OperandValue::Pair(a, b),
820                BackendRepr::ScalarPair { a: from_sa, b: from_sb, b_offset: _ },
821            ) => match &mut self.val {
822                OperandValueBuilder::Pair(fst @ Either::Right(_), snd @ Either::Right(_)) => {
823                    update(fst, a, from_sa);
824                    update(snd, b, from_sb);
825                }
826                _ => {
827                    ::rustc_middle::util::bug::bug_fmt(format_args!("Tried to insert {0:?} into {1:?}.{2:?} of {3:?}",
        field_operand, variant, field, self))bug!("Tried to insert {field_operand:?} into {variant:?}.{field:?} of {self:?}")
828                }
829            },
830            (OperandValue::Ref(place), BackendRepr::Memory { .. }) => match &mut self.val {
831                OperandValueBuilder::Vector(val @ Either::Right(())) => {
832                    let ibty = bx.cx().immediate_backend_type(self.layout);
833                    let simd = bx.load_from_place(ibty, place);
834                    *val = Either::Left(simd);
835                }
836                _ => {
837                    ::rustc_middle::util::bug::bug_fmt(format_args!("Tried to insert {0:?} into {1:?}.{2:?} of {3:?}",
        field_operand, variant, field, self))bug!("Tried to insert {field_operand:?} into {variant:?}.{field:?} of {self:?}")
838                }
839            },
840            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("Operand cannot be used with `insert_field`: {0:?}",
        field_operand))bug!("Operand cannot be used with `insert_field`: {field_operand:?}"),
841        }
842    }
843
844    /// Insert the immediate value `imm` for field `f` in the *type itself*,
845    /// rather than into one of the variants.
846    ///
847    /// Most things want [`Self::insert_field`] instead, but this one is
848    /// necessary for writing things like enum tags that aren't in any variant.
849    pub(super) fn insert_imm(&mut self, f: FieldIdx, imm: V) {
850        let field_offset = self.layout.fields.offset(f.as_usize());
851        let is_zero_offset = field_offset == Size::ZERO;
852        match &mut self.val {
853            OperandValueBuilder::Immediate(val @ Either::Right(_)) if is_zero_offset => {
854                *val = Either::Left(imm);
855            }
856            OperandValueBuilder::Pair(fst @ Either::Right(_), _) if is_zero_offset => {
857                *fst = Either::Left(imm);
858            }
859            OperandValueBuilder::Pair(_, snd @ Either::Right(_)) if !is_zero_offset => {
860                *snd = Either::Left(imm);
861            }
862            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("Tried to insert {0:?} into field {1:?} of {2:?}",
        imm, f, self))bug!("Tried to insert {imm:?} into field {f:?} of {self:?}"),
863        }
864    }
865
866    /// Replaces the current immediate value at the offset `offset`
867    /// with the value `imm`. A value must already be present.
868    ///
869    /// This is used along with [`Self::from_existing`] to perform in-place updates
870    /// of any operand.
871    pub(super) fn update_imm(&mut self, offset: Size, imm: V) {
872        let is_zero_offset = offset == Size::ZERO;
873        match &mut self.val {
874            OperandValueBuilder::Immediate(val @ Either::Left(_)) if is_zero_offset => {
875                *val = Either::Left(imm);
876            }
877            OperandValueBuilder::Pair(fst @ Either::Left(_), _) if is_zero_offset => {
878                *fst = Either::Left(imm);
879            }
880            OperandValueBuilder::Pair(_, snd @ Either::Left(_)) if !is_zero_offset => {
881                *snd = Either::Left(imm);
882            }
883            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("Tried to update {0:?} at offset {1:?} of {2:?}",
        imm, offset, self))bug!("Tried to update {imm:?} at offset {offset:?} of {self:?}"),
884        }
885    }
886
887    /// After having set all necessary fields, this converts the builder back
888    /// to the normal `OperandRef`.
889    ///
890    /// ICEs if any required fields were not set.
891    pub(super) fn build(&self, cx: &impl CodegenMethods<'tcx, Value = V>) -> OperandRef<'tcx, V> {
892        let OperandRefBuilder { val, layout } = *self;
893
894        // For something like `Option::<u32>::None`, it's expected that the
895        // payload scalar will not actually have been set, so this converts
896        // unset scalars to corresponding `undef` values so long as the scalar
897        // from the layout allows uninit.
898        let unwrap = |r: Either<V, abi::Scalar>| match r {
899            Either::Left(v) => v,
900            Either::Right(s) if s.is_uninit_valid() => {
901                let bty = cx.type_from_scalar(s);
902                cx.const_undef(bty)
903            }
904            Either::Right(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("OperandRef::build called while fields are missing {0:?}",
        self))bug!("OperandRef::build called while fields are missing {self:?}"),
905        };
906
907        let val = match val {
908            OperandValueBuilder::ZeroSized => OperandValue::ZeroSized,
909            OperandValueBuilder::Immediate(v) => OperandValue::Immediate(unwrap(v)),
910            OperandValueBuilder::Pair(a, b) => OperandValue::Pair(unwrap(a), unwrap(b)),
911            OperandValueBuilder::Vector(v) => match v {
912                Either::Left(v) => OperandValue::Immediate(v),
913                Either::Right(())
914                    if let BackendRepr::SimdVector { element, .. } = layout.backend_repr
915                        && element.is_uninit_valid() =>
916                {
917                    let bty = cx.immediate_backend_type(layout);
918                    OperandValue::Immediate(cx.const_undef(bty))
919                }
920                Either::Right(()) => {
921                    ::rustc_middle::util::bug::bug_fmt(format_args!("OperandRef::build called while fields are missing {0:?}",
        self))bug!("OperandRef::build called while fields are missing {self:?}")
922                }
923            },
924        };
925        OperandRef { val, layout, move_annotation: None }
926    }
927}
928
929/// Default size limit for move/copy annotations (in bytes). 64 bytes is a common size of a cache
930/// line, and the assumption is that anything this size or below is very cheap to move/copy, so only
931/// annotate copies larger than this.
932const MOVE_ANNOTATION_DEFAULT_LIMIT: u64 = 65;
933
934impl<'a, 'tcx, V: CodegenObject> OperandValue<V> {
935    /// Returns an `OperandValue` that's generally UB to use in any way.
936    ///
937    /// Depending on the `layout`, returns `ZeroSized` for ZSTs, an `Immediate` or
938    /// `Pair` containing poison value(s), or a `Ref` containing a poison pointer.
939    ///
940    /// Supports sized types only.
941    pub fn poison<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
942        bx: &mut Bx,
943        layout: TyAndLayout<'tcx>,
944    ) -> OperandValue<V> {
945        if !layout.is_sized() {
    ::core::panicking::panic("assertion failed: layout.is_sized()")
};assert!(layout.is_sized());
946        if layout.is_zst() {
947            OperandValue::ZeroSized
948        } else if bx.cx().is_backend_immediate(layout) {
949            let ibty = bx.cx().immediate_backend_type(layout);
950            OperandValue::Immediate(bx.const_poison(ibty))
951        } else if bx.cx().is_backend_scalar_pair(layout) {
952            let ibty0 = bx.cx().scalar_pair_element_backend_type(layout, 0, true);
953            let ibty1 = bx.cx().scalar_pair_element_backend_type(layout, 1, true);
954            OperandValue::Pair(bx.const_poison(ibty0), bx.const_poison(ibty1))
955        } else {
956            let ptr = bx.cx().type_ptr();
957            OperandValue::Ref(PlaceValue::new_sized(bx.const_poison(ptr), layout.align.abi))
958        }
959    }
960
961    pub fn store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
962        self,
963        bx: &mut Bx,
964        dest: PlaceRef<'tcx, V>,
965    ) {
966        self.store_with_flags(bx, dest, MemFlags::empty());
967    }
968
969    pub fn volatile_store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
970        self,
971        bx: &mut Bx,
972        dest: PlaceRef<'tcx, V>,
973    ) {
974        self.store_with_flags(bx, dest, MemFlags::VOLATILE);
975    }
976
977    pub fn unaligned_volatile_store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
978        self,
979        bx: &mut Bx,
980        dest: PlaceRef<'tcx, V>,
981    ) {
982        self.store_with_flags(bx, dest, MemFlags::VOLATILE | MemFlags::UNALIGNED);
983    }
984
985    pub fn nontemporal_store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
986        self,
987        bx: &mut Bx,
988        dest: PlaceRef<'tcx, V>,
989    ) {
990        self.store_with_flags(bx, dest, MemFlags::NONTEMPORAL);
991    }
992
993    pub(crate) fn store_with_flags<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
994        self,
995        bx: &mut Bx,
996        dest: PlaceRef<'tcx, V>,
997        flags: MemFlags,
998    ) {
999        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/operand.rs:999",
                        "rustc_codegen_ssa::mir::operand", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/operand.rs"),
                        ::tracing_core::__macro_support::Option::Some(999u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::operand"),
                        ::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!("OperandRef::store: operand={0:?}, dest={1:?}",
                                                    self, dest) as &dyn Value))])
            });
    } else { ; }
};debug!("OperandRef::store: operand={:?}, dest={:?}", self, dest);
1000        match self {
1001            OperandValue::ZeroSized => {
1002                // Avoid generating stores of zero-sized values, because the only way to have a
1003                // zero-sized value is through `undef`/`poison`, and the store itself is useless.
1004            }
1005            OperandValue::Ref(val) => {
1006                if !dest.layout.is_sized() {
    {
        ::core::panicking::panic_fmt(format_args!("cannot directly store unsized values"));
    }
};assert!(dest.layout.is_sized(), "cannot directly store unsized values");
1007                if val.llextra.is_some() {
1008                    ::rustc_middle::util::bug::bug_fmt(format_args!("cannot directly store unsized values"));bug!("cannot directly store unsized values");
1009                }
1010                bx.typed_place_copy_with_flags(dest.val, val, dest.layout, flags);
1011            }
1012            OperandValue::Immediate(s) => {
1013                let val = bx.from_immediate(s);
1014                bx.store_with_flags(val, dest.val.llval, dest.val.align, flags);
1015            }
1016            OperandValue::Pair(a, b) => {
1017                let BackendRepr::ScalarPair { a: _, b: _, b_offset } = dest.layout.backend_repr
1018                else {
1019                    ::rustc_middle::util::bug::bug_fmt(format_args!("store_with_flags: invalid ScalarPair layout: {0:#?}",
        dest.layout));bug!("store_with_flags: invalid ScalarPair layout: {:#?}", dest.layout);
1020                };
1021
1022                let val = bx.from_immediate(a);
1023                let align = dest.val.align;
1024                bx.store_with_flags(val, dest.val.llval, align, flags);
1025
1026                let llptr = bx.inbounds_ptradd(dest.val.llval, bx.const_usize(b_offset.bytes()));
1027                let val = bx.from_immediate(b);
1028                let align = dest.val.align.restrict_for_offset(b_offset);
1029                // The CAPTURES_READ_ONLY flag only applies to the first element.
1030                bx.store_with_flags(val, llptr, align, flags & !MemFlags::CAPTURES_READ_ONLY);
1031            }
1032        }
1033    }
1034}
1035
1036impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
1037    fn maybe_codegen_consume_direct(
1038        &mut self,
1039        bx: &mut Bx,
1040        place_ref: mir::PlaceRef<'tcx>,
1041    ) -> Option<OperandRef<'tcx, Bx::Value>> {
1042        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/operand.rs:1042",
                        "rustc_codegen_ssa::mir::operand", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/operand.rs"),
                        ::tracing_core::__macro_support::Option::Some(1042u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::operand"),
                        ::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!("maybe_codegen_consume_direct(place_ref={0:?})",
                                                    place_ref) as &dyn Value))])
            });
    } else { ; }
};debug!("maybe_codegen_consume_direct(place_ref={:?})", place_ref);
1043
1044        match self.locals[place_ref.local] {
1045            LocalRef::Operand(mut o) => {
1046                // We only need to handle the projections that
1047                // `LocalAnalyzer::process_place` let make it here.
1048                for elem in place_ref.projection {
1049                    match *elem {
1050                        mir::ProjectionElem::Field(f, _) => {
1051                            if !!o.layout.ty.is_any_ptr() {
    {
        ::core::panicking::panic_fmt(format_args!("Bad PlaceRef: destructing pointers should use cast/PtrMetadata, but tried to access field {0:?} of pointer {1:?}",
                f, o));
    }
};assert!(
1052                                !o.layout.ty.is_any_ptr(),
1053                                "Bad PlaceRef: destructing pointers should use cast/PtrMetadata, \
1054                                 but tried to access field {f:?} of pointer {o:?}",
1055                            );
1056                            o = o.extract_field(self, bx, f.index());
1057                        }
1058                        mir::PlaceElem::Downcast(_, vidx) => {
1059                            if true {
    {
        match (&o.layout.variants, &abi::Variants::Single { index: vidx }) {
            (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);
                }
            }
        }
    };
};debug_assert_eq!(
1060                                o.layout.variants,
1061                                abi::Variants::Single { index: vidx },
1062                            );
1063                            let layout = o.layout.for_variant(bx.cx(), vidx);
1064                            o = OperandRef { layout, ..o }
1065                        }
1066                        _ => return None,
1067                    }
1068                }
1069
1070                Some(o)
1071            }
1072            LocalRef::PendingOperand => {
1073                ::rustc_middle::util::bug::bug_fmt(format_args!("use of {0:?} before def",
        place_ref));bug!("use of {:?} before def", place_ref);
1074            }
1075            LocalRef::Place(..) | LocalRef::UnsizedPlace(..) => {
1076                // watch out for locals that do not have an
1077                // alloca; they are handled somewhat differently
1078                None
1079            }
1080        }
1081    }
1082
1083    pub fn codegen_consume(
1084        &mut self,
1085        bx: &mut Bx,
1086        place_ref: mir::PlaceRef<'tcx>,
1087    ) -> OperandRef<'tcx, Bx::Value> {
1088        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/operand.rs:1088",
                        "rustc_codegen_ssa::mir::operand", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/operand.rs"),
                        ::tracing_core::__macro_support::Option::Some(1088u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::operand"),
                        ::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!("codegen_consume(place_ref={0:?})",
                                                    place_ref) as &dyn Value))])
            });
    } else { ; }
};debug!("codegen_consume(place_ref={:?})", place_ref);
1089
1090        let ty = self.monomorphized_place_ty(place_ref);
1091        let layout = bx.cx().layout_of(ty);
1092
1093        // ZSTs don't require any actual memory access.
1094        if layout.is_zst() {
1095            return OperandRef::zero_sized(layout);
1096        }
1097
1098        if let Some(o) = self.maybe_codegen_consume_direct(bx, place_ref) {
1099            return o;
1100        }
1101
1102        // for most places, to consume them we just load them
1103        // out from their home
1104        let place = self.codegen_place(bx, place_ref);
1105        bx.load_operand(place)
1106    }
1107
1108    pub fn codegen_operand(
1109        &mut self,
1110        bx: &mut Bx,
1111        operand: &mir::Operand<'tcx>,
1112    ) -> OperandRef<'tcx, Bx::Value> {
1113        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/operand.rs:1113",
                        "rustc_codegen_ssa::mir::operand", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/operand.rs"),
                        ::tracing_core::__macro_support::Option::Some(1113u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::operand"),
                        ::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!("codegen_operand(operand={0:?})",
                                                    operand) as &dyn Value))])
            });
    } else { ; }
};debug!("codegen_operand(operand={:?})", operand);
1114
1115        match *operand {
1116            mir::Operand::Copy(ref place) | mir::Operand::Move(ref place) => {
1117                let kind = match operand {
1118                    mir::Operand::Move(_) => LangItem::CompilerMove,
1119                    mir::Operand::Copy(_) => LangItem::CompilerCopy,
1120                    _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1121                };
1122
1123                // Check if we should annotate this move/copy for profiling
1124                let move_annotation = self.move_copy_annotation_instance(bx, place.as_ref(), kind);
1125
1126                OperandRef { move_annotation, ..self.codegen_consume(bx, place.as_ref()) }
1127            }
1128
1129            mir::Operand::RuntimeChecks(checks) => {
1130                let layout = bx.layout_of(bx.tcx().types.bool);
1131                let BackendRepr::Scalar(scalar) = layout.backend_repr else {
1132                    ::rustc_middle::util::bug::bug_fmt(format_args!("from_const: invalid ByVal layout: {0:#?}",
        layout));bug!("from_const: invalid ByVal layout: {:#?}", layout);
1133                };
1134                let x = Scalar::from_bool(checks.value(bx.tcx().sess));
1135                let llval = bx.scalar_to_backend(x, scalar, bx.immediate_backend_type(layout));
1136                let val = OperandValue::Immediate(llval);
1137                OperandRef { val, layout, move_annotation: None }
1138            }
1139
1140            mir::Operand::Constant(ref constant) => {
1141                let constant_ty = self.monomorphize(constant.ty());
1142                // Most SIMD vector constants should be passed as immediates.
1143                // (In particular, some intrinsics really rely on this.)
1144                if constant_ty.is_simd() {
1145                    // However, some SIMD types do not actually use the vector ABI
1146                    // (in particular, packed SIMD types do not). Ensure we exclude those.
1147                    //
1148                    // We also have to exclude vectors of pointers because `immediate_const_vector`
1149                    // does not work for those.
1150                    let layout = bx.layout_of(constant_ty);
1151                    let (_, element_ty) = constant_ty.simd_size_and_type(bx.tcx());
1152                    if let BackendRepr::SimdVector { .. } = layout.backend_repr
1153                        && element_ty.is_numeric()
1154                    {
1155                        let (llval, ty) = self.immediate_const_vector(bx, constant);
1156                        return OperandRef {
1157                            val: OperandValue::Immediate(llval),
1158                            layout: bx.layout_of(ty),
1159                            move_annotation: None,
1160                        };
1161                    }
1162                }
1163                self.eval_mir_constant_to_operand(bx, constant)
1164            }
1165        }
1166    }
1167
1168    /// Creates an `Instance` for annotating a move/copy operation at codegen time.
1169    ///
1170    /// Returns `Some(instance)` if the operation should be annotated with debug info, `None`
1171    /// otherwise. The instance represents a monomorphized `compiler_move<T, SIZE>` or
1172    /// `compiler_copy<T, SIZE>` function that can be used to create debug scopes.
1173    ///
1174    /// There are a number of conditions that must be met for an annotation to be created, but aside
1175    /// from the basics (annotation is enabled, we're generating debuginfo), the primary concern is
1176    /// moves/copies which could result in a real `memcpy`. So we check for the size limit, but also
1177    /// that the underlying representation of the type is in memory.
1178    fn move_copy_annotation_instance(
1179        &self,
1180        bx: &Bx,
1181        place: mir::PlaceRef<'tcx>,
1182        kind: LangItem,
1183    ) -> Option<ty::Instance<'tcx>> {
1184        let tcx = bx.tcx();
1185        let sess = tcx.sess;
1186
1187        // Skip if we're not generating debuginfo
1188        if sess.opts.debuginfo == DebugInfo::None {
1189            return None;
1190        }
1191
1192        // Check if annotation is enabled and get size limit (otherwise skip)
1193        let size_limit = match sess.opts.unstable_opts.annotate_moves {
1194            AnnotateMoves::Disabled => return None,
1195            AnnotateMoves::Enabled(None) => MOVE_ANNOTATION_DEFAULT_LIMIT,
1196            AnnotateMoves::Enabled(Some(limit)) => limit,
1197        };
1198
1199        let ty = self.monomorphized_place_ty(place);
1200        let layout = bx.cx().layout_of(ty);
1201        let ty_size = layout.size.bytes();
1202
1203        // Only annotate if type has a memory representation and exceeds size limit (and has a
1204        // non-zero size)
1205        if layout.is_zst()
1206            || ty_size < size_limit
1207            || !#[allow(non_exhaustive_omitted_patterns)] match layout.backend_repr {
    BackendRepr::Memory { .. } => true,
    _ => false,
}matches!(layout.backend_repr, BackendRepr::Memory { .. })
1208        {
1209            return None;
1210        }
1211
1212        // Look up the DefId for compiler_move or compiler_copy lang item
1213        let def_id = tcx.lang_items().get(kind)?;
1214
1215        // Create generic args: compiler_move<T, SIZE> or compiler_copy<T, SIZE>
1216        let size_const = ty::Const::from_target_usize(tcx, ty_size);
1217        let generic_args = tcx.mk_args(&[ty.into(), size_const.into()]);
1218
1219        // Create the Instance
1220        let typing_env = self.mir.typing_env(tcx);
1221        let instance = ty::Instance::expect_resolve(
1222            tcx,
1223            typing_env,
1224            def_id,
1225            generic_args,
1226            rustc_span::DUMMY_SP, // span only used for error messages
1227        );
1228
1229        Some(instance)
1230    }
1231}