Skip to main content

rustc_codegen_ssa/mir/
rvalue.rs

1use std::assert_matches;
2use std::cmp::Ordering;
3
4use itertools::Itertools as _;
5use rustc_abi::{self as abi, BackendRepr, FIRST_VARIANT};
6use rustc_index::IndexVec;
7use rustc_middle::mir;
8use rustc_middle::ty::adjustment::PointerCoercion;
9use rustc_middle::ty::layout::{HasTyCtxt, HasTypingEnv, LayoutOf, TyAndLayout};
10use rustc_middle::ty::{self, Instance, Mutability, Ty, TyCtxt};
11use rustc_session::config::OptLevel;
12use rustc_span::{bug, span_bug};
13use tracing::{debug, instrument};
14
15use super::FunctionCx;
16use super::operand::{OperandRef, OperandRefBuilder, OperandValue};
17use super::place::{PlaceRef, PlaceValue, codegen_tag_value};
18use crate::common::IntPredicate;
19use crate::traits::*;
20use crate::{MemFlags, base};
21
22impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
23    fn try_codegen_const_aggregate_as_immediate(
24        &mut self,
25        bx: &mut Bx,
26        dest: PlaceRef<'tcx, Bx::Value>,
27        kind: &mir::AggregateKind<'tcx>,
28        operands: &IndexVec<abi::FieldIdx, mir::Operand<'tcx>>,
29    ) -> bool {
30        // Keep this allowlist limited to aggregate kinds with direct codegen coverage.
31        // Extract the variant index at the same time so we can verify it against
32        // the layout below. Tuples always use `FIRST_VARIANT` (index 0); the
33        // `None` in the `Adt` arm excludes unions (which carry an active field).
34        let variant_index = match kind {
35            mir::AggregateKind::Tuple => FIRST_VARIANT,
36            mir::AggregateKind::Adt(_, variant_index, _, _, None) => *variant_index,
37            _ => return false,
38        };
39        if !#[allow(non_exhaustive_omitted_patterns)] match dest.layout.fields {
    abi::FieldsShape::Arbitrary { .. } => true,
    _ => false,
}matches!(dest.layout.fields, abi::FieldsShape::Arbitrary { .. }) {
40            return false;
41        }
42        // `dest.layout` is the layout of the *overall* type, not a specific
43        // variant. When the layout is `Variants::Single { index: M }`, the
44        // field offsets and counts below all refer to variant M. If the MIR
45        // aggregate is constructing a different variant N (e.g. because N is
46        // uninhabited and the layout collapsed to M), using `dest.layout`
47        // directly would read the wrong field metadata. Bail out and let the
48        // normal codegen path handle it via `project_downcast`.
49        if !#[allow(non_exhaustive_omitted_patterns)] match dest.layout.variants {
    abi::Variants::Single { index } if index == variant_index => true,
    _ => false,
}matches!(dest.layout.variants, abi::Variants::Single { index } if index == variant_index)
50        {
51            return false;
52        }
53        // Now that the variant indices are known to match, the operand count
54        // and the layout field count must agree.
55        if true {
    {
        match (&operands.len(), &dest.layout.fields.count()) {
            (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!(operands.len(), dest.layout.fields.count());
56
57        let size = dest.layout.size.bytes();
58        let llty = match size {
59            1 => bx.cx().type_i8(),
60            2 => bx.cx().type_i16(),
61            4 => bx.cx().type_i32(),
62            8 => bx.cx().type_i64(),
63            16 => bx.cx().type_i128(),
64            _ => return false,
65        };
66
67        let mut value = 0u128;
68        for (field_idx, operand) in operands.iter_enumerated() {
69            let field_layout = dest.layout.field(bx.cx(), field_idx.as_usize());
70            if field_layout.is_zst() {
71                continue;
72            }
73            let mir::Operand::Constant(constant) = operand else {
74                return false;
75            };
76            let Some(field_value) = self.eval_mir_constant(constant).try_to_bits(field_layout.size)
77            else {
78                return false;
79            };
80
81            let field_size = field_layout.size.bytes();
82            let field_offset = dest.layout.fields.offset(field_idx.as_usize()).bytes();
83            if true {
    if !(field_offset + field_size <= size) {
        ::core::panicking::panic("assertion failed: field_offset + field_size <= size")
    };
};debug_assert!(field_offset + field_size <= size);
84            let shift = match bx.tcx().data_layout.endian {
85                abi::Endian::Little => field_offset * 8,
86                abi::Endian::Big => (size - field_offset - field_size) * 8,
87            };
88            value |= field_value << shift;
89        }
90
91        let value = bx.cx().const_uint_big(llty, value);
92        bx.store_to_place(value, dest.val);
93        true
94    }
95
96    fn is_entirely_uninit_const(&self, operand: &mir::Operand<'tcx>) -> bool {
97        let mir::Operand::Constant(const_op) = operand else { return false };
98        self.eval_mir_constant(const_op).all_bytes_uninit(self.cx.tcx())
99    }
100
101    {}
#[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_rvalue",
                                    "rustc_codegen_ssa::mir::rvalue", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/mir/rvalue.rs"),
                                    ::tracing_core::__macro_support::Option::Some(101u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::rvalue"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("dest")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("dest");
                                                        NAME.as_str()
                                                    },
                                                    {
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("rvalue")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("rvalue");
                                                        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(&dest)
                                                            as &dyn ::tracing::field::Value)),
                                                (::tracing::__macro_support::Option::Some(&::tracing::field::debug(&rvalue)
                                                            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: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            match *rvalue {
                mir::Rvalue::Use(ref operand, with_retag) => {
                    if self.is_entirely_uninit_const(operand) { return; }
                    let cg_operand = self.codegen_operand(bx, operand);
                    if #[allow(non_exhaustive_omitted_patterns)] match cg_operand.layout.backend_repr
                            {
                            BackendRepr::Scalar(..) | BackendRepr::ScalarPair { .. } =>
                                true,
                            _ => false,
                        } {
                        if true {
                            if !!#[allow(non_exhaustive_omitted_patterns)] match cg_operand.val
                                            {
                                            OperandValue::Ref(..) => true,
                                            _ => false,
                                        } {
                                ::core::panicking::panic("assertion failed: !matches!(cg_operand.val, OperandValue::Ref(..))")
                            };
                        };
                    }
                    let flags =
                        if let ty::Ref(_, pointee_ty, Mutability::Not) =
                                        cg_operand.layout.ty.kind() && with_retag.yes() &&
                                pointee_ty.is_freeze(self.cx.tcx(), self.cx.typing_env()) {
                            MemFlags::CAPTURES_READ_ONLY
                        } else { MemFlags::empty() };
                    cg_operand.store_with_annotation_and_flags(bx, dest, flags);
                }
                mir::Rvalue::Cast(mir::CastKind::PointerCoercion(PointerCoercion::Unsize,
                    _), ref source, _) => {
                    if let BackendRepr::ScalarPair { .. } =
                            dest.layout.backend_repr {
                        let temp = self.codegen_rvalue_operand(bx, rvalue);
                        temp.store_with_annotation(bx, dest);
                        return;
                    }
                    let operand = self.codegen_operand(bx, source);
                    match operand.val {
                        OperandValue::Pair(..) | OperandValue::Immediate(_) => {
                            {
                                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/rvalue.rs:167",
                                                    "rustc_codegen_ssa::mir::rvalue", ::tracing::Level::DEBUG,
                                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/mir/rvalue.rs"),
                                                    ::tracing_core::__macro_support::Option::Some(167u32),
                                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::rvalue"),
                                                    ::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_rvalue: creating ugly alloca")
                                                                        as &dyn ::tracing::field::Value))])
                                        });
                                } else { ; }
                            };
                            let scratch = PlaceRef::alloca(bx, operand.layout);
                            scratch.storage_live(bx);
                            operand.store_with_annotation(bx, scratch);
                            base::coerce_unsized_into(bx, scratch, dest);
                            scratch.storage_dead(bx);
                        }
                        OperandValue::Ref(val) => {
                            if val.llextra.is_some() {
                                ::rustc_span::macros::bug_impl(None,
                                    format_args!("unsized coercion on an unsized rvalue"),
                                    Location::caller());
                            }
                            base::coerce_unsized_into(bx, val.with_type(operand.layout),
                                dest);
                        }
                        OperandValue::ZeroSized => {
                            ::rustc_span::macros::bug_impl(None,
                                format_args!("unsized coercion on a ZST rvalue"),
                                Location::caller());
                        }
                    }
                }
                mir::Rvalue::Cast(mir::CastKind::Transmute |
                    mir::CastKind::Subtype, ref operand, _ty) => {
                    let src = self.codegen_operand(bx, operand);
                    self.codegen_transmute(bx, src, dest);
                }
                mir::Rvalue::Repeat(ref elem, count) => {
                    if dest.layout.is_zst() { return; }
                    if self.is_entirely_uninit_const(elem) {
                        let size = bx.const_usize(dest.layout.size.bytes());
                        bx.memset(dest.val.llval, bx.const_undef(bx.type_i8()),
                            size, dest.val.align, MemFlags::empty());
                        return;
                    }
                    let cg_elem = self.codegen_operand(bx, elem);
                    let try_init_all_same =
                        |bx: &mut Bx, v|
                            {
                                let start = dest.val.llval;
                                let size = bx.const_usize(dest.layout.size.bytes());
                                if let Some(int) = bx.cx().const_to_opt_u128(v, false) &&
                                            let bytes =
                                                &int.to_le_bytes()[..cg_elem.layout.size.bytes_usize()] &&
                                        let Ok(&byte) = bytes.iter().all_equal_value() {
                                    let fill = bx.cx().const_u8(byte);
                                    bx.memset(start, fill, size, dest.val.align,
                                        MemFlags::empty());
                                    return true;
                                }
                                let v = bx.from_immediate(v);
                                if bx.cx().val_ty(v) == bx.cx().type_i8() {
                                    bx.memset(start, v, size, dest.val.align,
                                        MemFlags::empty());
                                    return true;
                                }
                                false
                            };
                    if let OperandValue::Immediate(v) = cg_elem.val &&
                            try_init_all_same(bx, v) {
                        return;
                    }
                    let count =
                        self.monomorphize(count).try_to_target_usize(bx.tcx()).expect("expected monomorphic const in codegen");
                    bx.write_operand_repeatedly(cg_elem, count, dest);
                }
                mir::Rvalue::Aggregate(ref kind, ref operands) if
                    !#[allow(non_exhaustive_omitted_patterns)] match **kind {
                            mir::AggregateKind::RawPtr(..) => true,
                            _ => false,
                        } => {
                    if self.try_codegen_const_aggregate_as_immediate(bx, dest,
                            kind, operands) {
                        return;
                    }
                    let (variant_index, variant_dest, active_field_index) =
                        match **kind {
                            mir::AggregateKind::Adt(_, variant_index, _, _,
                                active_field_index) => {
                                let variant_dest = dest.project_downcast(bx, variant_index);
                                (variant_index, variant_dest, active_field_index)
                            }
                            _ => (FIRST_VARIANT, dest, None),
                        };
                    if active_field_index.is_some() {
                        {
                            match (&operands.len(), &1) {
                                (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);
                                    }
                                }
                            }
                        };
                    }
                    for (i, operand) in operands.iter_enumerated() {
                        if self.is_entirely_uninit_const(operand) { continue; }
                        let op = self.codegen_operand(bx, operand);
                        if !op.layout.is_zst() {
                            let field_index = active_field_index.unwrap_or(i);
                            let field =
                                if let mir::AggregateKind::Array(_) = **kind {
                                    let llindex =
                                        bx.cx().const_usize(field_index.as_u32().into());
                                    variant_dest.project_index(bx, llindex)
                                } else {
                                    variant_dest.project_field(bx, field_index.as_usize())
                                };
                            op.store_with_annotation(bx, field);
                        }
                    }
                    dest.codegen_set_discr(bx, variant_index);
                }
                _ => {
                    let temp = self.codegen_rvalue_operand(bx, rvalue);
                    temp.store_with_annotation(bx, dest);
                }
            }
        }
    }
}#[instrument(level = "trace", skip(self, bx))]
102    pub(crate) fn codegen_rvalue(
103        &mut self,
104        bx: &mut Bx,
105        dest: PlaceRef<'tcx, Bx::Value>,
106        rvalue: &mir::Rvalue<'tcx>,
107    ) {
108        match *rvalue {
109            mir::Rvalue::Use(ref operand, with_retag) => {
110                if self.is_entirely_uninit_const(operand) {
111                    return;
112                }
113                let cg_operand = self.codegen_operand(bx, operand);
114                // Crucially, we do *not* use `OperandValue::Ref` for types with
115                // `BackendRepr::Scalar | BackendRepr::ScalarPair`. This ensures we match the MIR
116                // semantics regarding when assignment operators allow overlap of LHS and RHS.
117                if matches!(
118                    cg_operand.layout.backend_repr,
119                    BackendRepr::Scalar(..) | BackendRepr::ScalarPair { .. },
120                ) {
121                    debug_assert!(!matches!(cg_operand.val, OperandValue::Ref(..)));
122                }
123                // If this is storing a &Freeze reference with a retag, record that it's not
124                // possible to perform writes through the stored pointer.
125                let flags = if let ty::Ref(_, pointee_ty, Mutability::Not) =
126                    cg_operand.layout.ty.kind()
127                    && with_retag.yes()
128                    && pointee_ty.is_freeze(self.cx.tcx(), self.cx.typing_env())
129                {
130                    MemFlags::CAPTURES_READ_ONLY
131                } else {
132                    MemFlags::empty()
133                };
134                // FIXME: consider not copying constants through stack. (Fixable by codegen'ing
135                // constants into `OperandValue::Ref`; why don’t we do that yet if we don’t?)
136                cg_operand.store_with_annotation_and_flags(bx, dest, flags);
137            }
138
139            mir::Rvalue::Cast(
140                mir::CastKind::PointerCoercion(PointerCoercion::Unsize, _),
141                ref source,
142                _,
143            ) => {
144                // The destination necessarily contains a wide pointer, so if
145                // it's a scalar pair, it's a wide pointer or newtype thereof.
146                if let BackendRepr::ScalarPair { .. } = dest.layout.backend_repr {
147                    // Into-coerce of a thin pointer to a wide pointer -- just
148                    // use the operand path.
149                    let temp = self.codegen_rvalue_operand(bx, rvalue);
150                    temp.store_with_annotation(bx, dest);
151                    return;
152                }
153
154                // Unsize of a nontrivial struct. I would prefer for
155                // this to be eliminated by MIR building, but
156                // `CoerceUnsized` can be passed by a where-clause,
157                // so the (generic) MIR may not be able to expand it.
158                let operand = self.codegen_operand(bx, source);
159                match operand.val {
160                    OperandValue::Pair(..) | OperandValue::Immediate(_) => {
161                        // Unsize from an immediate structure. We don't
162                        // really need a temporary alloca here, but
163                        // avoiding it would require us to have
164                        // `coerce_unsized_into` use `extractvalue` to
165                        // index into the struct, and this case isn't
166                        // important enough for it.
167                        debug!("codegen_rvalue: creating ugly alloca");
168                        let scratch = PlaceRef::alloca(bx, operand.layout);
169                        scratch.storage_live(bx);
170                        operand.store_with_annotation(bx, scratch);
171                        base::coerce_unsized_into(bx, scratch, dest);
172                        scratch.storage_dead(bx);
173                    }
174                    OperandValue::Ref(val) => {
175                        if val.llextra.is_some() {
176                            bug!("unsized coercion on an unsized rvalue");
177                        }
178                        base::coerce_unsized_into(bx, val.with_type(operand.layout), dest);
179                    }
180                    OperandValue::ZeroSized => {
181                        bug!("unsized coercion on a ZST rvalue");
182                    }
183                }
184            }
185
186            mir::Rvalue::Cast(
187                mir::CastKind::Transmute | mir::CastKind::Subtype,
188                ref operand,
189                _ty,
190            ) => {
191                let src = self.codegen_operand(bx, operand);
192                self.codegen_transmute(bx, src, dest);
193            }
194
195            mir::Rvalue::Repeat(ref elem, count) => {
196                // Do not generate the loop for zero-sized elements or empty arrays.
197                if dest.layout.is_zst() {
198                    return;
199                }
200
201                // When the element is a const with all bytes uninit, emit a single memset that
202                // writes undef to the entire destination.
203                if self.is_entirely_uninit_const(elem) {
204                    let size = bx.const_usize(dest.layout.size.bytes());
205                    bx.memset(
206                        dest.val.llval,
207                        bx.const_undef(bx.type_i8()),
208                        size,
209                        dest.val.align,
210                        MemFlags::empty(),
211                    );
212                    return;
213                }
214
215                let cg_elem = self.codegen_operand(bx, elem);
216
217                let try_init_all_same = |bx: &mut Bx, v| {
218                    let start = dest.val.llval;
219                    let size = bx.const_usize(dest.layout.size.bytes());
220
221                    // Use llvm.memset.p0i8.* to initialize all same byte arrays
222                    if let Some(int) = bx.cx().const_to_opt_u128(v, false)
223                        && let bytes = &int.to_le_bytes()[..cg_elem.layout.size.bytes_usize()]
224                        && let Ok(&byte) = bytes.iter().all_equal_value()
225                    {
226                        let fill = bx.cx().const_u8(byte);
227                        bx.memset(start, fill, size, dest.val.align, MemFlags::empty());
228                        return true;
229                    }
230
231                    // Use llvm.memset.p0i8.* to initialize byte arrays
232                    let v = bx.from_immediate(v);
233                    if bx.cx().val_ty(v) == bx.cx().type_i8() {
234                        bx.memset(start, v, size, dest.val.align, MemFlags::empty());
235                        return true;
236                    }
237                    false
238                };
239
240                if let OperandValue::Immediate(v) = cg_elem.val
241                    && try_init_all_same(bx, v)
242                {
243                    return;
244                }
245
246                let count = self
247                    .monomorphize(count)
248                    .try_to_target_usize(bx.tcx())
249                    .expect("expected monomorphic const in codegen");
250
251                bx.write_operand_repeatedly(cg_elem, count, dest);
252            }
253
254            // This implementation does field projection, so never use it for `RawPtr`,
255            // which will always be fine with the `codegen_rvalue_operand` path below.
256            mir::Rvalue::Aggregate(ref kind, ref operands)
257                if !matches!(**kind, mir::AggregateKind::RawPtr(..)) =>
258            {
259                if self.try_codegen_const_aggregate_as_immediate(bx, dest, kind, operands) {
260                    return;
261                }
262
263                let (variant_index, variant_dest, active_field_index) = match **kind {
264                    mir::AggregateKind::Adt(_, variant_index, _, _, active_field_index) => {
265                        let variant_dest = dest.project_downcast(bx, variant_index);
266                        (variant_index, variant_dest, active_field_index)
267                    }
268                    _ => (FIRST_VARIANT, dest, None),
269                };
270                if active_field_index.is_some() {
271                    assert_eq!(operands.len(), 1);
272                }
273                for (i, operand) in operands.iter_enumerated() {
274                    // Do not generate stores for entirely uninit constant fields, for the same
275                    // reason as in `Rvalue::Use` above.
276                    if self.is_entirely_uninit_const(operand) {
277                        continue;
278                    }
279                    let op = self.codegen_operand(bx, operand);
280                    // Do not generate stores and GEPis for zero-sized fields.
281                    if !op.layout.is_zst() {
282                        let field_index = active_field_index.unwrap_or(i);
283                        let field = if let mir::AggregateKind::Array(_) = **kind {
284                            let llindex = bx.cx().const_usize(field_index.as_u32().into());
285                            variant_dest.project_index(bx, llindex)
286                        } else {
287                            variant_dest.project_field(bx, field_index.as_usize())
288                        };
289                        op.store_with_annotation(bx, field);
290                    }
291                }
292                dest.codegen_set_discr(bx, variant_index);
293            }
294
295            _ => {
296                let temp = self.codegen_rvalue_operand(bx, rvalue);
297                temp.store_with_annotation(bx, dest);
298            }
299        }
300    }
301
302    /// Transmutes the `src` value to the destination type by writing it to `dst`.
303    ///
304    /// See also [`Self::codegen_transmute_operand`] for cases that can be done
305    /// without needing a pre-allocated place for the destination.
306    fn codegen_transmute(
307        &mut self,
308        bx: &mut Bx,
309        src: OperandRef<'tcx, Bx::Value>,
310        dst: PlaceRef<'tcx, Bx::Value>,
311    ) {
312        // The MIR validator enforces no unsized transmutes.
313        if !src.layout.is_sized() {
    ::core::panicking::panic("assertion failed: src.layout.is_sized()")
};assert!(src.layout.is_sized());
314        if !dst.layout.is_sized() {
    ::core::panicking::panic("assertion failed: dst.layout.is_sized()")
};assert!(dst.layout.is_sized());
315
316        if src.layout.size != dst.layout.size
317            || src.layout.is_uninhabited()
318            || dst.layout.is_uninhabited()
319        {
320            // These cases are all UB to actually hit, so don't emit code for them.
321            // (The size mismatches are reachable via `transmute_unchecked`.)
322            bx.unreachable_nonterminator();
323        } else {
324            // Since in this path we have a place anyway, we can store or copy to it,
325            // making sure we use the destination place's alignment even if the
326            // source would normally have a higher one.
327            src.store_with_annotation(bx, dst.val.with_type(src.layout));
328        }
329    }
330
331    /// Transmutes an `OperandValue` to another `OperandValue`.
332    ///
333    /// This is supported for all cases where the `cast` type is SSA,
334    /// but for non-ZSTs with [`abi::BackendRepr::Memory`] it ICEs.
335    pub(crate) fn codegen_transmute_operand(
336        &mut self,
337        bx: &mut Bx,
338        operand: OperandRef<'tcx, Bx::Value>,
339        cast: TyAndLayout<'tcx>,
340    ) -> OperandValue<Bx::Value> {
341        if let abi::BackendRepr::Memory { .. } = cast.backend_repr
342            && !cast.is_zst()
343        {
344            ::rustc_span::macros::bug_impl(Some(self.mir.span),
    format_args!("Use `codegen_transmute` to transmute to {0:?}", cast),
    Location::caller());span_bug!(self.mir.span, "Use `codegen_transmute` to transmute to {cast:?}");
345        }
346
347        // `Layout` is interned, so we can do a cheap check for things that are
348        // exactly the same and thus don't need any handling.
349        if abi::Layout::eq(&operand.layout.layout, &cast.layout) {
350            return operand.val;
351        }
352
353        // Check for transmutes that are always UB.
354        if operand.layout.size != cast.size
355            || operand.layout.is_uninhabited()
356            || cast.is_uninhabited()
357        {
358            bx.unreachable_nonterminator();
359
360            // We still need to return a value of the appropriate type, but
361            // it's already UB so do the easiest thing available.
362            return OperandValue::poison(bx, cast);
363        }
364
365        // To or from pointers takes different methods, so we use this to restrict
366        // the SimdVector case to types which can be `bitcast` between each other.
367        #[inline]
368        fn vector_can_bitcast(x: abi::Scalar) -> bool {
369            #[allow(non_exhaustive_omitted_patterns)] match x {
    abi::Scalar::Initialized {
        value: abi::Primitive::Int(..) | abi::Primitive::Float(..), .. } =>
        true,
    _ => false,
}matches!(
370                x,
371                abi::Scalar::Initialized {
372                    value: abi::Primitive::Int(..) | abi::Primitive::Float(..),
373                    ..
374                }
375            )
376        }
377
378        let cx = bx.cx();
379        match (operand.val, operand.layout.backend_repr, cast.backend_repr) {
380            _ if cast.is_zst() => OperandValue::ZeroSized,
381            (OperandValue::Ref(source_place_val), abi::BackendRepr::Memory { .. }, _) => {
382                {
    match (&source_place_val.llextra, &None) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(source_place_val.llextra, None);
383                // The existing alignment is part of `source_place_val`,
384                // so that alignment will be used, not `cast`'s.
385                bx.load_operand(source_place_val.with_type(cast)).val
386            }
387            (
388                OperandValue::Immediate(imm),
389                abi::BackendRepr::Scalar(from_scalar),
390                abi::BackendRepr::Scalar(to_scalar),
391            ) if from_scalar.size(cx) == to_scalar.size(cx) => {
392                OperandValue::Immediate(transmute_scalar(bx, imm, from_scalar, to_scalar))
393            }
394            (
395                OperandValue::Immediate(imm),
396                abi::BackendRepr::SimdVector { element: from_scalar, .. },
397                abi::BackendRepr::SimdVector { element: to_scalar, .. },
398            ) if vector_can_bitcast(from_scalar) && vector_can_bitcast(to_scalar) => {
399                let to_backend_ty = bx.cx().immediate_backend_type(cast);
400                OperandValue::Immediate(bx.bitcast(imm, to_backend_ty))
401            }
402            (
403                OperandValue::Immediate(imm),
404                abi::BackendRepr::SimdScalableVector { element: from_scalar, .. },
405                abi::BackendRepr::SimdScalableVector { element: to_scalar, .. },
406            ) if vector_can_bitcast(from_scalar) && vector_can_bitcast(to_scalar) => {
407                let to_backend_ty = bx.cx().immediate_backend_type(cast);
408                OperandValue::Immediate(bx.bitcast(imm, to_backend_ty))
409            }
410            (
411                OperandValue::Pair(imm_a, imm_b),
412                abi::BackendRepr::ScalarPair { a: in_a, b: in_b, b_offset: in_offset },
413                abi::BackendRepr::ScalarPair { a: out_a, b: out_b, b_offset: out_offset },
414            ) if in_a.size(cx) == out_a.size(cx)
415                && in_b.size(cx) == out_b.size(cx)
416                && in_offset == out_offset =>
417            {
418                OperandValue::Pair(
419                    transmute_scalar(bx, imm_a, in_a, out_a),
420                    transmute_scalar(bx, imm_b, in_b, out_b),
421                )
422            }
423            _ => {
424                // For any other potentially-tricky cases, make a temporary instead.
425                // If anything else wants the target local to be in memory this won't
426                // be hit, as `codegen_transmute` will get called directly. Thus this
427                // is only for places where everything else wants the operand form,
428                // and thus it's not worth making those places get it from memory.
429                //
430                // Notably, Scalar ⇌ ScalarPair cases go here to avoid padding
431                // and endianness issues, as do SimdVector ones to avoid worrying
432                // about things like f32x8 ⇌ ptrx4 that would need multiple steps.
433                let align = Ord::max(operand.layout.align, cast.align);
434                let size = Ord::max(operand.layout.size, cast.size);
435                let temp = PlaceValue::alloca(bx, size, align);
436                bx.lifetime_start(temp.llval, size);
437                operand.store_with_annotation(bx, temp.with_type(operand.layout));
438                let val = bx.load_operand(temp.with_type(cast)).val;
439                bx.lifetime_end(temp.llval, size);
440                val
441            }
442        }
443    }
444
445    /// Cast one of the immediates from an [`OperandValue::Immediate`]
446    /// or an [`OperandValue::Pair`] to an immediate of the target type.
447    ///
448    /// Returns `None` if the cast is not possible.
449    fn cast_immediate(
450        &self,
451        bx: &mut Bx,
452        mut imm: Bx::Value,
453        from_scalar: abi::Scalar,
454        from_backend_ty: Bx::Type,
455        to_scalar: abi::Scalar,
456        to_backend_ty: Bx::Type,
457    ) -> Option<Bx::Value> {
458        use abi::Primitive::*;
459
460        // When scalars are passed by value, there's no metadata recording their
461        // valid ranges. For example, `char`s are passed as just `i32`, with no
462        // way for LLVM to know that they're 0x10FFFF at most. Thus we assume
463        // the range of the input value too, not just the output range.
464        assume_scalar_range(bx, imm, from_scalar, from_backend_ty, None);
465
466        imm = match (from_scalar.primitive(), to_scalar.primitive()) {
467            (Int(_, is_signed), Int(..)) => bx.intcast(imm, to_backend_ty, is_signed),
468            (Bool, Int(..)) | (Int(..), Bool) | (Bool, Bool) => {
469                bx.intcast(imm, to_backend_ty, false)
470            }
471            (Float(src), Float(dst)) => match dst.size().cmp(&src.size()) {
472                Ordering::Greater => bx.fpext(imm, to_backend_ty),
473                Ordering::Less => bx.fptrunc(imm, to_backend_ty),
474                Ordering::Equal => imm,
475            },
476            (Int(_, is_signed), Float(_)) => {
477                if is_signed {
478                    bx.sitofp(imm, to_backend_ty)
479                } else {
480                    bx.uitofp(imm, to_backend_ty)
481                }
482            }
483            (Pointer(..), Pointer(..)) => bx.pointercast(imm, to_backend_ty),
484            (Int(_, is_signed), Pointer(..)) => {
485                let usize_imm = bx.intcast(imm, bx.cx().type_isize(), is_signed);
486                bx.inttoptr(usize_imm, to_backend_ty)
487            }
488            (Float(_), Int(_, is_signed)) => bx.cast_float_to_int(is_signed, imm, to_backend_ty),
489            (Bool, Float(..))
490            | (Float(..), Bool)
491            | (Bool, Pointer(..))
492            | (Pointer(..), Bool)
493            | (Pointer(..), Float(..))
494            | (Pointer(..), Int(..))
495            | (Float(..), Pointer(..)) => {
496                return None;
497            }
498        };
499        Some(imm)
500    }
501
502    pub(crate) fn codegen_rvalue_operand(
503        &mut self,
504        bx: &mut Bx,
505        rvalue: &mir::Rvalue<'tcx>,
506    ) -> OperandRef<'tcx, Bx::Value> {
507        match *rvalue {
508            mir::Rvalue::Cast(ref kind, ref source, mir_cast_ty) => {
509                let operand = self.codegen_operand(bx, source);
510                {
    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/rvalue.rs:510",
                        "rustc_codegen_ssa::mir::rvalue", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/6c709eb428d472a3c3d93681c1ba37d44a1c27cf/compiler/rustc_codegen_ssa/src/mir/rvalue.rs"),
                        ::tracing_core::__macro_support::Option::Some(510u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::rvalue"),
                        ::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!("cast operand is {0:?}",
                                                    operand) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("cast operand is {:?}", operand);
511                let cast = bx.cx().layout_of(self.monomorphize(mir_cast_ty));
512
513                let val = match *kind {
514                    mir::CastKind::PointerExposeProvenance => {
515                        if !cast.backend_repr.is_scalar_or_simd() {
    ::core::panicking::panic("assertion failed: cast.backend_repr.is_scalar_or_simd()")
};assert!(cast.backend_repr.is_scalar_or_simd());
516                        let llptr = operand.immediate();
517                        let llcast_ty = bx.cx().immediate_backend_type(cast);
518                        let lladdr = bx.ptrtoint(llptr, llcast_ty);
519                        OperandValue::Immediate(lladdr)
520                    }
521                    mir::CastKind::PointerCoercion(PointerCoercion::ReifyFnPointer(_), _) => {
522                        match *operand.layout.ty.kind() {
523                            ty::FnDef(def_id, args) => {
524                                let instance = ty::Instance::resolve_for_fn_ptr(
525                                    bx.tcx(),
526                                    bx.typing_env(),
527                                    def_id,
528                                    args.no_bound_vars().unwrap(),
529                                )
530                                .unwrap();
531                                OperandValue::Immediate(
532                                    bx.get_fn_addr(
533                                        instance,
534                                        bx.sess().pointer_authentication_functions(),
535                                    ),
536                                )
537                            }
538                            _ => ::rustc_span::macros::bug_impl(None,
    format_args!("{0} cannot be reified to a fn ptr", operand.layout.ty),
    Location::caller())bug!("{} cannot be reified to a fn ptr", operand.layout.ty),
539                        }
540                    }
541                    mir::CastKind::PointerCoercion(PointerCoercion::ClosureFnPointer(_), _) => {
542                        match *operand.layout.ty.kind() {
543                            ty::Closure(def_id, args) => {
544                                let instance = Instance::resolve_closure(
545                                    bx.cx().tcx(),
546                                    def_id,
547                                    args,
548                                    ty::ClosureKind::FnOnce,
549                                );
550                                OperandValue::Immediate(
551                                    bx.cx().get_fn_addr(
552                                        instance,
553                                        bx.sess().pointer_authentication_functions(),
554                                    ),
555                                )
556                            }
557                            _ => ::rustc_span::macros::bug_impl(None,
    format_args!("{0} cannot be cast to a fn ptr", operand.layout.ty),
    Location::caller())bug!("{} cannot be cast to a fn ptr", operand.layout.ty),
558                        }
559                    }
560                    mir::CastKind::PointerCoercion(PointerCoercion::UnsafeFnPointer, _) => {
561                        // This is a no-op at the LLVM level.
562                        operand.val
563                    }
564                    mir::CastKind::PointerCoercion(PointerCoercion::Unsize, _) => {
565                        {
    match cast.backend_repr {
        BackendRepr::ScalarPair { .. } => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "BackendRepr::ScalarPair { .. }",
                ::core::option::Option::None);
        }
    }
};assert_matches!(cast.backend_repr, BackendRepr::ScalarPair { .. });
566                        let (lldata, llextra) = operand.val.pointer_parts();
567                        let (lldata, llextra) =
568                            base::unsize_ptr(bx, lldata, operand.layout.ty, cast.ty, llextra);
569                        OperandValue::Pair(lldata, llextra)
570                    }
571                    mir::CastKind::PointerCoercion(
572                        PointerCoercion::MutToConstPointer | PointerCoercion::ArrayToPointer,
573                        _,
574                    ) => {
575                        ::rustc_span::macros::bug_impl(None,
    format_args!("{0:?} is for borrowck, and should never appear in codegen",
        kind), Location::caller());bug!("{kind:?} is for borrowck, and should never appear in codegen");
576                    }
577                    mir::CastKind::PtrToPtr if let BackendRepr::ScalarPair { .. } = operand.layout.backend_repr => {
578                        if let OperandValue::Pair(data_ptr, meta) = operand.val {
579                            if let BackendRepr::ScalarPair { .. } = cast.layout.backend_repr {
580                                OperandValue::Pair(data_ptr, meta)
581                            } else {
582                                // Cast of wide-ptr to thin-ptr is an extraction of data-ptr.
583                                OperandValue::Immediate(data_ptr)
584                            }
585                        } else {
586                            ::rustc_span::macros::bug_impl(None,
    format_args!("unexpected non-pair operand"), Location::caller());bug!("unexpected non-pair operand");
587                        }
588                    }
589                    | mir::CastKind::IntToInt
590                    | mir::CastKind::FloatToInt
591                    | mir::CastKind::FloatToFloat
592                    | mir::CastKind::IntToFloat
593                    | mir::CastKind::PtrToPtr
594                    | mir::CastKind::FnPtrToPtr
595                    // Since int2ptr can have arbitrary integer types as input (so we have to do
596                    // sign extension and all that), it is currently best handled in the same code
597                    // path as the other integer-to-X casts.
598                    | mir::CastKind::PointerWithExposedProvenance => {
599                        let imm = operand.immediate();
600                        let abi::BackendRepr::Scalar(from_scalar) = operand.layout.backend_repr
601                        else {
602                            ::rustc_span::macros::bug_impl(None,
    format_args!("Found non-scalar for operand {0:?}", operand),
    Location::caller());bug!("Found non-scalar for operand {operand:?}");
603                        };
604                        let from_backend_ty = bx.cx().immediate_backend_type(operand.layout);
605
606                        if !cast.backend_repr.is_scalar_or_simd() {
    ::core::panicking::panic("assertion failed: cast.backend_repr.is_scalar_or_simd()")
};assert!(cast.backend_repr.is_scalar_or_simd());
607                        let to_backend_ty = bx.cx().immediate_backend_type(cast);
608                        if operand.layout.is_uninhabited() {
609                            let val = OperandValue::Immediate(bx.cx().const_poison(to_backend_ty));
610                            return OperandRef { val, layout: cast, move_annotation: None };
611                        }
612                        let abi::BackendRepr::Scalar(to_scalar) = cast.layout.backend_repr else {
613                            ::rustc_span::macros::bug_impl(None,
    format_args!("Found non-scalar for cast {0:?}", cast),
    Location::caller());bug!("Found non-scalar for cast {cast:?}");
614                        };
615
616                        self.cast_immediate(
617                            bx,
618                            imm,
619                            from_scalar,
620                            from_backend_ty,
621                            to_scalar,
622                            to_backend_ty,
623                        )
624                        .map(OperandValue::Immediate)
625                        .unwrap_or_else(|| {
626                            ::rustc_span::macros::bug_impl(None,
    format_args!("Unsupported cast of {0:?} to {1:?}", operand, cast),
    Location::caller());bug!("Unsupported cast of {operand:?} to {cast:?}");
627                        })
628                    }
629                    mir::CastKind::Transmute | mir::CastKind::BoxDerefTransmute | mir::CastKind::Subtype => {
630                        self.codegen_transmute_operand(bx, operand, cast)
631                    }
632                };
633                OperandRef { val, layout: cast, move_annotation: None }
634            }
635
636            mir::Rvalue::Ref(_, bk, place) => {
637                let mk_ref = move |tcx: TyCtxt<'tcx>, ty: Ty<'tcx>| {
638                    Ty::new_ref(tcx, tcx.lifetimes.re_erased, ty, bk.to_mutbl_lossy())
639                };
640                let op = self.codegen_place_to_pointer(bx, place, mk_ref);
641                if self.cx.tcx().sess.opts.unstable_opts.codegen_emit_retag.is_some() {
642                    self.codegen_retag_operand(bx, op, false)
643                } else {
644                    op
645                }
646            }
647
648            // Note: Exclusive reborrowing is always equal to a memcpy, as the types do not change.
649            // Generic shared reborrowing is not (necessarily) a simple memcpy, but currently the
650            // coherence check places such restrictions on the CoerceShared trait as to guarantee
651            // that it is.
652            mir::Rvalue::Reborrow(_, _, place) => {
653                self.codegen_operand(bx, &mir::Operand::Copy(place))
654            }
655
656            mir::Rvalue::RawPtr(kind, place) => {
657                let mk_ptr = move |tcx: TyCtxt<'tcx>, ty: Ty<'tcx>| {
658                    Ty::new_ptr(tcx, ty, kind.to_mutbl_lossy())
659                };
660                self.codegen_place_to_pointer(bx, place, mk_ptr)
661            }
662
663            mir::Rvalue::BinaryOp(op_with_overflow, (ref lhs, ref rhs))
664                if let Some(op) = op_with_overflow.overflowing_to_wrapping() =>
665            {
666                let lhs = self.codegen_operand(bx, lhs);
667                let rhs = self.codegen_operand(bx, rhs);
668                let result = self.codegen_scalar_checked_binop(
669                    bx,
670                    op,
671                    lhs.immediate(),
672                    rhs.immediate(),
673                    lhs.layout.ty,
674                );
675                let val_ty = op.ty(bx.tcx(), lhs.layout.ty, rhs.layout.ty);
676                let operand_ty = Ty::new_tup(bx.tcx(), &[val_ty, bx.tcx().types.bool]);
677                OperandRef {
678                    val: result,
679                    layout: bx.cx().layout_of(operand_ty),
680                    move_annotation: None,
681                }
682            }
683
684            mir::Rvalue::BinaryOp(op, (ref lhs, ref rhs)) => {
685                let lhs = self.codegen_operand(bx, lhs);
686                let rhs = self.codegen_operand(bx, rhs);
687                let llresult = match (lhs.val, rhs.val) {
688                    (
689                        OperandValue::Pair(lhs_addr, lhs_extra),
690                        OperandValue::Pair(rhs_addr, rhs_extra),
691                    ) => self.codegen_wide_ptr_binop(
692                        bx,
693                        op,
694                        lhs_addr,
695                        lhs_extra,
696                        rhs_addr,
697                        rhs_extra,
698                        lhs.layout.ty,
699                    ),
700
701                    (OperandValue::Immediate(lhs_val), OperandValue::Immediate(rhs_val)) => self
702                        .codegen_scalar_binop(
703                            bx,
704                            op,
705                            lhs_val,
706                            rhs_val,
707                            lhs.layout.ty,
708                            rhs.layout.ty,
709                        ),
710
711                    _ => ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller())bug!(),
712                };
713                OperandRef {
714                    val: OperandValue::Immediate(llresult),
715                    layout: bx.cx().layout_of(op.ty(bx.tcx(), lhs.layout.ty, rhs.layout.ty)),
716                    move_annotation: None,
717                }
718            }
719
720            mir::Rvalue::UnaryOp(op, ref operand) => {
721                let operand = self.codegen_operand(bx, operand);
722                let is_float = operand.layout.ty.is_floating_point();
723                let (val, layout) = match op {
724                    mir::UnOp::Not => {
725                        let llval = bx.not(operand.immediate());
726                        (OperandValue::Immediate(llval), operand.layout)
727                    }
728                    mir::UnOp::Neg => {
729                        let llval = if is_float {
730                            bx.fneg(operand.immediate())
731                        } else {
732                            bx.neg(operand.immediate())
733                        };
734                        (OperandValue::Immediate(llval), operand.layout)
735                    }
736                    mir::UnOp::PtrMetadata => {
737                        if !(operand.layout.ty.is_raw_ptr() || operand.layout.ty.is_ref()) {
    ::core::panicking::panic("assertion failed: operand.layout.ty.is_raw_ptr() || operand.layout.ty.is_ref()")
};assert!(operand.layout.ty.is_raw_ptr() || operand.layout.ty.is_ref(),);
738                        let (_, meta) = operand.val.pointer_parts();
739                        {
    match (&(operand.layout.fields.count() > 1), &meta.is_some()) {
        (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!(operand.layout.fields.count() > 1, meta.is_some());
740                        if let Some(meta) = meta {
741                            (OperandValue::Immediate(meta), operand.layout.field(self.cx, 1))
742                        } else {
743                            (OperandValue::ZeroSized, bx.cx().layout_of(bx.tcx().types.unit))
744                        }
745                    }
746                };
747                if !val.is_expected_variant_for_type(layout) {
    {
        ::core::panicking::panic_fmt(format_args!("Made wrong variant {0:?} for type {1:?}",
                val, layout));
    }
};assert!(
748                    val.is_expected_variant_for_type(layout),
749                    "Made wrong variant {val:?} for type {layout:?}",
750                );
751                OperandRef { val, layout, move_annotation: None }
752            }
753
754            mir::Rvalue::Discriminant(ref place) => {
755                let discr_ty = rvalue.ty(self.mir, bx.tcx());
756                let discr_ty = self.monomorphize(discr_ty);
757                let operand = self.codegen_consume(bx, place.as_ref());
758                let discr = operand.codegen_get_discr(self, bx, discr_ty);
759                OperandRef {
760                    val: OperandValue::Immediate(discr),
761                    layout: self.cx.layout_of(discr_ty),
762                    move_annotation: None,
763                }
764            }
765
766            mir::Rvalue::ThreadLocalRef(def_id) => {
767                if !bx.cx().tcx().is_static(def_id) {
    ::core::panicking::panic("assertion failed: bx.cx().tcx().is_static(def_id)")
};assert!(bx.cx().tcx().is_static(def_id));
768                let layout = bx.layout_of(bx.cx().tcx().static_ptr_ty(def_id, bx.typing_env()));
769                let static_ = if !def_id.is_local() && bx.cx().tcx().needs_thread_local_shim(def_id)
770                {
771                    let instance = ty::Instance {
772                        def: ty::InstanceKind::Shim(ty::ShimKind::ThreadLocal(def_id)),
773                        args: ty::GenericArgs::empty(),
774                    };
775                    let fn_ptr =
776                        bx.get_fn_addr(instance, bx.sess().pointer_authentication_functions());
777                    let fn_abi = bx.fn_abi_of_instance(instance, ty::List::empty());
778                    let fn_ty = bx.fn_decl_backend_type(fn_abi);
779                    let fn_attrs = if bx.tcx().def_kind(instance.def_id()).has_codegen_attrs() {
780                        Some(bx.tcx().codegen_instance_attrs(instance.def))
781                    } else {
782                        None
783                    };
784                    bx.call(
785                        fn_ty,
786                        fn_attrs.as_deref(),
787                        Some(fn_abi),
788                        fn_ptr,
789                        ReturnSlot::Direct,
790                        &[],
791                        None,
792                        Some(instance),
793                    )
794                } else {
795                    bx.get_static(def_id)
796                };
797                OperandRef { val: OperandValue::Immediate(static_), layout, move_annotation: None }
798            }
799
800            mir::Rvalue::Use(ref operand, _) => self.codegen_operand(bx, operand),
801
802            mir::Rvalue::Repeat(ref elem, len_const) => {
803                // All arrays have `BackendRepr::Memory`, so only the ZST cases
804                // end up here. Anything else forces the destination local to be
805                // `Memory`, and thus ends up handled in `codegen_rvalue` instead.
806                let operand = self.codegen_operand(bx, elem);
807                let array_ty = Ty::new_array_with_const_len(bx.tcx(), operand.layout.ty, len_const);
808                let array_ty = self.monomorphize(array_ty);
809                let array_layout = bx.layout_of(array_ty);
810                if !array_layout.is_zst() {
    ::core::panicking::panic("assertion failed: array_layout.is_zst()")
};assert!(array_layout.is_zst());
811                OperandRef {
812                    val: OperandValue::ZeroSized,
813                    layout: array_layout,
814                    move_annotation: None,
815                }
816            }
817
818            mir::Rvalue::Aggregate(ref kind, ref fields) => {
819                let (variant_index, active_field_index) = match **kind {
820                    mir::AggregateKind::Adt(_, variant_index, _, _, active_field_index) => {
821                        (variant_index, active_field_index)
822                    }
823                    _ => (FIRST_VARIANT, None),
824                };
825
826                let ty = rvalue.ty(self.mir, self.cx.tcx());
827                let ty = self.monomorphize(ty);
828                let layout = self.cx.layout_of(ty);
829
830                let mut builder = OperandRefBuilder::new(layout);
831                for (field_idx, field) in fields.iter_enumerated() {
832                    let op = self.codegen_operand(bx, field);
833                    let fi = active_field_index.unwrap_or(field_idx);
834                    builder.insert_field(bx, variant_index, fi, op);
835                }
836
837                let tag_result = codegen_tag_value(self.cx, variant_index, layout);
838                match tag_result {
839                    Err(super::place::UninhabitedVariantError) => {
840                        // Like codegen_set_discr we use a sound abort, but could
841                        // potentially `unreachable` or just return the poison for
842                        // optimizability, if that turns out to be helpful.
843                        bx.abort_immediate();
844                        let val = OperandValue::poison(bx, layout);
845                        OperandRef { val, layout, move_annotation: None }
846                    }
847                    Ok(maybe_tag_value) => {
848                        if let Some((tag_field, tag_imm)) = maybe_tag_value {
849                            builder.insert_imm(tag_field, tag_imm);
850                        }
851                        builder.build(bx.cx())
852                    }
853                }
854            }
855
856            mir::Rvalue::WrapUnsafeBinder(ref operand, binder_ty) => {
857                let operand = self.codegen_operand(bx, operand);
858                let binder_ty = self.monomorphize(binder_ty);
859                let layout = bx.cx().layout_of(binder_ty);
860                OperandRef { val: operand.val, layout, move_annotation: None }
861            }
862
863            mir::Rvalue::CopyForDeref(_) => ::rustc_span::macros::bug_impl(None,
    format_args!("`CopyForDeref` in codegen"), Location::caller())bug!("`CopyForDeref` in codegen"),
864        }
865    }
866
867    /// Codegen an `Rvalue::RawPtr` or `Rvalue::Ref`
868    fn codegen_place_to_pointer(
869        &mut self,
870        bx: &mut Bx,
871        place: mir::Place<'tcx>,
872        mk_ptr_ty: impl FnOnce(TyCtxt<'tcx>, Ty<'tcx>) -> Ty<'tcx>,
873    ) -> OperandRef<'tcx, Bx::Value> {
874        let cg_place = self.codegen_place(bx, place.as_ref());
875        let val = cg_place.val.address();
876
877        let ty = cg_place.layout.ty;
878        if !if bx.cx().tcx().type_has_metadata(ty, bx.cx().typing_env()) {

            #[allow(non_exhaustive_omitted_patterns)]
            match val { OperandValue::Pair(..) => true, _ => false, }
        } else {

            #[allow(non_exhaustive_omitted_patterns)]
            match val { OperandValue::Immediate(..) => true, _ => false, }
        } {
    {
        ::core::panicking::panic_fmt(format_args!("Address of place was unexpectedly {0:?} for pointee type {1:?}",
                val, ty));
    }
};assert!(
879            if bx.cx().tcx().type_has_metadata(ty, bx.cx().typing_env()) {
880                matches!(val, OperandValue::Pair(..))
881            } else {
882                matches!(val, OperandValue::Immediate(..))
883            },
884            "Address of place was unexpectedly {val:?} for pointee type {ty:?}",
885        );
886
887        OperandRef {
888            val,
889            layout: self.cx.layout_of(mk_ptr_ty(self.cx.tcx(), ty)),
890            move_annotation: None,
891        }
892    }
893
894    fn codegen_scalar_binop(
895        &mut self,
896        bx: &mut Bx,
897        op: mir::BinOp,
898        lhs: Bx::Value,
899        rhs: Bx::Value,
900        lhs_ty: Ty<'tcx>,
901        rhs_ty: Ty<'tcx>,
902    ) -> Bx::Value {
903        let is_float = lhs_ty.is_floating_point();
904        let is_signed = lhs_ty.is_signed();
905        match op {
906            mir::BinOp::Add => {
907                if is_float {
908                    bx.fadd(lhs, rhs)
909                } else {
910                    bx.add(lhs, rhs)
911                }
912            }
913            mir::BinOp::AddUnchecked => {
914                if is_signed {
915                    bx.unchecked_sadd(lhs, rhs)
916                } else {
917                    bx.unchecked_uadd(lhs, rhs)
918                }
919            }
920            mir::BinOp::Sub => {
921                if is_float {
922                    bx.fsub(lhs, rhs)
923                } else {
924                    bx.sub(lhs, rhs)
925                }
926            }
927            mir::BinOp::SubUnchecked => {
928                if is_signed {
929                    bx.unchecked_ssub(lhs, rhs)
930                } else {
931                    bx.unchecked_usub(lhs, rhs)
932                }
933            }
934            mir::BinOp::Mul => {
935                if is_float {
936                    bx.fmul(lhs, rhs)
937                } else {
938                    bx.mul(lhs, rhs)
939                }
940            }
941            mir::BinOp::MulUnchecked => {
942                if is_signed {
943                    bx.unchecked_smul(lhs, rhs)
944                } else {
945                    bx.unchecked_umul(lhs, rhs)
946                }
947            }
948            mir::BinOp::Div => {
949                if is_float {
950                    bx.fdiv(lhs, rhs)
951                } else if is_signed {
952                    bx.sdiv(lhs, rhs)
953                } else {
954                    bx.udiv(lhs, rhs)
955                }
956            }
957            mir::BinOp::Rem => {
958                if is_float {
959                    bx.frem(lhs, rhs)
960                } else if is_signed {
961                    bx.srem(lhs, rhs)
962                } else {
963                    bx.urem(lhs, rhs)
964                }
965            }
966            mir::BinOp::BitOr => bx.or(lhs, rhs),
967            mir::BinOp::BitAnd => bx.and(lhs, rhs),
968            mir::BinOp::BitXor => bx.xor(lhs, rhs),
969            mir::BinOp::Offset => {
970                let pointee_type = lhs_ty
971                    .builtin_deref(true)
972                    .unwrap_or_else(|| ::rustc_span::macros::bug_impl(None,
    format_args!("deref of non-pointer {0:?}", lhs_ty), Location::caller())bug!("deref of non-pointer {:?}", lhs_ty));
973                let pointee_layout = bx.cx().layout_of(pointee_type);
974                if pointee_layout.is_zst() {
975                    // `Offset` works in terms of the size of pointee,
976                    // so offsetting a pointer to ZST is a noop.
977                    lhs
978                } else {
979                    if !rhs_ty.is_signed() {
980                        bx.inbounds_nuw_gep(pointee_layout.size, lhs, rhs)
981                    } else {
982                        bx.inbounds_gep(pointee_layout.size, lhs, rhs)
983                    }
984                }
985            }
986            mir::BinOp::Shl | mir::BinOp::ShlUnchecked => {
987                let rhs = base::build_shift_expr_rhs(bx, lhs, rhs, op == mir::BinOp::ShlUnchecked);
988                bx.shl(lhs, rhs)
989            }
990            mir::BinOp::Shr | mir::BinOp::ShrUnchecked => {
991                let rhs = base::build_shift_expr_rhs(bx, lhs, rhs, op == mir::BinOp::ShrUnchecked);
992                if is_signed { bx.ashr(lhs, rhs) } else { bx.lshr(lhs, rhs) }
993            }
994            mir::BinOp::Ne
995            | mir::BinOp::Lt
996            | mir::BinOp::Gt
997            | mir::BinOp::Eq
998            | mir::BinOp::Le
999            | mir::BinOp::Ge => {
1000                if is_float {
1001                    bx.fcmp(base::bin_op_to_fcmp_predicate(op), lhs, rhs)
1002                } else {
1003                    bx.icmp(base::bin_op_to_icmp_predicate(op, is_signed), lhs, rhs)
1004                }
1005            }
1006            mir::BinOp::Cmp => {
1007                if !!is_float { ::core::panicking::panic("assertion failed: !is_float") };assert!(!is_float);
1008                bx.three_way_compare(lhs_ty, lhs, rhs)
1009            }
1010            mir::BinOp::AddWithOverflow
1011            | mir::BinOp::SubWithOverflow
1012            | mir::BinOp::MulWithOverflow => {
1013                ::rustc_span::macros::bug_impl(None,
    format_args!("{0:?} needs to return a pair, so call codegen_scalar_checked_binop instead",
        op), Location::caller())bug!("{op:?} needs to return a pair, so call codegen_scalar_checked_binop instead")
1014            }
1015        }
1016    }
1017
1018    fn codegen_wide_ptr_binop(
1019        &mut self,
1020        bx: &mut Bx,
1021        op: mir::BinOp,
1022        lhs_addr: Bx::Value,
1023        lhs_extra: Bx::Value,
1024        rhs_addr: Bx::Value,
1025        rhs_extra: Bx::Value,
1026        _input_ty: Ty<'tcx>,
1027    ) -> Bx::Value {
1028        match op {
1029            mir::BinOp::Eq => {
1030                let lhs = bx.icmp(IntPredicate::IntEQ, lhs_addr, rhs_addr);
1031                let rhs = bx.icmp(IntPredicate::IntEQ, lhs_extra, rhs_extra);
1032                bx.and(lhs, rhs)
1033            }
1034            mir::BinOp::Ne => {
1035                let lhs = bx.icmp(IntPredicate::IntNE, lhs_addr, rhs_addr);
1036                let rhs = bx.icmp(IntPredicate::IntNE, lhs_extra, rhs_extra);
1037                bx.or(lhs, rhs)
1038            }
1039            mir::BinOp::Le | mir::BinOp::Lt | mir::BinOp::Ge | mir::BinOp::Gt => {
1040                // a OP b ~ a.0 STRICT(OP) b.0 | (a.0 == b.0 && a.1 OP a.1)
1041                let (op, strict_op) = match op {
1042                    mir::BinOp::Lt => (IntPredicate::IntULT, IntPredicate::IntULT),
1043                    mir::BinOp::Le => (IntPredicate::IntULE, IntPredicate::IntULT),
1044                    mir::BinOp::Gt => (IntPredicate::IntUGT, IntPredicate::IntUGT),
1045                    mir::BinOp::Ge => (IntPredicate::IntUGE, IntPredicate::IntUGT),
1046                    _ => ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller())bug!(),
1047                };
1048                let lhs = bx.icmp(strict_op, lhs_addr, rhs_addr);
1049                let and_lhs = bx.icmp(IntPredicate::IntEQ, lhs_addr, rhs_addr);
1050                let and_rhs = bx.icmp(op, lhs_extra, rhs_extra);
1051                let rhs = bx.and(and_lhs, and_rhs);
1052                bx.or(lhs, rhs)
1053            }
1054            _ => {
1055                ::rustc_span::macros::bug_impl(None,
    format_args!("unexpected wide ptr binop"), Location::caller());bug!("unexpected wide ptr binop");
1056            }
1057        }
1058    }
1059
1060    fn codegen_scalar_checked_binop(
1061        &mut self,
1062        bx: &mut Bx,
1063        op: mir::BinOp,
1064        lhs: Bx::Value,
1065        rhs: Bx::Value,
1066        input_ty: Ty<'tcx>,
1067    ) -> OperandValue<Bx::Value> {
1068        let (val, of) = match op {
1069            // These are checked using intrinsics
1070            mir::BinOp::Add | mir::BinOp::Sub | mir::BinOp::Mul => {
1071                let oop = match op {
1072                    mir::BinOp::Add => OverflowOp::Add,
1073                    mir::BinOp::Sub => OverflowOp::Sub,
1074                    mir::BinOp::Mul => OverflowOp::Mul,
1075                    _ => ::core::panicking::unreachable_default_msg()unreachable!(),
1076                };
1077                bx.checked_binop(oop, input_ty, lhs, rhs)
1078            }
1079            _ => ::rustc_span::macros::bug_impl(None,
    format_args!("Operator `{0:?}` is not a checkable operator", op),
    Location::caller())bug!("Operator `{:?}` is not a checkable operator", op),
1080        };
1081
1082        OperandValue::Pair(val, of)
1083    }
1084}
1085
1086/// Transmutes a single scalar value `imm` from `from_scalar` to `to_scalar`.
1087///
1088/// This is expected to be in *immediate* form, as seen in [`OperandValue::Immediate`]
1089/// or [`OperandValue::Pair`] (so `i1` for bools, not `i8`, for example).
1090///
1091/// ICEs if the passed-in `imm` is not a value of the expected type for
1092/// `from_scalar`, such as if it's a vector or a pair.
1093pub(super) fn transmute_scalar<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
1094    bx: &mut Bx,
1095    mut imm: Bx::Value,
1096    from_scalar: abi::Scalar,
1097    to_scalar: abi::Scalar,
1098) -> Bx::Value {
1099    {
    match (&from_scalar.size(bx.cx()), &to_scalar.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!(from_scalar.size(bx.cx()), to_scalar.size(bx.cx()));
1100    let imm_ty = bx.cx().val_ty(imm);
1101    if !bx.cx().vector_element_type(imm_ty).is_none() {
    {
        ::core::panicking::panic_fmt(format_args!("Vector type {0:?} not allowed in transmute_scalar {1:?} -> {2:?}",
                imm_ty, from_scalar, to_scalar));
    }
};assert!(
1102        bx.cx().vector_element_type(imm_ty).is_none(),
1103        "Vector type {imm_ty:?} not allowed in transmute_scalar {from_scalar:?} -> {to_scalar:?}"
1104    );
1105
1106    // While optimizations will remove no-op transmutes, they might still be
1107    // there in debug or things that aren't no-op in MIR because they change
1108    // the Rust type but not the underlying layout/niche.
1109    if from_scalar == to_scalar {
1110        return imm;
1111    }
1112
1113    use abi::Primitive::*;
1114    imm = bx.from_immediate(imm);
1115
1116    let from_backend_ty = bx.cx().type_from_scalar(from_scalar);
1117    if true {
    {
        match (&bx.cx().val_ty(imm), &from_backend_ty) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(bx.cx().val_ty(imm), from_backend_ty);
1118    let to_backend_ty = bx.cx().type_from_scalar(to_scalar);
1119
1120    // If we have a scalar, we must already know its range. Either
1121    //
1122    // 1) It's a parameter with `range` parameter metadata,
1123    // 2) It's something we `load`ed with `!range` metadata, or
1124    // 3) After a transmute we `assume`d the range (see below).
1125    //
1126    // That said, last time we tried removing this, it didn't actually help
1127    // the rustc-perf results, so might as well keep doing it
1128    // <https://github.com/rust-lang/rust/pull/135610#issuecomment-2599275182>
1129    assume_scalar_range(bx, imm, from_scalar, from_backend_ty, Some(&to_scalar));
1130
1131    imm = match (from_scalar.primitive(), to_scalar.primitive()) {
1132        (Bool | Int(..) | Float(_), Bool | Int(..) | Float(_)) => bx.bitcast(imm, to_backend_ty),
1133        (Pointer(..), Pointer(..)) => bx.pointercast(imm, to_backend_ty),
1134        (Bool | Int(..), Pointer(..)) => bx.inttoptr(imm, to_backend_ty),
1135        (Pointer(..), Bool | Int(..)) => {
1136            // FIXME: this exposes the provenance, which shouldn't be necessary.
1137            bx.ptrtoint(imm, to_backend_ty)
1138        }
1139        (Float(_), Pointer(..)) => {
1140            let int_imm = bx.bitcast(imm, bx.cx().type_isize());
1141            bx.inttoptr(int_imm, to_backend_ty)
1142        }
1143        (Pointer(..), Float(_)) => {
1144            // FIXME: this exposes the provenance, which shouldn't be necessary.
1145            let int_imm = bx.ptrtoint(imm, bx.cx().type_isize());
1146            bx.bitcast(int_imm, to_backend_ty)
1147        }
1148    };
1149
1150    if true {
    {
        match (&bx.cx().val_ty(imm), &to_backend_ty) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(bx.cx().val_ty(imm), to_backend_ty);
1151
1152    // This `assume` remains important for cases like (a conceptual)
1153    //    transmute::<u32, NonZeroU32>(x) == 0
1154    // since it's never passed to something with parameter metadata (especially
1155    // after MIR inlining) so the only way to tell the backend about the
1156    // constraint that the `transmute` introduced is to `assume` it.
1157    assume_scalar_range(bx, imm, to_scalar, to_backend_ty, Some(&from_scalar));
1158
1159    imm = bx.to_immediate_scalar(imm, to_scalar);
1160    imm
1161}
1162
1163/// Emits an `assume` call that `imm`'s value is within the known range of `scalar`.
1164///
1165/// If `known` is `Some`, only emits the assume if it's more specific than
1166/// whatever is already known from the range of *that* scalar.
1167fn assume_scalar_range<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
1168    bx: &mut Bx,
1169    imm: Bx::Value,
1170    scalar: abi::Scalar,
1171    backend_ty: Bx::Type,
1172    known: Option<&abi::Scalar>,
1173) {
1174    if #[allow(non_exhaustive_omitted_patterns)] match bx.cx().sess().opts.optimize {
    OptLevel::No => true,
    _ => false,
}matches!(bx.cx().sess().opts.optimize, OptLevel::No) {
1175        return;
1176    }
1177
1178    match (scalar, known) {
1179        (abi::Scalar::Union { .. }, _) => return,
1180        (_, None) => {
1181            if scalar.is_always_valid(bx.cx()) {
1182                return;
1183            }
1184        }
1185        (abi::Scalar::Initialized { valid_range, .. }, Some(known)) => {
1186            let known_range = known.valid_range(bx.cx());
1187            if valid_range.contains_range(known_range, scalar.size(bx.cx())) {
1188                return;
1189            }
1190        }
1191    }
1192
1193    match scalar.primitive() {
1194        abi::Primitive::Bool | abi::Primitive::Int(..) => {
1195            let range = scalar.valid_range(bx.cx());
1196            bx.assume_integer_range(imm, backend_ty, range);
1197        }
1198        abi::Primitive::Pointer(abi::AddressSpace::ZERO)
1199            if !scalar.valid_range(bx.cx()).contains(0) =>
1200        {
1201            bx.assume_nonnull(imm);
1202        }
1203        abi::Primitive::Pointer(..) | abi::Primitive::Float(..) => {}
1204    }
1205}