Skip to main content

rustc_codegen_ssa/mir/
rvalue.rs

1use std::assert_matches;
2
3use itertools::Itertools as _;
4use rustc_abi::{self as abi, BackendRepr, FIRST_VARIANT};
5use rustc_index::IndexVec;
6use rustc_middle::mir;
7use rustc_middle::ty::adjustment::PointerCoercion;
8use rustc_middle::ty::consts::ConstExt;
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, TypeKind};
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/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/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/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/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/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/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.abi, cast.align.abi);
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            (Float(_), Float(_)) => {
469                let srcsz = bx.cx().float_width(from_backend_ty);
470                let dstsz = bx.cx().float_width(to_backend_ty);
471                if dstsz > srcsz {
472                    bx.fpext(imm, to_backend_ty)
473                } else if srcsz > dstsz {
474                    bx.fptrunc(imm, to_backend_ty)
475                } else {
476                    imm
477                }
478            }
479            (Int(_, is_signed), Float(_)) => {
480                if is_signed {
481                    bx.sitofp(imm, to_backend_ty)
482                } else {
483                    bx.uitofp(imm, to_backend_ty)
484                }
485            }
486            (Pointer(..), Pointer(..)) => bx.pointercast(imm, to_backend_ty),
487            (Int(_, is_signed), Pointer(..)) => {
488                let usize_imm = bx.intcast(imm, bx.cx().type_isize(), is_signed);
489                bx.inttoptr(usize_imm, to_backend_ty)
490            }
491            (Float(_), Int(_, is_signed)) => bx.cast_float_to_int(is_signed, imm, to_backend_ty),
492            _ => return None,
493        };
494        Some(imm)
495    }
496
497    pub(crate) fn codegen_rvalue_operand(
498        &mut self,
499        bx: &mut Bx,
500        rvalue: &mir::Rvalue<'tcx>,
501    ) -> OperandRef<'tcx, Bx::Value> {
502        match *rvalue {
503            mir::Rvalue::Cast(ref kind, ref source, mir_cast_ty) => {
504                let operand = self.codegen_operand(bx, source);
505                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_codegen_ssa/src/mir/rvalue.rs:505",
                        "rustc_codegen_ssa::mir::rvalue", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/5ceaf6608eb354c2f5bbb3b8d974caa367dac81c/compiler/rustc_codegen_ssa/src/mir/rvalue.rs"),
                        ::tracing_core::__macro_support::Option::Some(505u32),
                        ::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);
506                let cast = bx.cx().layout_of(self.monomorphize(mir_cast_ty));
507
508                let val = match *kind {
509                    mir::CastKind::PointerExposeProvenance => {
510                        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());
511                        let llptr = operand.immediate();
512                        let llcast_ty = bx.cx().immediate_backend_type(cast);
513                        let lladdr = bx.ptrtoint(llptr, llcast_ty);
514                        OperandValue::Immediate(lladdr)
515                    }
516                    mir::CastKind::PointerCoercion(PointerCoercion::ReifyFnPointer(_), _) => {
517                        match *operand.layout.ty.kind() {
518                            ty::FnDef(def_id, args) => {
519                                let instance = ty::Instance::resolve_for_fn_ptr(
520                                    bx.tcx(),
521                                    bx.typing_env(),
522                                    def_id,
523                                    args.no_bound_vars().unwrap(),
524                                )
525                                .unwrap();
526                                OperandValue::Immediate(
527                                    bx.get_fn_addr(
528                                        instance,
529                                        bx.sess().pointer_authentication_functions(),
530                                    ),
531                                )
532                            }
533                            _ => ::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),
534                        }
535                    }
536                    mir::CastKind::PointerCoercion(PointerCoercion::ClosureFnPointer(_), _) => {
537                        match *operand.layout.ty.kind() {
538                            ty::Closure(def_id, args) => {
539                                let instance = Instance::resolve_closure(
540                                    bx.cx().tcx(),
541                                    def_id,
542                                    args,
543                                    ty::ClosureKind::FnOnce,
544                                );
545                                OperandValue::Immediate(
546                                    bx.cx().get_fn_addr(
547                                        instance,
548                                        bx.sess().pointer_authentication_functions(),
549                                    ),
550                                )
551                            }
552                            _ => ::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),
553                        }
554                    }
555                    mir::CastKind::PointerCoercion(PointerCoercion::UnsafeFnPointer, _) => {
556                        // This is a no-op at the LLVM level.
557                        operand.val
558                    }
559                    mir::CastKind::PointerCoercion(PointerCoercion::Unsize, _) => {
560                        {
    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 { .. });
561                        let (lldata, llextra) = operand.val.pointer_parts();
562                        let (lldata, llextra) =
563                            base::unsize_ptr(bx, lldata, operand.layout.ty, cast.ty, llextra);
564                        OperandValue::Pair(lldata, llextra)
565                    }
566                    mir::CastKind::PointerCoercion(
567                        PointerCoercion::MutToConstPointer | PointerCoercion::ArrayToPointer,
568                        _,
569                    ) => {
570                        ::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");
571                    }
572                    mir::CastKind::PtrToPtr if let BackendRepr::ScalarPair { .. } = operand.layout.backend_repr => {
573                        if let OperandValue::Pair(data_ptr, meta) = operand.val {
574                            if let BackendRepr::ScalarPair { .. } = cast.layout.backend_repr {
575                                OperandValue::Pair(data_ptr, meta)
576                            } else {
577                                // Cast of wide-ptr to thin-ptr is an extraction of data-ptr.
578                                OperandValue::Immediate(data_ptr)
579                            }
580                        } else {
581                            ::rustc_span::macros::bug_impl(None,
    format_args!("unexpected non-pair operand"), Location::caller());bug!("unexpected non-pair operand");
582                        }
583                    }
584                    | mir::CastKind::IntToInt
585                    | mir::CastKind::FloatToInt
586                    | mir::CastKind::FloatToFloat
587                    | mir::CastKind::IntToFloat
588                    | mir::CastKind::PtrToPtr
589                    | mir::CastKind::FnPtrToPtr
590                    // Since int2ptr can have arbitrary integer types as input (so we have to do
591                    // sign extension and all that), it is currently best handled in the same code
592                    // path as the other integer-to-X casts.
593                    | mir::CastKind::PointerWithExposedProvenance => {
594                        let imm = operand.immediate();
595                        let abi::BackendRepr::Scalar(from_scalar) = operand.layout.backend_repr
596                        else {
597                            ::rustc_span::macros::bug_impl(None,
    format_args!("Found non-scalar for operand {0:?}", operand),
    Location::caller());bug!("Found non-scalar for operand {operand:?}");
598                        };
599                        let from_backend_ty = bx.cx().immediate_backend_type(operand.layout);
600
601                        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());
602                        let to_backend_ty = bx.cx().immediate_backend_type(cast);
603                        if operand.layout.is_uninhabited() {
604                            let val = OperandValue::Immediate(bx.cx().const_poison(to_backend_ty));
605                            return OperandRef { val, layout: cast, move_annotation: None };
606                        }
607                        let abi::BackendRepr::Scalar(to_scalar) = cast.layout.backend_repr else {
608                            ::rustc_span::macros::bug_impl(None,
    format_args!("Found non-scalar for cast {0:?}", cast),
    Location::caller());bug!("Found non-scalar for cast {cast:?}");
609                        };
610
611                        self.cast_immediate(
612                            bx,
613                            imm,
614                            from_scalar,
615                            from_backend_ty,
616                            to_scalar,
617                            to_backend_ty,
618                        )
619                        .map(OperandValue::Immediate)
620                        .unwrap_or_else(|| {
621                            ::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:?}");
622                        })
623                    }
624                    mir::CastKind::Transmute | mir::CastKind::BoxDerefTransmute | mir::CastKind::Subtype => {
625                        self.codegen_transmute_operand(bx, operand, cast)
626                    }
627                };
628                OperandRef { val, layout: cast, move_annotation: None }
629            }
630
631            mir::Rvalue::Ref(_, bk, place) => {
632                let mk_ref = move |tcx: TyCtxt<'tcx>, ty: Ty<'tcx>| {
633                    Ty::new_ref(tcx, tcx.lifetimes.re_erased, ty, bk.to_mutbl_lossy())
634                };
635                let op = self.codegen_place_to_pointer(bx, place, mk_ref);
636                if self.cx.tcx().sess.opts.unstable_opts.codegen_emit_retag.is_some() {
637                    self.codegen_retag_operand(bx, op, false)
638                } else {
639                    op
640                }
641            }
642
643            // Note: Exclusive reborrowing is always equal to a memcpy, as the types do not change.
644            // Generic shared reborrowing is not (necessarily) a simple memcpy, but currently the
645            // coherence check places such restrictions on the CoerceShared trait as to guarantee
646            // that it is.
647            mir::Rvalue::Reborrow(_, _, place) => {
648                self.codegen_operand(bx, &mir::Operand::Copy(place))
649            }
650
651            mir::Rvalue::RawPtr(kind, place) => {
652                let mk_ptr = move |tcx: TyCtxt<'tcx>, ty: Ty<'tcx>| {
653                    Ty::new_ptr(tcx, ty, kind.to_mutbl_lossy())
654                };
655                self.codegen_place_to_pointer(bx, place, mk_ptr)
656            }
657
658            mir::Rvalue::BinaryOp(op_with_overflow, (ref lhs, ref rhs))
659                if let Some(op) = op_with_overflow.overflowing_to_wrapping() =>
660            {
661                let lhs = self.codegen_operand(bx, lhs);
662                let rhs = self.codegen_operand(bx, rhs);
663                let result = self.codegen_scalar_checked_binop(
664                    bx,
665                    op,
666                    lhs.immediate(),
667                    rhs.immediate(),
668                    lhs.layout.ty,
669                );
670                let val_ty = op.ty(bx.tcx(), lhs.layout.ty, rhs.layout.ty);
671                let operand_ty = Ty::new_tup(bx.tcx(), &[val_ty, bx.tcx().types.bool]);
672                OperandRef {
673                    val: result,
674                    layout: bx.cx().layout_of(operand_ty),
675                    move_annotation: None,
676                }
677            }
678
679            mir::Rvalue::BinaryOp(op, (ref lhs, ref rhs)) => {
680                let lhs = self.codegen_operand(bx, lhs);
681                let rhs = self.codegen_operand(bx, rhs);
682                let llresult = match (lhs.val, rhs.val) {
683                    (
684                        OperandValue::Pair(lhs_addr, lhs_extra),
685                        OperandValue::Pair(rhs_addr, rhs_extra),
686                    ) => self.codegen_wide_ptr_binop(
687                        bx,
688                        op,
689                        lhs_addr,
690                        lhs_extra,
691                        rhs_addr,
692                        rhs_extra,
693                        lhs.layout.ty,
694                    ),
695
696                    (OperandValue::Immediate(lhs_val), OperandValue::Immediate(rhs_val)) => self
697                        .codegen_scalar_binop(
698                            bx,
699                            op,
700                            lhs_val,
701                            rhs_val,
702                            lhs.layout.ty,
703                            rhs.layout.ty,
704                        ),
705
706                    _ => ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller())bug!(),
707                };
708                OperandRef {
709                    val: OperandValue::Immediate(llresult),
710                    layout: bx.cx().layout_of(op.ty(bx.tcx(), lhs.layout.ty, rhs.layout.ty)),
711                    move_annotation: None,
712                }
713            }
714
715            mir::Rvalue::UnaryOp(op, ref operand) => {
716                let operand = self.codegen_operand(bx, operand);
717                let is_float = operand.layout.ty.is_floating_point();
718                let (val, layout) = match op {
719                    mir::UnOp::Not => {
720                        let llval = bx.not(operand.immediate());
721                        (OperandValue::Immediate(llval), operand.layout)
722                    }
723                    mir::UnOp::Neg => {
724                        let llval = if is_float {
725                            bx.fneg(operand.immediate())
726                        } else {
727                            bx.neg(operand.immediate())
728                        };
729                        (OperandValue::Immediate(llval), operand.layout)
730                    }
731                    mir::UnOp::PtrMetadata => {
732                        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(),);
733                        let (_, meta) = operand.val.pointer_parts();
734                        {
    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());
735                        if let Some(meta) = meta {
736                            (OperandValue::Immediate(meta), operand.layout.field(self.cx, 1))
737                        } else {
738                            (OperandValue::ZeroSized, bx.cx().layout_of(bx.tcx().types.unit))
739                        }
740                    }
741                };
742                if !val.is_expected_variant_for_type(layout) {
    {
        ::core::panicking::panic_fmt(format_args!("Made wrong variant {0:?} for type {1:?}",
                val, layout));
    }
};assert!(
743                    val.is_expected_variant_for_type(layout),
744                    "Made wrong variant {val:?} for type {layout:?}",
745                );
746                OperandRef { val, layout, move_annotation: None }
747            }
748
749            mir::Rvalue::Discriminant(ref place) => {
750                let discr_ty = rvalue.ty(self.mir, bx.tcx());
751                let discr_ty = self.monomorphize(discr_ty);
752                let operand = self.codegen_consume(bx, place.as_ref());
753                let discr = operand.codegen_get_discr(self, bx, discr_ty);
754                OperandRef {
755                    val: OperandValue::Immediate(discr),
756                    layout: self.cx.layout_of(discr_ty),
757                    move_annotation: None,
758                }
759            }
760
761            mir::Rvalue::ThreadLocalRef(def_id) => {
762                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));
763                let layout = bx.layout_of(bx.cx().tcx().static_ptr_ty(def_id, bx.typing_env()));
764                let static_ = if !def_id.is_local() && bx.cx().tcx().needs_thread_local_shim(def_id)
765                {
766                    let instance = ty::Instance {
767                        def: ty::InstanceKind::Shim(ty::ShimKind::ThreadLocal(def_id)),
768                        args: ty::GenericArgs::empty(),
769                    };
770                    let fn_ptr =
771                        bx.get_fn_addr(instance, bx.sess().pointer_authentication_functions());
772                    let fn_abi = bx.fn_abi_of_instance(instance, ty::List::empty());
773                    let fn_ty = bx.fn_decl_backend_type(fn_abi);
774                    let fn_attrs = if bx.tcx().def_kind(instance.def_id()).has_codegen_attrs() {
775                        Some(bx.tcx().codegen_instance_attrs(instance.def))
776                    } else {
777                        None
778                    };
779                    bx.call(
780                        fn_ty,
781                        fn_attrs.as_deref(),
782                        Some(fn_abi),
783                        fn_ptr,
784                        ReturnSlot::Direct,
785                        &[],
786                        None,
787                        Some(instance),
788                    )
789                } else {
790                    bx.get_static(def_id)
791                };
792                OperandRef { val: OperandValue::Immediate(static_), layout, move_annotation: None }
793            }
794
795            mir::Rvalue::Use(ref operand, _) => self.codegen_operand(bx, operand),
796
797            mir::Rvalue::Repeat(ref elem, len_const) => {
798                // All arrays have `BackendRepr::Memory`, so only the ZST cases
799                // end up here. Anything else forces the destination local to be
800                // `Memory`, and thus ends up handled in `codegen_rvalue` instead.
801                let operand = self.codegen_operand(bx, elem);
802                let array_ty = Ty::new_array_with_const_len(bx.tcx(), operand.layout.ty, len_const);
803                let array_ty = self.monomorphize(array_ty);
804                let array_layout = bx.layout_of(array_ty);
805                if !array_layout.is_zst() {
    ::core::panicking::panic("assertion failed: array_layout.is_zst()")
};assert!(array_layout.is_zst());
806                OperandRef {
807                    val: OperandValue::ZeroSized,
808                    layout: array_layout,
809                    move_annotation: None,
810                }
811            }
812
813            mir::Rvalue::Aggregate(ref kind, ref fields) => {
814                let (variant_index, active_field_index) = match **kind {
815                    mir::AggregateKind::Adt(_, variant_index, _, _, active_field_index) => {
816                        (variant_index, active_field_index)
817                    }
818                    _ => (FIRST_VARIANT, None),
819                };
820
821                let ty = rvalue.ty(self.mir, self.cx.tcx());
822                let ty = self.monomorphize(ty);
823                let layout = self.cx.layout_of(ty);
824
825                let mut builder = OperandRefBuilder::new(layout);
826                for (field_idx, field) in fields.iter_enumerated() {
827                    let op = self.codegen_operand(bx, field);
828                    let fi = active_field_index.unwrap_or(field_idx);
829                    builder.insert_field(bx, variant_index, fi, op);
830                }
831
832                let tag_result = codegen_tag_value(self.cx, variant_index, layout);
833                match tag_result {
834                    Err(super::place::UninhabitedVariantError) => {
835                        // Like codegen_set_discr we use a sound abort, but could
836                        // potentially `unreachable` or just return the poison for
837                        // more optimizability, if that turns out to be helpful.
838                        bx.abort();
839                        let val = OperandValue::poison(bx, layout);
840                        OperandRef { val, layout, move_annotation: None }
841                    }
842                    Ok(maybe_tag_value) => {
843                        if let Some((tag_field, tag_imm)) = maybe_tag_value {
844                            builder.insert_imm(tag_field, tag_imm);
845                        }
846                        builder.build(bx.cx())
847                    }
848                }
849            }
850
851            mir::Rvalue::WrapUnsafeBinder(ref operand, binder_ty) => {
852                let operand = self.codegen_operand(bx, operand);
853                let binder_ty = self.monomorphize(binder_ty);
854                let layout = bx.cx().layout_of(binder_ty);
855                OperandRef { val: operand.val, layout, move_annotation: None }
856            }
857
858            mir::Rvalue::CopyForDeref(_) => ::rustc_span::macros::bug_impl(None,
    format_args!("`CopyForDeref` in codegen"), Location::caller())bug!("`CopyForDeref` in codegen"),
