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::ty::adjustment::PointerCoercion;
7use rustc_middle::ty::layout::{HasTyCtxt, HasTypingEnv, LayoutOf, TyAndLayout};
8use rustc_middle::ty::{self, Instance, Mutability, Ty, TyCtxt};
9use rustc_middle::{bug, mir, span_bug};
10use rustc_session::config::OptLevel;
11use tracing::{debug, instrument};
12
13use super::FunctionCx;
14use super::operand::{OperandRef, OperandRefBuilder, OperandValue};
15use super::place::{PlaceRef, PlaceValue, codegen_tag_value};
16use crate::common::{IntPredicate, TypeKind};
17use crate::traits::*;
18use crate::{MemFlags, base};
19
20impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
21    fn try_codegen_const_aggregate_as_immediate(
22        &mut self,
23        bx: &mut Bx,
24        dest: PlaceRef<'tcx, Bx::Value>,
25        kind: &mir::AggregateKind<'tcx>,
26        operands: &IndexVec<abi::FieldIdx, mir::Operand<'tcx>>,
27    ) -> bool {
28        // Keep this allowlist limited to aggregate kinds with direct codegen coverage.
29        // Extract the variant index at the same time so we can verify it against
30        // the layout below. Tuples always use `FIRST_VARIANT` (index 0); the
31        // `None` in the `Adt` arm excludes unions (which carry an active field).
32        let variant_index = match kind {
33            mir::AggregateKind::Tuple => FIRST_VARIANT,
34            mir::AggregateKind::Adt(_, variant_index, _, _, None) => *variant_index,
35            _ => return false,
36        };
37        if !#[allow(non_exhaustive_omitted_patterns)] match dest.layout.fields {
    abi::FieldsShape::Arbitrary { .. } => true,
    _ => false,
}matches!(dest.layout.fields, abi::FieldsShape::Arbitrary { .. }) {
38            return false;
39        }
40        // `dest.layout` is the layout of the *overall* type, not a specific
41        // variant. When the layout is `Variants::Single { index: M }`, the
42        // field offsets and counts below all refer to variant M. If the MIR
43        // aggregate is constructing a different variant N (e.g. because N is
44        // uninhabited and the layout collapsed to M), using `dest.layout`
45        // directly would read the wrong field metadata. Bail out and let the
46        // normal codegen path handle it via `project_downcast`.
47        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)
48        {
49            return false;
50        }
51        // Now that the variant indices are known to match, the operand count
52        // and the layout field count must agree.
53        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());
54
55        let size = dest.layout.size.bytes();
56        let llty = match size {
57            1 => bx.cx().type_i8(),
58            2 => bx.cx().type_i16(),
59            4 => bx.cx().type_i32(),
60            8 => bx.cx().type_i64(),
61            16 => bx.cx().type_i128(),
62            _ => return false,
63        };
64
65        let mut value = 0u128;
66        for (field_idx, operand) in operands.iter_enumerated() {
67            let field_layout = dest.layout.field(bx.cx(), field_idx.as_usize());
68            if field_layout.is_zst() {
69                continue;
70            }
71            let mir::Operand::Constant(constant) = operand else {
72                return false;
73            };
74            let Some(field_value) = self.eval_mir_constant(constant).try_to_bits(field_layout.size)
75            else {
76                return false;
77            };
78
79            let field_size = field_layout.size.bytes();
80            let field_offset = dest.layout.fields.offset(field_idx.as_usize()).bytes();
81            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);
82            let shift = match bx.tcx().data_layout.endian {
83                abi::Endian::Little => field_offset * 8,
84                abi::Endian::Big => (size - field_offset - field_size) * 8,
85            };
86            value |= field_value << shift;
87        }
88
89        let value = bx.cx().const_uint_big(llty, value);
90        bx.store_to_place(value, dest.val);
91        true
92    }
93
94    #[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("compiler/rustc_codegen_ssa/src/mir/rvalue.rs"),
                                    ::tracing_core::__macro_support::Option::Some(94u32),
                                    ::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 let mir::Operand::Constant(const_op) = operand {
                        let val = self.eval_mir_constant(&const_op);
                        if val.all_bytes_uninit(self.cx.tcx()) { 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 compiler/rustc_codegen_ssa/src/mir/rvalue.rs:163",
                                                    "rustc_codegen_ssa::mir::rvalue", ::tracing::Level::DEBUG,
                                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/rvalue.rs"),
                                                    ::tracing_core::__macro_support::Option::Some(163u32),
                                                    ::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_middle::util::bug::bug_fmt(format_args!("unsized coercion on an unsized rvalue"));
                            }
                            base::coerce_unsized_into(bx, val.with_type(operand.layout),
                                dest);
                        }
                        OperandValue::ZeroSized => {
                            ::rustc_middle::util::bug::bug_fmt(format_args!("unsized coercion on a ZST rvalue"));
                        }
                    }
                }
                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 let mir::Operand::Constant(const_op) = elem {
                        let val = self.eval_mir_constant(const_op);
                        if val.all_bytes_uninit(self.cx.tcx()) {
                            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() {
                        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))]
