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