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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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