859        }
860    }
861
862    /// Codegen an `Rvalue::RawPtr` or `Rvalue::Ref`
863    fn codegen_place_to_pointer(
864        &mut self,
865        bx: &mut Bx,
866        place: mir::Place<'tcx>,
867        mk_ptr_ty: impl FnOnce(TyCtxt<'tcx>, Ty<'tcx>) -> Ty<'tcx>,
868    ) -> OperandRef<'tcx, Bx::Value> {
869        let cg_place = self.codegen_place(bx, place.as_ref());
870        let val = cg_place.val.address();
871
872        let ty = cg_place.layout.ty;
873        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!(
874            if bx.cx().tcx().type_has_metadata(ty, bx.cx().typing_env()) {
875                matches!(val, OperandValue::Pair(..))
876            } else {
877                matches!(val, OperandValue::Immediate(..))
878            },
879            "Address of place was unexpectedly {val:?} for pointee type {ty:?}",
880        );
881
882        OperandRef {
883            val,
884            layout: self.cx.layout_of(mk_ptr_ty(self.cx.tcx(), ty)),
885            move_annotation: None,
886        }
887    }
888
889    fn codegen_scalar_binop(
890        &mut self,
891        bx: &mut Bx,
892        op: mir::BinOp,
893        lhs: Bx::Value,
894        rhs: Bx::Value,
895        lhs_ty: Ty<'tcx>,
896        rhs_ty: Ty<'tcx>,
897    ) -> Bx::Value {
898        let is_float = lhs_ty.is_floating_point();
899        let is_signed = lhs_ty.is_signed();
900        match op {
901            mir::BinOp::Add => {
902                if is_float {
903                    bx.fadd(lhs, rhs)
904                } else {
905                    bx.add(lhs, rhs)
906                }
907            }
908            mir::BinOp::AddUnchecked => {
909                if is_signed {
910                    bx.unchecked_sadd(lhs, rhs)
911                } else {
912                    bx.unchecked_uadd(lhs, rhs)
913                }
914            }
915            mir::BinOp::Sub => {
916                if is_float {
917                    bx.fsub(lhs, rhs)
918                } else {
919                    bx.sub(lhs, rhs)
920                }
921            }
922            mir::BinOp::SubUnchecked => {
923                if is_signed {
924                    bx.unchecked_ssub(lhs, rhs)
925                } else {
926                    bx.unchecked_usub(lhs, rhs)
927                }
928            }
929            mir::BinOp::Mul => {
930                if is_float {
931                    bx.fmul(lhs, rhs)
932                } else {
933                    bx.mul(lhs, rhs)
934                }
935            }
936            mir::BinOp::MulUnchecked => {
937                if is_signed {
938                    bx.unchecked_smul(lhs, rhs)
939                } else {
940                    bx.unchecked_umul(lhs, rhs)
941                }
942            }
943            mir::BinOp::Div => {
944                if is_float {
945                    bx.fdiv(lhs, rhs)
946                } else if is_signed {
947                    bx.sdiv(lhs, rhs)
948                } else {
949                    bx.udiv(lhs, rhs)
950                }
951            }
952            mir::BinOp::Rem => {
953                if is_float {
954                    bx.frem(lhs, rhs)
955                } else if is_signed {
956                    bx.srem(lhs, rhs)
957                } else {
958                    bx.urem(lhs, rhs)
959                }
960            }
961            mir::BinOp::BitOr => bx.or(lhs, rhs),
962            mir::BinOp::BitAnd => bx.and(lhs, rhs),
963            mir::BinOp::BitXor => bx.xor(lhs, rhs),
964            mir::BinOp::Offset => {
965                let pointee_type = lhs_ty
966                    .builtin_deref(true)
967                    .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));
968                let pointee_layout = bx.cx().layout_of(pointee_type);
969                if pointee_layout.is_zst() {
970                    // `Offset` works in terms of the size of pointee,
971                    // so offsetting a pointer to ZST is a noop.
972                    lhs
973                } else {
974                    let llty = bx.cx().backend_type(pointee_layout);
975                    if !rhs_ty.is_signed() {
976                        bx.inbounds_nuw_gep(llty, lhs, &[rhs])
977                    } else {
978                        bx.inbounds_gep(llty, lhs, &[rhs])
979                    }
980                }
981            }
982            mir::BinOp::Shl | mir::BinOp::ShlUnchecked => {
983                let rhs = base::build_shift_expr_rhs(bx, lhs, rhs, op == mir::BinOp::ShlUnchecked);
984                bx.shl(lhs, rhs)
985            }
986            mir::BinOp::Shr | mir::BinOp::ShrUnchecked => {
987                let rhs = base::build_shift_expr_rhs(bx, lhs, rhs, op == mir::BinOp::ShrUnchecked);
988                if is_signed { bx.ashr(lhs, rhs) } else { bx.lshr(lhs, rhs) }
989            }
990            mir::BinOp::Ne
991            | mir::BinOp::Lt
992            | mir::BinOp::Gt
993            | mir::BinOp::Eq
994            | mir::BinOp::Le
995            | mir::BinOp::Ge => {
996                if is_float {
997                    bx.fcmp(base::bin_op_to_fcmp_predicate(op), lhs, rhs)
998                } else {
999                    bx.icmp(base::bin_op_to_icmp_predicate(op, is_signed), lhs, rhs)
1000                }
1001            }
1002            mir::BinOp::Cmp => {
1003                if !!is_float { ::core::panicking::panic("assertion failed: !is_float") };assert!(!is_float);
1004                bx.three_way_compare(lhs_ty, lhs, rhs)
1005            }
1006            mir::BinOp::AddWithOverflow
1007            | mir::BinOp::SubWithOverflow
1008            | mir::BinOp::MulWithOverflow => {
1009                ::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")
1010            }
1011        }
1012    }
1013
1014    fn codegen_wide_ptr_binop(
1015        &mut self,
1016        bx: &mut Bx,
1017        op: mir::BinOp,
1018        lhs_addr: Bx::Value,
1019        lhs_extra: Bx::Value,
1020        rhs_addr: Bx::Value,
1021        rhs_extra: Bx::Value,
1022        _input_ty: Ty<'tcx>,
1023    ) -> Bx::Value {
1024        match op {
1025            mir::BinOp::Eq => {
1026                let lhs = bx.icmp(IntPredicate::IntEQ, lhs_addr, rhs_addr);
1027                let rhs = bx.icmp(IntPredicate::IntEQ, lhs_extra, rhs_extra);
1028                bx.and(lhs, rhs)
1029            }
1030            mir::BinOp::Ne => {
1031                let lhs = bx.icmp(IntPredicate::IntNE, lhs_addr, rhs_addr);
1032                let rhs = bx.icmp(IntPredicate::IntNE, lhs_extra, rhs_extra);
1033                bx.or(lhs, rhs)
1034            }
1035            mir::BinOp::Le | mir::BinOp::Lt | mir::BinOp::Ge | mir::BinOp::Gt => {
1036                // a OP b ~ a.0 STRICT(OP) b.0 | (a.0 == b.0 && a.1 OP a.1)
1037                let (op, strict_op) = match op {
1038                    mir::BinOp::Lt => (IntPredicate::IntULT, IntPredicate::IntULT),
1039                    mir::BinOp::Le => (IntPredicate::IntULE, IntPredicate::IntULT),
1040                    mir::BinOp::Gt => (IntPredicate::IntUGT, IntPredicate::IntUGT),
1041                    mir::BinOp::Ge => (IntPredicate::IntUGE, IntPredicate::IntUGT),
1042                    _ => ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller())bug!(),
1043                };
1044                let lhs = bx.icmp(strict_op, lhs_addr, rhs_addr);
1045                let and_lhs = bx.icmp(IntPredicate::IntEQ, lhs_addr, rhs_addr);
1046                let and_rhs = bx.icmp(op, lhs_extra, rhs_extra);
1047                let rhs = bx.and(and_lhs, and_rhs);
1048                bx.or(lhs, rhs)
1049            }
1050            _ => {
1051                ::rustc_span::macros::bug_impl(None,
    format_args!("unexpected wide ptr binop"), Location::caller());bug!("unexpected wide ptr binop");
1052            }
1053        }
1054    }
1055
1056    fn codegen_scalar_checked_binop(
1057        &mut self,
1058        bx: &mut Bx,
1059        op: mir::BinOp,
1060        lhs: Bx::Value,
1061        rhs: Bx::Value,
1062        input_ty: Ty<'tcx>,
1063    ) -> OperandValue<Bx::Value> {
1064        let (val, of) = match op {
1065            // These are checked using intrinsics
1066            mir::BinOp::Add | mir::BinOp::Sub | mir::BinOp::Mul => {
1067                let oop = match op {
1068                    mir::BinOp::Add => OverflowOp::Add,
1069                    mir::BinOp::Sub => OverflowOp::Sub,
1070                    mir::BinOp::Mul => OverflowOp::Mul,
1071                    _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1072                };
1073                bx.checked_binop(oop, input_ty, lhs, rhs)
1074            }
1075            _ => ::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),
1076        };
1077
1078        OperandValue::Pair(val, of)
1079    }
1080}
1081
1082/// Transmutes a single scalar value `imm` from `from_scalar` to `to_scalar`.
1083///
1084/// This is expected to be in *immediate* form, as seen in [`OperandValue::Immediate`]
1085/// or [`OperandValue::Pair`] (so `i1` for bools, not `i8`, for example).
1086///
1087/// ICEs if the passed-in `imm` is not a value of the expected type for
1088/// `from_scalar`, such as if it's a vector or a pair.
1089pub(super) fn transmute_scalar<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
1090    bx: &mut Bx,
1091    mut imm: Bx::Value,
1092    from_scalar: abi::Scalar,
1093    to_scalar: abi::Scalar,
1094) -> Bx::Value {
1095    {
    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()));