95    pub(crate) fn codegen_rvalue(
96        &mut self,
97        bx: &mut Bx,
98        dest: PlaceRef<'tcx, Bx::Value>,
99        rvalue: &mir::Rvalue<'tcx>,
100    ) {
101        match *rvalue {
102            mir::Rvalue::Use(ref operand, with_retag) => {
103                if let mir::Operand::Constant(const_op) = operand {
104                    let val = self.eval_mir_constant(&const_op);
105                    if val.all_bytes_uninit(self.cx.tcx()) {
106                        return;
107                    }
108                }
109                let cg_operand = self.codegen_operand(bx, operand);
110                // Crucially, we do *not* use `OperandValue::Ref` for types with
111                // `BackendRepr::Scalar | BackendRepr::ScalarPair`. This ensures we match the MIR
112                // semantics regarding when assignment operators allow overlap of LHS and RHS.
113                if matches!(
114                    cg_operand.layout.backend_repr,
115                    BackendRepr::Scalar(..) | BackendRepr::ScalarPair { .. },
116                ) {
117                    debug_assert!(!matches!(cg_operand.val, OperandValue::Ref(..)));
118                }
119                // If this is storing a &Freeze reference with a retag, record that it's not
120                // possible to perform writes through the stored pointer.
121                let flags = if let ty::Ref(_, pointee_ty, Mutability::Not) =
122                    cg_operand.layout.ty.kind()
123                    && with_retag.yes()
124                    && pointee_ty.is_freeze(self.cx.tcx(), self.cx.typing_env())
125                {
126                    MemFlags::CAPTURES_READ_ONLY
127                } else {
128                    MemFlags::empty()
129                };
130                // FIXME: consider not copying constants through stack. (Fixable by codegen'ing
131                // constants into `OperandValue::Ref`; why don’t we do that yet if we don’t?)
132                cg_operand.store_with_annotation_and_flags(bx, dest, flags);
133            }
134
135            mir::Rvalue::Cast(
136                mir::CastKind::PointerCoercion(PointerCoercion::Unsize, _),
137                ref source,
138                _,
139            ) => {
140                // The destination necessarily contains a wide pointer, so if
141                // it's a scalar pair, it's a wide pointer or newtype thereof.
142                if let BackendRepr::ScalarPair { .. } = dest.layout.backend_repr {
143                    // Into-coerce of a thin pointer to a wide pointer -- just
144                    // use the operand path.
145                    let temp = self.codegen_rvalue_operand(bx, rvalue);
146                    temp.store_with_annotation(bx, dest);
147                    return;
148                }
149
150                // Unsize of a nontrivial struct. I would prefer for
151                // this to be eliminated by MIR building, but
152                // `CoerceUnsized` can be passed by a where-clause,
153                // so the (generic) MIR may not be able to expand it.
154                let operand = self.codegen_operand(bx, source);
155                match operand.val {
156                    OperandValue::Pair(..) | OperandValue::Immediate(_) => {
157                        // Unsize from an immediate structure. We don't
158                        // really need a temporary alloca here, but
159                        // avoiding it would require us to have
160                        // `coerce_unsized_into` use `extractvalue` to
161                        // index into the struct, and this case isn't
162                        // important enough for it.
163                        debug!("codegen_rvalue: creating ugly alloca");
164                        let scratch = PlaceRef::alloca(bx, operand.layout);
165                        scratch.storage_live(bx);
166                        operand.store_with_annotation(bx, scratch);
167                        base::coerce_unsized_into(bx, scratch, dest);
168                        scratch.storage_dead(bx);
169                    }
170                    OperandValue::Ref(val) => {
171                        if val.llextra.is_some() {
172                            bug!("unsized coercion on an unsized rvalue");
173                        }
174                        base::coerce_unsized_into(bx, val.with_type(operand.layout), dest);
175                    }
176                    OperandValue::ZeroSized => {
177                        bug!("unsized coercion on a ZST rvalue");
178                    }
179                }
180            }
181
182            mir::Rvalue::Cast(
183                mir::CastKind::Transmute | mir::CastKind::Subtype,
184                ref operand,
185                _ty,
186            ) => {
187                let src = self.codegen_operand(bx, operand);
188                self.codegen_transmute(bx, src, dest);
189            }
190
191            mir::Rvalue::Repeat(ref elem, count) => {
192                // Do not generate the loop for zero-sized elements or empty arrays.
193                if dest.layout.is_zst() {
194                    return;
195                }
196
197                // When the element is a const with all bytes uninit, emit a single memset that
198                // writes undef to the entire destination.
199                if let mir::Operand::Constant(const_op) = elem {
200                    let val = self.eval_mir_constant(const_op);
201                    if val.all_bytes_uninit(self.cx.tcx()) {
202                        let size = bx.const_usize(dest.layout.size.bytes());
203                        bx.memset(
204                            dest.val.llval,
205                            bx.const_undef(bx.type_i8()),
206                            size,
207                            dest.val.align,
208                            MemFlags::empty(),
209                        );
210                        return;
211                    }
212                }
213
214                let cg_elem = self.codegen_operand(bx, elem);
215
216                let try_init_all_same = |bx: &mut Bx, v| {
217                    let start = dest.val.llval;
218                    let size = bx.const_usize(dest.layout.size.bytes());
219
220                    // Use llvm.memset.p0i8.* to initialize all same byte arrays
221                    if let Some(int) = bx.cx().const_to_opt_u128(v, false)
222                        && let bytes = &int.to_le_bytes()[..cg_elem.layout.size.bytes_usize()]
223                        && let Ok(&byte) = bytes.iter().all_equal_value()
224                    {
225                        let fill = bx.cx().const_u8(byte);
226                        bx.memset(start, fill, size, dest.val.align, MemFlags::empty());
227                        return true;
228                    }
229
230                    // Use llvm.memset.p0i8.* to initialize byte arrays
231                    let v = bx.from_immediate(v);
232                    if bx.cx().val_ty(v) == bx.cx().type_i8() {
233                        bx.memset(start, v, size, dest.val.align, MemFlags::empty());
234                        return true;
235                    }
236                    false
237                };
238
239                if let OperandValue::Immediate(v) = cg_elem.val
240                    && try_init_all_same(bx, v)
241                {
242                    return;
243                }
244
245                let count = self
246                    .monomorphize(count)
247                    .try_to_target_usize(bx.tcx())
248                    .expect("expected monomorphic const in codegen");
249
250                bx.write_operand_repeatedly(cg_elem, count, dest);
251            }
252
253            // This implementation does field projection, so never use it for `RawPtr`,
254            // which will always be fine with the `codegen_rvalue_operand` path below.
255            mir::Rvalue::Aggregate(ref kind, ref operands)
256                if !matches!(**kind, mir::AggregateKind::RawPtr(..)) =>
257            {
258                if self.try_codegen_const_aggregate_as_immediate(bx, dest, kind, operands) {
259                    return;
260                }
261
262                let (variant_index, variant_dest, active_field_index) = match **kind {
263                    mir::AggregateKind::Adt(_, variant_index, _, _, active_field_index) => {
264                        let variant_dest = dest.project_downcast(bx, variant_index);
265                        (variant_index, variant_dest, active_field_index)
266                    }
267                    _ => (FIRST_VARIANT, dest, None),
268                };
269                if active_field_index.is_some() {
270                    assert_eq!(operands.len(), 1);
271                }
272                for (i, operand) in operands.iter_enumerated() {
273                    let op = self.codegen_operand(bx, operand);
274                    // Do not generate stores and GEPis for zero-sized fields.
275                    if !op.layout.is_zst() {
276                        let field_index = active_field_index.unwrap_or(i);
277                        let field = if let mir::AggregateKind::Array(_) = **kind {
278                            let llindex = bx.cx().const_usize(field_index.as_u32().into());
279                            variant_dest.project_index(bx, llindex)
280                        } else {
281                            variant_dest.project_field(bx, field_index.as_usize())
282                        };
283                        op.store_with_annotation(bx, field);
284                    }
285                }
286                dest.codegen_set_discr(bx, variant_index);
287            }
288
289            _ => {
290                let temp = self.codegen_rvalue_operand(bx, rvalue);
291                temp.store_with_annotation(bx, dest);
292            }
293        }
294    }
295
296    /// Transmutes the `src` value to the destination type by writing it to `dst`.
297    ///
298    /// See also [`Self::codegen_transmute_operand`] for cases that can be done
299    /// without needing a pre-allocated place for the destination.
300    fn codegen_transmute(
301        &mut self,
302        bx: &mut Bx,
303        src: OperandRef<'tcx, Bx::Value>,
304        dst: PlaceRef<'tcx, Bx::Value>,
305    ) {
306        // The MIR validator enforces no unsized transmutes.
307        if !src.layout.is_sized() {
    ::core::panicking::panic("assertion failed: src.layout.is_sized()")
};assert!(src.layout.is_sized());
308        if !dst.layout.is_sized() {
    ::core::panicking::panic("assertion failed: dst.layout.is_sized()")
};assert!(dst.layout.is_sized());
309
310        if src.layout.size != dst.layout.size
311            || src.layout.is_uninhabited()
312            || dst.layout.is_uninhabited()
313        {
314            // These cases are all UB to actually hit, so don't emit code for them.
315            // (The size mismatches are reachable via `transmute_unchecked`.)
316            bx.unreachable_nonterminator();
317        } else {
318            // Since in this path we have a place anyway, we can store or copy to it,
319            // making sure we use the destination place's alignment even if the
320            // source would normally have a higher one.
321            src.store_with_annotation(bx, dst.val.with_type(src.layout));
322        }
323    }
324
325    /// Transmutes an `OperandValue` to another `OperandValue`.
326    ///
327    /// This is supported for all cases where the `cast` type is SSA,
328    /// but for non-ZSTs with [`abi::BackendRepr::Memory`] it ICEs.
329    pub(crate) fn codegen_transmute_operand(
330        &mut self,
331        bx: &mut Bx,
332        operand: OperandRef<'tcx, Bx::Value>,
333        cast: TyAndLayout<'tcx>,
334    ) -> OperandValue<Bx::Value> {
335        if let abi::BackendRepr::Memory { .. } = cast.backend_repr
336            && !cast.is_zst()
337        {
338            ::rustc_middle::util::bug::span_bug_fmt(self.mir.span,
    format_args!("Use `codegen_transmute` to transmute to {0:?}", cast));span_bug!(self.mir.span, "Use `codegen_transmute` to transmute to {cast:?}");
339        }
340
341        // `Layout` is interned, so we can do a cheap check for things that are
342        // exactly the same and thus don't need any handling.
343        if abi::Layout::eq(&operand.layout.layout, &cast.layout) {
344            return operand.val;
345        }
346
347        // Check for transmutes that are always UB.
348        if operand.layout.size != cast.size
349            || operand.layout.is_uninhabited()
350            || cast.is_uninhabited()
351        {
352            bx.unreachable_nonterminator();
353
354            // We still need to return a value of the appropriate type, but
355            // it's already UB so do the easiest thing available.
356            return OperandValue::poison(bx, cast);
357        }
358
359        // To or from pointers takes different methods, so we use this to restrict
360        // the SimdVector case to types which can be `bitcast` between each other.
361        #[inline]
362        fn vector_can_bitcast(x: abi::Scalar) -> bool {
363            #[allow(non_exhaustive_omitted_patterns)] match x {
    abi::Scalar::Initialized {
        value: abi::Primitive::Int(..) | abi::Primitive::Float(..), .. } =>
        true,
    _ => false,
}matches!(
364                x,
365                abi::Scalar::Initialized {
366                    value: abi::Primitive::Int(..) | abi::Primitive::Float(..),
367                    ..
368                }
369            )
370        }
371
372        let cx = bx.cx();
373        match (operand.val, operand.layout.backend_repr, cast.backend_repr) {
374            _ if cast.is_zst() => OperandValue::ZeroSized,
375            (OperandValue::Ref(source_place_val), abi::BackendRepr::Memory { .. }, _) => {
376                {
    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);
377                // The existing alignment is part of `source_place_val`,
378                // so that alignment will be used, not `cast`'s.
379                bx.load_operand(source_place_val.with_type(cast)).val
380            }
381            (
382                OperandValue::Immediate(imm),
383                abi::BackendRepr::Scalar(from_scalar),
384                abi::BackendRepr::Scalar(to_scalar),
385            ) if from_scalar.size(cx) == to_scalar.size(cx) => {
386                OperandValue::Immediate(transmute_scalar(bx, imm, from_scalar, to_scalar))
387            }
388            (
389                OperandValue::Immediate(imm),
390                abi::BackendRepr::SimdVector { element: from_scalar, .. },
391                abi::BackendRepr::SimdVector { element: to_scalar, .. },
392            ) if vector_can_bitcast(from_scalar) && vector_can_bitcast(to_scalar) => {
393                let to_backend_ty = bx.cx().immediate_backend_type(cast);
394                OperandValue::Immediate(bx.bitcast(imm, to_backend_ty))
395            }
396            (
397                OperandValue::Immediate(imm),
398                abi::BackendRepr::SimdScalableVector { element: from_scalar, .. },
399                abi::BackendRepr::SimdScalableVector { element: to_scalar, .. },
400            ) if vector_can_bitcast(from_scalar) && vector_can_bitcast(to_scalar) => {
401                let to_backend_ty = bx.cx().immediate_backend_type(cast);
402                OperandValue::Immediate(bx.bitcast(imm, to_backend_ty))
403            }
404            (
405                OperandValue::Pair(imm_a, imm_b),
406                abi::BackendRepr::ScalarPair { a: in_a, b: in_b, b_offset: in_offset },
407                abi::BackendRepr::ScalarPair { a: out_a, b: out_b, b_offset: out_offset },
408            ) if in_a.size(cx) == out_a.size(cx)
409                && in_b.size(cx) == out_b.size(cx)
410                && in_offset == out_offset =>
411            {
412                OperandValue::Pair(
413                    transmute_scalar(bx, imm_a, in_a, out_a),
414                    transmute_scalar(bx, imm_b, in_b, out_b),
415                )
416            }
417            _ => {
418                // For any other potentially-tricky cases, make a temporary instead.
419                // If anything else wants the target local to be in memory this won't
420                // be hit, as `codegen_transmute` will get called directly. Thus this
421                // is only for places where everything else wants the operand form,
422                // and thus it's not worth making those places get it from memory.
423                //
424                // Notably, Scalar ⇌ ScalarPair cases go here to avoid padding
425                // and endianness issues, as do SimdVector ones to avoid worrying
426                // about things like f32x8 ⇌ ptrx4 that would need multiple steps.
427                let align = Ord::max(operand.layout.align.abi, cast.align.abi);
428                let size = Ord::max(operand.layout.size, cast.size);
429                let temp = PlaceValue::alloca(bx, size, align);
430                bx.lifetime_start(temp.llval, size);
431                operand.store_with_annotation(bx, temp.with_type(operand.layout));
432                let val = bx.load_operand(temp.with_type(cast)).val;
433                bx.lifetime_end(temp.llval, size);
434                val
435            }
436        }
437    }
438
439    /// Cast one of the immediates from an [`OperandValue::Immediate`]
440    /// or an [`OperandValue::Pair`] to an immediate of the target type.
441    ///
442    /// Returns `None` if the cast is not possible.
443    fn cast_immediate(
444        &self,
445        bx: &mut Bx,
446        mut imm: Bx::Value,
447        from_scalar: abi::Scalar,
448        from_backend_ty: Bx::Type,
449        to_scalar: abi::Scalar,
450        to_backend_ty: Bx::Type,
451    ) -> Option<Bx::Value> {
452        use abi::Primitive::*;
453
454        // When scalars are passed by value, there's no metadata recording their
455        // valid ranges. For example, `char`s are passed as just `i32`, with no
456        // way for LLVM to know that they're 0x10FFFF at most. Thus we assume
457        // the range of the input value too, not just the output range.
458        assume_scalar_range(bx, imm, from_scalar, from_backend_ty, None);
459
460        imm = match (from_scalar.primitive(), to_scalar.primitive()) {
461            (Int(_, is_signed), Int(..)) => bx.intcast(imm, to_backend_ty, is_signed),
462            (Float(_), Float(_)) => {
463                let srcsz = bx.cx().float_width(from_backend_ty);
464                let dstsz = bx.cx().float_width(to_backend_ty);
465                if dstsz > srcsz {
466                    bx.fpext(imm, to_backend_ty)
467                } else if srcsz > dstsz {
468                    bx.fptrunc(imm, to_backend_ty)
469                } else {
470                    imm
471                }
472            }
473            (Int(_, is_signed), Float(_)) => {
474                if is_signed {
475                    bx.sitofp(imm, to_backend_ty)
476                } else {
477                    bx.uitofp(imm, to_backend_ty)
478                }
479            }
480            (Pointer(..), Pointer(..)) => bx.pointercast(imm, to_backend_ty),
481            (Int(_, is_signed), Pointer(..)) => {
482                let usize_imm = bx.intcast(imm, bx.cx().type_isize(), is_signed);
483                bx.inttoptr(usize_imm, to_backend_ty)
484            }
485            (Float(_), Int(_, is_signed)) => bx.cast_float_to_int(is_signed, imm, to_backend_ty),
486            _ => return None,
487        };
488        Some(imm)
489    }
490
491    pub(crate) fn codegen_rvalue_operand(
492        &mut self,
493        bx: &mut Bx,
494        rvalue: &mir::Rvalue<'tcx>,
495    ) -> OperandRef<'tcx, Bx::Value> {
496        match *rvalue {
497            mir::Rvalue::Cast(ref kind, ref source, mir_cast_ty) => {
498                let operand = self.codegen_operand(bx, source);
499                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/rvalue.rs:499",
                        "rustc_codegen_ssa::mir::rvalue", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/rvalue.rs"),
                        ::tracing_core::__macro_support::Option::Some(499u32),
                        ::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);
500                let cast = bx.cx().layout_of(self.monomorphize(mir_cast_ty));
501
502                let val = match *kind {
503                    mir::CastKind::PointerExposeProvenance => {
504                        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());
505                        let llptr = operand.immediate();
506                        let llcast_ty = bx.cx().immediate_backend_type(cast);
507                        let lladdr = bx.ptrtoint(llptr, llcast_ty);
508                        OperandValue::Immediate(lladdr)
509                    }
510                    mir::CastKind::PointerCoercion(PointerCoercion::ReifyFnPointer(_), _) => {
511                        match *operand.layout.ty.kind() {
512                            ty::FnDef(def_id, args) => {
513                                let instance = ty::Instance::resolve_for_fn_ptr(
514                                    bx.tcx(),
515                                    bx.typing_env(),
516                                    def_id,
517                                    args.no_bound_vars().unwrap(),
518                                )
519                                .unwrap();
520                                OperandValue::Immediate(
521                                    bx.get_fn_addr(
522                                        instance,
523                                        bx.sess().pointer_authentication_functions(),
524                                    ),
525                                )
526                            }
527                            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("{0} cannot be reified to a fn ptr",
        operand.layout.ty))bug!("{} cannot be reified to a fn ptr", operand.layout.ty),
528                        }
529                    }
530                    mir::CastKind::PointerCoercion(PointerCoercion::ClosureFnPointer(_), _) => {
531                        match *operand.layout.ty.kind() {
532                            ty::Closure(def_id, args) => {
533                                let instance = Instance::resolve_closure(
534                                    bx.cx().tcx(),
535                                    def_id,
536                                    args,
537                                    ty::ClosureKind::FnOnce,
538                                );
539                                OperandValue::Immediate(
540                                    bx.cx().get_fn_addr(
541                                        instance,
542                                        bx.sess().pointer_authentication_functions(),
543                                    ),
544                                )
545                            }
546                            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("{0} cannot be cast to a fn ptr",
        operand.layout.ty))bug!("{} cannot be cast to a fn ptr", operand.layout.ty),
547                        }
548                    }
549                    mir::CastKind::PointerCoercion(PointerCoercion::UnsafeFnPointer, _) => {
550                        // This is a no-op at the LLVM level.
551                        operand.val
552                    }
553                    mir::CastKind::PointerCoercion(PointerCoercion::Unsize, _) => {
554                        {
    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 { .. });
555                        let (lldata, llextra) = operand.val.pointer_parts();
556                        let (lldata, llextra) =
557                            base::unsize_ptr(bx, lldata, operand.layout.ty, cast.ty, llextra);
558                        OperandValue::Pair(lldata, llextra)
559                    }
560                    mir::CastKind::PointerCoercion(
561                        PointerCoercion::MutToConstPointer | PointerCoercion::ArrayToPointer,
562                        _,
563                    ) => {
564                        ::rustc_middle::util::bug::bug_fmt(format_args!("{0:?} is for borrowck, and should never appear in codegen",
        kind));bug!("{kind:?} is for borrowck, and should never appear in codegen");
565                    }
566                    mir::CastKind::PtrToPtr if let BackendRepr::ScalarPair { .. } = operand.layout.backend_repr => {
567                        if let OperandValue::Pair(data_ptr, meta) = operand.val {
568                            if let BackendRepr::ScalarPair { .. } = cast.layout.backend_repr {
569                                OperandValue::Pair(data_ptr, meta)
570                            } else {
571                                // Cast of wide-ptr to thin-ptr is an extraction of data-ptr.
572                                OperandValue::Immediate(data_ptr)
573                            }
574                        } else {
575                            ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected non-pair operand"));bug!("unexpected non-pair operand");
576                        }
577                    }
578                    | mir::CastKind::IntToInt
579                    | mir::CastKind::FloatToInt
580                    | mir::CastKind::FloatToFloat
581                    | mir::CastKind::IntToFloat
582                    | mir::CastKind::PtrToPtr
583                    | mir::CastKind::FnPtrToPtr
584                    // Since int2ptr can have arbitrary integer types as input (so we have to do
585                    // sign extension and all that), it is currently best handled in the same code
586                    // path as the other integer-to-X casts.
587                    | mir::CastKind::PointerWithExposedProvenance => {
588                        let imm = operand.immediate();
589                        let abi::BackendRepr::Scalar(from_scalar) = operand.layout.backend_repr
590                        else {
591                            ::rustc_middle::util::bug::bug_fmt(format_args!("Found non-scalar for operand {0:?}",
        operand));bug!("Found non-scalar for operand {operand:?}");
592                        };
593                        let from_backend_ty = bx.cx().immediate_backend_type(operand.layout);
594
595                        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());
596                        let to_backend_ty = bx.cx().immediate_backend_type(cast);
597                        if operand.layout.is_uninhabited() {
598                            let val = OperandValue::Immediate(bx.cx().const_poison(to_backend_ty));
599                            return OperandRef { val, layout: cast, move_annotation: None };
600                        }
601                        let abi::BackendRepr::Scalar(to_scalar) = cast.layout.backend_repr else {
602                            ::rustc_middle::util::bug::bug_fmt(format_args!("Found non-scalar for cast {0:?}",
        cast));bug!("Found non-scalar for cast {cast:?}");
603                        };
604
605                        self.cast_immediate(
606                            bx,
607                            imm,
608                            from_scalar,
609                            from_backend_ty,
610                            to_scalar,
611                            to_backend_ty,
612                        )
613                        .map(OperandValue::Immediate)
614                        .unwrap_or_else(|| {
615                            ::rustc_middle::util::bug::bug_fmt(format_args!("Unsupported cast of {0:?} to {1:?}",
        operand, cast));bug!("Unsupported cast of {operand:?} to {cast:?}");
616                        })
617                    }
618                    mir::CastKind::Transmute | mir::CastKind::Subtype => {
619                        self.codegen_transmute_operand(bx, operand, cast)
620                    }
621                };
622                OperandRef { val, layout: cast, move_annotation: None }
623            }
624
625            mir::Rvalue::Ref(_, bk, place) => {
626                let mk_ref = move |tcx: TyCtxt<'tcx>, ty: Ty<'tcx>| {
627                    Ty::new_ref(tcx, tcx.lifetimes.re_erased, ty, bk.to_mutbl_lossy())
628                };
629                let op = self.codegen_place_to_pointer(bx, place, mk_ref);
630                if self.cx.tcx().sess.opts.unstable_opts.codegen_emit_retag.is_some() {
631                    self.codegen_retag_operand(bx, op, false)
632                } else {
633                    op
634                }
635            }
636
637            // Note: Exclusive reborrowing is always equal to a memcpy, as the types do not change.
638            // Generic shared reborrowing is not (necessarily) a simple memcpy, but currently the
639            // coherence check places such restrictions on the CoerceShared trait as to guarantee
640            // that it is.
641            mir::Rvalue::Reborrow(_, _, place) => {
642                self.codegen_operand(bx, &mir::Operand::Copy(place))
643            }
644
645            mir::Rvalue::RawPtr(kind, place) => {
646                let mk_ptr = move |tcx: TyCtxt<'tcx>, ty: Ty<'tcx>| {
647                    Ty::new_ptr(tcx, ty, kind.to_mutbl_lossy())
648                };
649                self.codegen_place_to_pointer(bx, place, mk_ptr)
650            }
651
652            mir::Rvalue::BinaryOp(op_with_overflow, (ref lhs, ref rhs))
653                if let Some(op) = op_with_overflow.overflowing_to_wrapping() =>
654            {
655                let lhs = self.codegen_operand(bx, lhs);
656                let rhs = self.codegen_operand(bx, rhs);
657                let result = self.codegen_scalar_checked_binop(
658                    bx,
659                    op,
660                    lhs.immediate(),
661                    rhs.immediate(),
662                    lhs.layout.ty,
663                );
664                let val_ty = op.ty(bx.tcx(), lhs.layout.ty, rhs.layout.ty);
665                let operand_ty = Ty::new_tup(bx.tcx(), &[val_ty, bx.tcx().types.bool]);
666                OperandRef {
667                    val: result,
668                    layout: bx.cx().layout_of(operand_ty),
669                    move_annotation: None,
670                }
671            }
672
673            mir::Rvalue::BinaryOp(op, (ref lhs, ref rhs)) => {
674                let lhs = self.codegen_operand(bx, lhs);
675                let rhs = self.codegen_operand(bx, rhs);
676                let llresult = match (lhs.val, rhs.val) {
677                    (
678                        OperandValue::Pair(lhs_addr, lhs_extra),
679                        OperandValue::Pair(rhs_addr, rhs_extra),
680                    ) => self.codegen_wide_ptr_binop(
681                        bx,
682                        op,
683                        lhs_addr,
684                        lhs_extra,
685                        rhs_addr,
686                        rhs_extra,
687                        lhs.layout.ty,
688                    ),
689
690                    (OperandValue::Immediate(lhs_val), OperandValue::Immediate(rhs_val)) => self
691                        .codegen_scalar_binop(
692                            bx,
693                            op,
694                            lhs_val,
695                            rhs_val,
696                            lhs.layout.ty,
697                            rhs.layout.ty,
698                        ),
699
700                    _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
701                };
702                OperandRef {
703                    val: OperandValue::Immediate(llresult),
704                    layout: bx.cx().layout_of(op.ty(bx.tcx(), lhs.layout.ty, rhs.layout.ty)),
705                    move_annotation: None,
706                }
707            }
708
709            mir::Rvalue::UnaryOp(op, ref operand) => {
710                let operand = self.codegen_operand(bx, operand);
711                let is_float = operand.layout.ty.is_floating_point();
712                let (val, layout) = match op {
713                    mir::UnOp::Not => {
714                        let llval = bx.not(operand.immediate());
715                        (OperandValue::Immediate(llval), operand.layout)
716                    }
717                    mir::UnOp::Neg => {
718                        let llval = if is_float {
719                            bx.fneg(operand.immediate())
720                        } else {
721                            bx.neg(operand.immediate())
722                        };
723                        (OperandValue::Immediate(llval), operand.layout)
724                    }
725                    mir::UnOp::PtrMetadata => {
726                        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(),);
727                        let (_, meta) = operand.val.pointer_parts();
728                        {
    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());
729                        if let Some(meta) = meta {
730                            (OperandValue::Immediate(meta), operand.layout.field(self.cx, 1))
731                        } else {
732                            (OperandValue::ZeroSized, bx.cx().layout_of(bx.tcx().types.unit))
733                        }
734                    }
735                };
736                if !val.is_expected_variant_for_type(layout) {
    {
        ::core::panicking::panic_fmt(format_args!("Made wrong variant {0:?} for type {1:?}",
                val, layout));
    }
};assert!(
737                    val.is_expected_variant_for_type(layout),
738                    "Made wrong variant {val:?} for type {layout:?}",
739                );
740                OperandRef { val, layout, move_annotation: None }
741            }
742
743            mir::Rvalue::Discriminant(ref place) => {
744                let discr_ty = rvalue.ty(self.mir, bx.tcx());
745                let discr_ty = self.monomorphize(discr_ty);
746                let operand = self.codegen_consume(bx, place.as_ref());
747                let discr = operand.codegen_get_discr(self, bx, discr_ty);
748                OperandRef {
749                    val: OperandValue::Immediate(discr),
750                    layout: self.cx.layout_of(discr_ty),
751                    move_annotation: None,
752                }
753            }
754
755            mir::Rvalue::ThreadLocalRef(def_id) => {
756                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));
757                let layout = bx.layout_of(bx.cx().tcx().static_ptr_ty(def_id, bx.typing_env()));
758                let static_ = if !def_id.is_local() && bx.cx().tcx().needs_thread_local_shim(def_id)
759                {
760                    let instance = ty::Instance {
761                        def: ty::InstanceKind::Shim(ty::ShimKind::ThreadLocal(def_id)),
762                        args: ty::GenericArgs::empty(),
763                    };
764                    let fn_ptr =
765                        bx.get_fn_addr(instance, bx.sess().pointer_authentication_functions());
766                    let fn_abi = bx.fn_abi_of_instance(instance, ty::List::empty());
767                    let fn_ty = bx.fn_decl_backend_type(fn_abi);
768                    let fn_attrs = if bx.tcx().def_kind(instance.def_id()).has_codegen_attrs() {
769                        Some(bx.tcx().codegen_instance_attrs(instance.def))
770                    } else {
771                        None
772                    };
773                    bx.call(
774                        fn_ty,
775                        fn_attrs.as_deref(),
776                        Some(fn_abi),
777                        fn_ptr,
778                        &[],
779                        None,
780                        Some(instance),
781                    )
782                } else {
783                    bx.get_static(def_id)
784                };
785                OperandRef { val: OperandValue::Immediate(static_), layout, move_annotation: None }
786            }
787
788            mir::Rvalue::Use(ref operand, _) => self.codegen_operand(bx, operand),
789
790            mir::Rvalue::Repeat(ref elem, len_const) => {
791                // All arrays have `BackendRepr::Memory`, so only the ZST cases
792                // end up here. Anything else forces the destination local to be
793                // `Memory`, and thus ends up handled in `codegen_rvalue` instead.
794                let operand = self.codegen_operand(bx, elem);
795                let array_ty = Ty::new_array_with_const_len(bx.tcx(), operand.layout.ty, len_const);
796                let array_ty = self.monomorphize(array_ty);
797                let array_layout = bx.layout_of(array_ty);
798                if !array_layout.is_zst() {
    ::core::panicking::panic("assertion failed: array_layout.is_zst()")
};assert!(array_layout.is_zst());
799                OperandRef {
800                    val: OperandValue::ZeroSized,
801                    layout: array_layout,
802                    move_annotation: None,
803                }
804            }
805
806            mir::Rvalue::Aggregate(ref kind, ref fields) => {
807                let (variant_index, active_field_index) = match **kind {
808                    mir::AggregateKind::Adt(_, variant_index, _, _, active_field_index) => {
809                        (variant_index, active_field_index)
810                    }
811                    _ => (FIRST_VARIANT, None),
812                };
813
814                let ty = rvalue.ty(self.mir, self.cx.tcx());
815                let ty = self.monomorphize(ty);
816                let layout = self.cx.layout_of(ty);
817
818                let mut builder = OperandRefBuilder::new(layout);
819                for (field_idx, field) in fields.iter_enumerated() {
820                    let op = self.codegen_operand(bx, field);
821                    let fi = active_field_index.unwrap_or(field_idx);
822                    builder.insert_field(bx, variant_index, fi, op);
823                }
824
825                let tag_result = codegen_tag_value(self.cx, variant_index, layout);
826                match tag_result {
827                    Err(super::place::UninhabitedVariantError) => {
828                        // Like codegen_set_discr we use a sound abort, but could
829                        // potentially `unreachable` or just return the poison for
830                        // more optimizability, if that turns out to be helpful.
831                        bx.abort();
832                        let val = OperandValue::poison(bx, layout);
833                        OperandRef { val, layout, move_annotation: None }
834                    }
835                    Ok(maybe_tag_value) => {
836                        if let Some((tag_field, tag_imm)) = maybe_tag_value {
837                            builder.insert_imm(tag_field, tag_imm);
838                        }
839                        builder.build(bx.cx())
840                    }
841                }
842            }
843
844            mir::Rvalue::WrapUnsafeBinder(ref operand, binder_ty) => {
845                let operand = self.codegen_operand(bx, operand);
846                let binder_ty = self.monomorphize(binder_ty);
847                let layout = bx.cx().layout_of(binder_ty);
848                OperandRef { val: operand.val, layout, move_annotation: None }
849            }
850
851            mir::Rvalue::CopyForDeref(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("`CopyForDeref` in codegen"))bug!("`CopyForDeref` in codegen"),
852        }
853    }
854
855    /// Codegen an `Rvalue::RawPtr` or `Rvalue::Ref`
856    fn codegen_place_to_pointer(
857        &mut self,
858        bx: &mut Bx,
859        place: mir::Place<'tcx>,
860        mk_ptr_ty: impl FnOnce(TyCtxt<'tcx>, Ty<'tcx>) -> Ty<'tcx>,
861    ) -> OperandRef<'tcx, Bx::Value> {
862        let cg_place = self.codegen_place(bx, place.as_ref());
863        let val = cg_place.val.address();
864
865        let ty = cg_place.layout.ty;
866        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!(
867            if bx.cx().tcx().type_has_metadata(ty, bx.cx().typing_env()) {
868                matches!(val, OperandValue::Pair(..))
869            } else {
870                matches!(val, OperandValue::Immediate(..))
871            },
872            "Address of place was unexpectedly {val:?} for pointee type {ty:?}",
873        );
874
875        OperandRef {
876            val,
877            layout: self.cx.layout_of(mk_ptr_ty(self.cx.tcx(), ty)),
878            move_annotation: None,
879        }
880    }
881
882    fn codegen_scalar_binop(
883        &mut self,
884        bx: &mut Bx,
885        op: mir::BinOp,
886        lhs: Bx::Value,
887        rhs: Bx::Value,
888        lhs_ty: Ty<'tcx>,
889        rhs_ty: Ty<'tcx>,
890    ) -> Bx::Value {
891        let is_float = lhs_ty.is_floating_point();
892        let is_signed = lhs_ty.is_signed();
893        match op {
894            mir::BinOp::Add => {
895                if is_float {
896                    bx.fadd(lhs, rhs)
897                } else {
898                    bx.add(lhs, rhs)
899                }
900            }
901            mir::BinOp::AddUnchecked => {
902                if is_signed {
903                    bx.unchecked_sadd(lhs, rhs)
904                } else {
905                    bx.unchecked_uadd(lhs, rhs)
906                }
907            }
908            mir::BinOp::Sub => {
909                if is_float {
910                    bx.fsub(lhs, rhs)
911                } else {
912                    bx.sub(lhs, rhs)
913                }
914            }
915            mir::BinOp::SubUnchecked => {
916                if is_signed {
917                    bx.unchecked_ssub(lhs, rhs)
918                } else {
919                    bx.unchecked_usub(lhs, rhs)
920                }
921            }
922            mir::BinOp::Mul => {
923                if is_float {
924                    bx.fmul(lhs, rhs)
925                } else {
926                    bx.mul(lhs, rhs)
927                }
928            }
929            mir::BinOp::MulUnchecked => {
930                if is_signed {
931                    bx.unchecked_smul(lhs, rhs)
932                } else {
933                    bx.unchecked_umul(lhs, rhs)
934                }
935            }
936            mir::BinOp::Div => {
937                if is_float {
938                    bx.fdiv(lhs, rhs)
939                } else if is_signed {
940                    bx.sdiv(lhs, rhs)
941                } else {
942                    bx.udiv(lhs, rhs)
943                }
944            }
945            mir::BinOp::Rem => {
946                if is_float {
947                    bx.frem(lhs, rhs)
948                } else if is_signed {
949                    bx.srem(lhs, rhs)
950                } else {
951                    bx.urem(lhs, rhs)
952                }
953            }
954            mir::BinOp::BitOr => bx.or(lhs, rhs),
955            mir::BinOp::BitAnd => bx.and(lhs, rhs),
956            mir::BinOp::BitXor => bx.xor(lhs, rhs),
957            mir::BinOp::Offset => {
958                let pointee_type = lhs_ty
959                    .builtin_deref(true)
960                    .unwrap_or_else(|| ::rustc_middle::util::bug::bug_fmt(format_args!("deref of non-pointer {0:?}",
        lhs_ty))bug!("deref of non-pointer {:?}", lhs_ty));
961                let pointee_layout = bx.cx().layout_of(pointee_type);
962                if pointee_layout.is_zst() {
963                    // `Offset` works in terms of the size of pointee,
964                    // so offsetting a pointer to ZST is a noop.
965                    lhs
966                } else {
967                    let llty = bx.cx().backend_type(pointee_layout);
968                    if !rhs_ty.is_signed() {
969                        bx.inbounds_nuw_gep(llty, lhs, &[rhs])
970                    } else {
971                        bx.inbounds_gep(llty, lhs, &[rhs])
972                    }
973                }
974            }
975            mir::BinOp::Shl | mir::BinOp::ShlUnchecked => {
976                let rhs = base::build_shift_expr_rhs(bx, lhs, rhs, op == mir::BinOp::ShlUnchecked);
977                bx.shl(lhs, rhs)
978            }
979            mir::BinOp::Shr | mir::BinOp::ShrUnchecked => {
980                let rhs = base::build_shift_expr_rhs(bx, lhs, rhs, op == mir::BinOp::ShrUnchecked);
981                if is_signed { bx.ashr(lhs, rhs) } else { bx.lshr(lhs, rhs) }
982            }
983            mir::BinOp::Ne
984            | mir::BinOp::Lt
985            | mir::BinOp::Gt
986            | mir::BinOp::Eq
987            | mir::BinOp::Le
988            | mir::BinOp::Ge => {
989                if is_float {
990                    bx.fcmp(base::bin_op_to_fcmp_predicate(op), lhs, rhs)
991                } else {
992                    bx.icmp(base::bin_op_to_icmp_predicate(op, is_signed), lhs, rhs)
993                }
994            }
995            mir::BinOp::Cmp => {
996                if !!is_float { ::core::panicking::panic("assertion failed: !is_float") };assert!(!is_float);
997                bx.three_way_compare(lhs_ty, lhs, rhs)
998            }
999            mir::BinOp::AddWithOverflow
1000            | mir::BinOp::SubWithOverflow
1001            | mir::BinOp::MulWithOverflow => {
1002                ::rustc_middle::util::bug::bug_fmt(format_args!("{0:?} needs to return a pair, so call codegen_scalar_checked_binop instead",
        op))bug!("{op:?} needs to return a pair, so call codegen_scalar_checked_binop instead")
1003            }
1004        }
1005    }
1006
1007    fn codegen_wide_ptr_binop(
1008        &mut self,
1009        bx: &mut Bx,
1010        op: mir::BinOp,
1011        lhs_addr: Bx::Value,
1012        lhs_extra: Bx::Value,
1013        rhs_addr: Bx::Value,
1014        rhs_extra: Bx::Value,
1015        _input_ty: Ty<'tcx>,
1016    ) -> Bx::Value {
1017        match op {
1018            mir::BinOp::Eq => {
1019                let lhs = bx.icmp(IntPredicate::IntEQ, lhs_addr, rhs_addr);
1020                let rhs = bx.icmp(IntPredicate::IntEQ, lhs_extra, rhs_extra);
1021                bx.and(lhs, rhs)
1022            }
1023            mir::BinOp::Ne => {
1024                let lhs = bx.icmp(IntPredicate::IntNE, lhs_addr, rhs_addr);
1025                let rhs = bx.icmp(IntPredicate::IntNE, lhs_extra, rhs_extra);
1026                bx.or(lhs, rhs)
1027            }
1028            mir::BinOp::Le | mir::BinOp::Lt | mir::BinOp::Ge | mir::BinOp::Gt => {
1029                // a OP b ~ a.0 STRICT(OP) b.0 | (a.0 == b.0 && a.1 OP a.1)
1030                let (op, strict_op) = match op {
1031                    mir::BinOp::Lt => (IntPredicate::IntULT, IntPredicate::IntULT),
1032                    mir::BinOp::Le => (IntPredicate::IntULE, IntPredicate::IntULT),
1033                    mir::BinOp::Gt => (IntPredicate::IntUGT, IntPredicate::IntUGT),
1034                    mir::BinOp::Ge => (IntPredicate::IntUGE, IntPredicate::IntUGT),
1035                    _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
1036                };
1037                let lhs = bx.icmp(strict_op, lhs_addr, rhs_addr);
1038                let and_lhs = bx.icmp(IntPredicate::IntEQ, lhs_addr, rhs_addr);
1039                let and_rhs = bx.icmp(op, lhs_extra, rhs_extra);
1040                let rhs = bx.and(and_lhs, and_rhs);
1041                bx.or(lhs, rhs)
1042            }
1043            _ => {
1044                ::rustc_middle::util::bug::bug_fmt(format_args!("unexpected wide ptr binop"));bug!("unexpected wide ptr binop");
1045            }
1046        }
1047    }
1048
1049    fn codegen_scalar_checked_binop(
1050        &mut self,
1051        bx: &mut Bx,
1052        op: mir::BinOp,
1053        lhs: Bx::Value,
1054        rhs: Bx::Value,
1055        input_ty: Ty<'tcx>,
1056    ) -> OperandValue<Bx::Value> {
1057        let (val, of) = match op {
1058            // These are checked using intrinsics
1059            mir::BinOp::Add | mir::BinOp::Sub | mir::BinOp::Mul => {
1060                let oop = match op {
1061                    mir::BinOp::Add => OverflowOp::Add,
1062                    mir::BinOp::Sub => OverflowOp::Sub,
1063                    mir::BinOp::Mul => OverflowOp::Mul,
1064                    _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1065                };
1066                bx.checked_binop(oop, input_ty, lhs, rhs)
1067            }
1068            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("Operator `{0:?}` is not a checkable operator",
        op))bug!("Operator `{:?}` is not a checkable operator", op),
1069        };
1070
1071        OperandValue::Pair(val, of)
1072    }
1073}
1074
1075/// Transmutes a single scalar value `imm` from `from_scalar` to `to_scalar`.
1076///
1077/// This is expected to be in *immediate* form, as seen in [`OperandValue::Immediate`]
1078/// or [`OperandValue::Pair`] (so `i1` for bools, not `i8`, for example).
1079///
1080/// ICEs if the passed-in `imm` is not a value of the expected type for
1081/// `from_scalar`, such as if it's a vector or a pair.
1082pub(super) fn transmute_scalar<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
1083    bx: &mut Bx,
1084    mut imm: Bx::Value,
1085    from_scalar: abi::Scalar,
1086    to_scalar: abi::Scalar,
1087) -> Bx::Value {
1088    {
    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()));
