Skip to main content

rustc_codegen_ssa/mir/
rvalue.rs

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