1096    let imm_ty = bx.cx().val_ty(imm);
1097    {
    match (&(bx.cx().type_kind(imm_ty)), &(TypeKind::Vector)) {
        (left_val, right_val) => {
            if *left_val == *right_val {
                let kind = ::core::panicking::AssertKind::Ne;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val,
                    ::core::option::Option::Some(format_args!("Vector type {0:?} not allowed in transmute_scalar {1:?} -> {2:?}",
                            imm_ty, from_scalar, to_scalar)));
            }
        }
    }
};assert_ne!(
1098        bx.cx().type_kind(imm_ty),
1099        TypeKind::Vector,
1100        "Vector type {imm_ty:?} not allowed in transmute_scalar {from_scalar:?} -> {to_scalar:?}"
1101    );
1102
1103    // While optimizations will remove no-op transmutes, they might still be
1104    // there in debug or things that aren't no-op in MIR because they change
1105    // the Rust type but not the underlying layout/niche.
1106    if from_scalar == to_scalar {
1107        return imm;
1108    }
1109
1110    use abi::Primitive::*;
1111    imm = bx.from_immediate(imm);
1112
1113    let from_backend_ty = bx.cx().type_from_scalar(from_scalar);
1114    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);
1115    let to_backend_ty = bx.cx().type_from_scalar(to_scalar);
1116
1117    // If we have a scalar, we must already know its range. Either
1118    //
1119    // 1) It's a parameter with `range` parameter metadata,
1120    // 2) It's something we `load`ed with `!range` metadata, or
1121    // 3) After a transmute we `assume`d the range (see below).
1122    //
1123    // That said, last time we tried removing this, it didn't actually help
1124    // the rustc-perf results, so might as well keep doing it
1125    // <https://github.com/rust-lang/rust/pull/135610#issuecomment-2599275182>
1126    assume_scalar_range(bx, imm, from_scalar, from_backend_ty, Some(&to_scalar));
1127
1128    imm = match (from_scalar.primitive(), to_scalar.primitive()) {
1129        (Int(..) | Float(_), Int(..) | Float(_)) => bx.bitcast(imm, to_backend_ty),
1130        (Pointer(..), Pointer(..)) => bx.pointercast(imm, to_backend_ty),
1131        (Int(..), Pointer(..)) => bx.inttoptr(imm, to_backend_ty),
1132        (Pointer(..), Int(..)) => {
1133            // FIXME: this exposes the provenance, which shouldn't be necessary.
1134            bx.ptrtoint(imm, to_backend_ty)
1135        }
1136        (Float(_), Pointer(..)) => {
1137            let int_imm = bx.bitcast(imm, bx.cx().type_isize());
1138            bx.inttoptr(int_imm, to_backend_ty)
1139        }
1140        (Pointer(..), Float(_)) => {
1141            // FIXME: this exposes the provenance, which shouldn't be necessary.
1142            let int_imm = bx.ptrtoint(imm, bx.cx().type_isize());
1143            bx.bitcast(int_imm, to_backend_ty)
1144        }
1145    };
1146
1147    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);
1148
1149    // This `assume` remains important for cases like (a conceptual)
1150    //    transmute::<u32, NonZeroU32>(x) == 0
1151    // since it's never passed to something with parameter metadata (especially
1152    // after MIR inlining) so the only way to tell the backend about the
1153    // constraint that the `transmute` introduced is to `assume` it.
1154    assume_scalar_range(bx, imm, to_scalar, to_backend_ty, Some(&from_scalar));
1155
1156    imm = bx.to_immediate_scalar(imm, to_scalar);
1157    imm
1158}
1159
1160/// Emits an `assume` call that `imm`'s value is within the known range of `scalar`.
1161///
1162/// If `known` is `Some`, only emits the assume if it's more specific than
1163/// whatever is already known from the range of *that* scalar.
1164fn assume_scalar_range<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
1165    bx: &mut Bx,
1166    imm: Bx::Value,
1167    scalar: abi::Scalar,
1168    backend_ty: Bx::Type,
1169    known: Option<&abi::Scalar>,
1170) {
1171    if #[allow(non_exhaustive_omitted_patterns)] match bx.cx().sess().opts.optimize {
    OptLevel::No => true,
    _ => false,
}matches!(bx.cx().sess().opts.optimize, OptLevel::No) {
1172        return;
1173    }
1174
1175    match (scalar, known) {
1176        (abi::Scalar::Union { .. }, _) => return,
1177        (_, None) => {
1178            if scalar.is_always_valid(bx.cx()) {
1179                return;
1180            }
1181        }
1182        (abi::Scalar::Initialized { valid_range, .. }, Some(known)) => {
1183            let known_range = known.valid_range(bx.cx());
1184            if valid_range.contains_range(known_range, scalar.size(bx.cx())) {
1185                return;
1186            }
1187        }
1188    }
1189
1190    match scalar.primitive() {
1191        abi::Primitive::Int(..) => {
1192            let range = scalar.valid_range(bx.cx());
1193            bx.assume_integer_range(imm, backend_ty, range);
1194        }
1195        abi::Primitive::Pointer(abi::AddressSpace::ZERO)
1196            if !scalar.valid_range(bx.cx()).contains(0) =>
1197        {
1198            bx.assume_nonnull(imm);
1199        }
1200        abi::Primitive::Pointer(..) | abi::Primitive::Float(..) => {}
1201    }
1202}