1089    let imm_ty = bx.cx().val_ty(imm);
1090    {
    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!(
1091        bx.cx().type_kind(imm_ty),
1092        TypeKind::Vector,
1093        "Vector type {imm_ty:?} not allowed in transmute_scalar {from_scalar:?} -> {to_scalar:?}"
1094    );
1095
1096    // While optimizations will remove no-op transmutes, they might still be
1097    // there in debug or things that aren't no-op in MIR because they change
1098    // the Rust type but not the underlying layout/niche.
1099    if from_scalar == to_scalar {
1100        return imm;
1101    }
1102
1103    use abi::Primitive::*;
1104    imm = bx.from_immediate(imm);
1105
1106    let from_backend_ty = bx.cx().type_from_scalar(from_scalar);
1107    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);
1108    let to_backend_ty = bx.cx().type_from_scalar(to_scalar);
1109
1110    // If we have a scalar, we must already know its range. Either
1111    //
1112    // 1) It's a parameter with `range` parameter metadata,
1113    // 2) It's something we `load`ed with `!range` metadata, or
1114    // 3) After a transmute we `assume`d the range (see below).
1115    //
1116    // That said, last time we tried removing this, it didn't actually help
1117    // the rustc-perf results, so might as well keep doing it
1118    // <https://github.com/rust-lang/rust/pull/135610#issuecomment-2599275182>
1119    assume_scalar_range(bx, imm, from_scalar, from_backend_ty, Some(&to_scalar));
1120
1121    imm = match (from_scalar.primitive(), to_scalar.primitive()) {
1122        (Int(..) | Float(_), Int(..) | Float(_)) => bx.bitcast(imm, to_backend_ty),
1123        (Pointer(..), Pointer(..)) => bx.pointercast(imm, to_backend_ty),
1124        (Int(..), Pointer(..)) => bx.inttoptr(imm, to_backend_ty),
1125        (Pointer(..), Int(..)) => {
1126            // FIXME: this exposes the provenance, which shouldn't be necessary.
1127            bx.ptrtoint(imm, to_backend_ty)
1128        }
1129        (Float(_), Pointer(..)) => {
1130            let int_imm = bx.bitcast(imm, bx.cx().type_isize());
1131            bx.inttoptr(int_imm, to_backend_ty)
1132        }
1133        (Pointer(..), Float(_)) => {
1134            // FIXME: this exposes the provenance, which shouldn't be necessary.
1135            let int_imm = bx.ptrtoint(imm, bx.cx().type_isize());
1136            bx.bitcast(int_imm, to_backend_ty)
1137        }
1138    };
1139
1140    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);
1141
1142    // This `assume` remains important for cases like (a conceptual)
1143    //    transmute::<u32, NonZeroU32>(x) == 0
1144    // since it's never passed to something with parameter metadata (especially
1145    // after MIR inlining) so the only way to tell the backend about the
1146    // constraint that the `transmute` introduced is to `assume` it.
1147    assume_scalar_range(bx, imm, to_scalar, to_backend_ty, Some(&from_scalar));
1148
1149    imm = bx.to_immediate_scalar(imm, to_scalar);
1150    imm
1151}
1152
1153/// Emits an `assume` call that `imm`'s value is within the known range of `scalar`.
1154///
1155/// If `known` is `Some`, only emits the assume if it's more specific than
1156/// whatever is already known from the range of *that* scalar.
1157fn assume_scalar_range<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
1158    bx: &mut Bx,
1159    imm: Bx::Value,
1160    scalar: abi::Scalar,
1161    backend_ty: Bx::Type,
1162    known: Option<&abi::Scalar>,
1163) {
1164    if #[allow(non_exhaustive_omitted_patterns)] match bx.cx().sess().opts.optimize {
    OptLevel::No => true,
    _ => false,
}matches!(bx.cx().sess().opts.optimize, OptLevel::No) {
1165        return;
1166    }
1167
1168    match (scalar, known) {
1169        (abi::Scalar::Union { .. }, _) => return,
1170        (_, None) => {
1171            if scalar.is_always_valid(bx.cx()) {
1172                return;
1173            }
1174        }
1175        (abi::Scalar::Initialized { valid_range, .. }, Some(known)) => {
1176            let known_range = known.valid_range(bx.cx());
1177            if valid_range.contains_range(known_range, scalar.size(bx.cx())) {
1178                return;
1179            }
1180        }
1181    }
1182
1183    match scalar.primitive() {
1184        abi::Primitive::Int(..) => {
1185            let range = scalar.valid_range(bx.cx());
1186            bx.assume_integer_range(imm, backend_ty, range);
1187        }
1188        abi::Primitive::Pointer(abi::AddressSpace::ZERO)
1189            if !scalar.valid_range(bx.cx()).contains(0) =>
1190        {
1191            bx.assume_nonnull(imm);
1192        }
1193        abi::Primitive::Pointer(..) | abi::Primitive::Float(..) => {}
1194    }
1195}