rustc_codegen_ssa/mir/
rvalue.rs

1use std::assert_matches::assert_matches;
2
3use arrayvec::ArrayVec;
4use rustc_abi::{self as abi, FIRST_VARIANT, FieldIdx};
5use rustc_middle::ty::adjustment::PointerCoercion;
6use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf, TyAndLayout};
7use rustc_middle::ty::{self, Instance, Ty, TyCtxt};
8use rustc_middle::{bug, mir, span_bug};
9use rustc_session::config::OptLevel;
10use rustc_span::{DUMMY_SP, Span};
11use tracing::{debug, instrument, trace};
12
13use super::operand::{OperandRef, OperandValue};
14use super::place::PlaceRef;
15use super::{FunctionCx, LocalRef};
16use crate::common::IntPredicate;
17use crate::traits::*;
18use crate::{MemFlags, base};
19
20impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
21    #[instrument(level = "trace", skip(self, bx))]
22    pub(crate) fn codegen_rvalue(
23        &mut self,
24        bx: &mut Bx,
25        dest: PlaceRef<'tcx, Bx::Value>,
26        rvalue: &mir::Rvalue<'tcx>,
27    ) {
28        match *rvalue {
29            mir::Rvalue::Use(ref operand) => {
30                let cg_operand = self.codegen_operand(bx, operand);
31                // FIXME: consider not copying constants through stack. (Fixable by codegen'ing
32                // constants into `OperandValue::Ref`; why don’t we do that yet if we don’t?)
33                cg_operand.val.store(bx, dest);
34            }
35
36            mir::Rvalue::Cast(
37                mir::CastKind::PointerCoercion(PointerCoercion::Unsize, _),
38                ref source,
39                _,
40            ) => {
41                // The destination necessarily contains a wide pointer, so if
42                // it's a scalar pair, it's a wide pointer or newtype thereof.
43                if bx.cx().is_backend_scalar_pair(dest.layout) {
44                    // Into-coerce of a thin pointer to a wide pointer -- just
45                    // use the operand path.
46                    let temp = self.codegen_rvalue_operand(bx, rvalue);
47                    temp.val.store(bx, dest);
48                    return;
49                }
50
51                // Unsize of a nontrivial struct. I would prefer for
52                // this to be eliminated by MIR building, but
53                // `CoerceUnsized` can be passed by a where-clause,
54                // so the (generic) MIR may not be able to expand it.
55                let operand = self.codegen_operand(bx, source);
56                match operand.val {
57                    OperandValue::Pair(..) | OperandValue::Immediate(_) => {
58                        // Unsize from an immediate structure. We don't
59                        // really need a temporary alloca here, but
60                        // avoiding it would require us to have
61                        // `coerce_unsized_into` use `extractvalue` to
62                        // index into the struct, and this case isn't
63                        // important enough for it.
64                        debug!("codegen_rvalue: creating ugly alloca");
65                        let scratch = PlaceRef::alloca(bx, operand.layout);
66                        scratch.storage_live(bx);
67                        operand.val.store(bx, scratch);
68                        base::coerce_unsized_into(bx, scratch, dest);
69                        scratch.storage_dead(bx);
70                    }
71                    OperandValue::Ref(val) => {
72                        if val.llextra.is_some() {
73                            bug!("unsized coercion on an unsized rvalue");
74                        }
75                        base::coerce_unsized_into(bx, val.with_type(operand.layout), dest);
76                    }
77                    OperandValue::ZeroSized => {
78                        bug!("unsized coercion on a ZST rvalue");
79                    }
80                }
81            }
82
83            mir::Rvalue::Cast(mir::CastKind::Transmute, ref operand, _ty) => {
84                let src = self.codegen_operand(bx, operand);
85                self.codegen_transmute(bx, src, dest);
86            }
87
88            mir::Rvalue::Repeat(ref elem, count) => {
89                let cg_elem = self.codegen_operand(bx, elem);
90
91                // Do not generate the loop for zero-sized elements or empty arrays.
92                if dest.layout.is_zst() {
93                    return;
94                }
95
96                // If `v` is an integer constant whose value is just a single byte repeated N times,
97                // emit a `memset` filling the entire `dest` with that byte.
98                let try_init_all_same = |bx: &mut Bx, v| {
99                    let start = dest.val.llval;
100                    let size = bx.const_usize(dest.layout.size.bytes());
101
102                    // Use llvm.memset.p0i8.* to initialize all same byte arrays
103                    if let Some(int) = bx.cx().const_to_opt_u128(v, false) {
104                        let bytes = &int.to_le_bytes()[..cg_elem.layout.size.bytes_usize()];
105                        let first = bytes[0];
106                        if bytes[1..].iter().all(|&b| b == first) {
107                            let fill = bx.cx().const_u8(first);
108                            bx.memset(start, fill, size, dest.val.align, MemFlags::empty());
109                            return true;
110                        }
111                    }
112
113                    // Use llvm.memset.p0i8.* to initialize byte arrays
114                    let v = bx.from_immediate(v);
115                    if bx.cx().val_ty(v) == bx.cx().type_i8() {
116                        bx.memset(start, v, size, dest.val.align, MemFlags::empty());
117                        return true;
118                    }
119                    false
120                };
121
122                trace!(?cg_elem.val);
123                match cg_elem.val {
124                    OperandValue::Immediate(v) => {
125                        if try_init_all_same(bx, v) {
126                            return;
127                        }
128                    }
129                    OperandValue::Pair(a, b) => {
130                        let a_is_undef = bx.cx().is_undef(a);
131                        match (a_is_undef, bx.cx().is_undef(b)) {
132                            // Can happen for uninit unions
133                            (true, true) => {
134                                // FIXME: can we produce better output here?
135                            }
136                            (false, true) | (true, false) => {
137                                let val = if a_is_undef { b } else { a };
138                                if try_init_all_same(bx, val) {
139                                    return;
140                                }
141                            }
142                            (false, false) => {
143                                // FIXME: if both are the same value, use try_init_all_same
144                            }
145                        }
146                    }
147                    OperandValue::ZeroSized => unreachable!("checked above"),
148                    OperandValue::Ref(..) => {}
149                }
150
151                let count = self
152                    .monomorphize(count)
153                    .try_to_target_usize(bx.tcx())
154                    .expect("expected monomorphic const in codegen");
155
156                bx.write_operand_repeatedly(cg_elem, count, dest);
157            }
158
159            // This implementation does field projection, so never use it for `RawPtr`,
160            // which will always be fine with the `codegen_rvalue_operand` path below.
161            mir::Rvalue::Aggregate(ref kind, ref operands)
162                if !matches!(**kind, mir::AggregateKind::RawPtr(..)) =>
163            {
164                let (variant_index, variant_dest, active_field_index) = match **kind {
165                    mir::AggregateKind::Adt(_, variant_index, _, _, active_field_index) => {
166                        let variant_dest = dest.project_downcast(bx, variant_index);
167                        (variant_index, variant_dest, active_field_index)
168                    }
169                    _ => (FIRST_VARIANT, dest, None),
170                };
171                if active_field_index.is_some() {
172                    assert_eq!(operands.len(), 1);
173                }
174                for (i, operand) in operands.iter_enumerated() {
175                    let op = self.codegen_operand(bx, operand);
176                    // Do not generate stores and GEPis for zero-sized fields.
177                    if !op.layout.is_zst() {
178                        let field_index = active_field_index.unwrap_or(i);
179                        let field = if let mir::AggregateKind::Array(_) = **kind {
180                            let llindex = bx.cx().const_usize(field_index.as_u32().into());
181                            variant_dest.project_index(bx, llindex)
182                        } else {
183                            variant_dest.project_field(bx, field_index.as_usize())
184                        };
185                        op.val.store(bx, field);
186                    }
187                }
188                dest.codegen_set_discr(bx, variant_index);
189            }
190
191            _ => {
192                assert!(self.rvalue_creates_operand(rvalue, DUMMY_SP));
193                let temp = self.codegen_rvalue_operand(bx, rvalue);
194                temp.val.store(bx, dest);
195            }
196        }
197    }
198
199    fn codegen_transmute(
200        &mut self,
201        bx: &mut Bx,
202        src: OperandRef<'tcx, Bx::Value>,
203        dst: PlaceRef<'tcx, Bx::Value>,
204    ) {
205        // The MIR validator enforces no unsized transmutes.
206        assert!(src.layout.is_sized());
207        assert!(dst.layout.is_sized());
208
209        if let Some(val) = self.codegen_transmute_operand(bx, src, dst.layout) {
210            val.store(bx, dst);
211            return;
212        }
213
214        match src.val {
215            OperandValue::Ref(..) | OperandValue::ZeroSized => {
216                span_bug!(
217                    self.mir.span,
218                    "Operand path should have handled transmute \
219                    from {src:?} to place {dst:?}"
220                );
221            }
222            OperandValue::Immediate(..) | OperandValue::Pair(..) => {
223                // When we have immediate(s), the alignment of the source is irrelevant,
224                // so we can store them using the destination's alignment.
225                src.val.store(bx, dst.val.with_type(src.layout));
226            }
227        }
228    }
229
230    /// Attempts to transmute an `OperandValue` to another `OperandValue`.
231    ///
232    /// Returns `None` for cases that can't work in that framework, such as for
233    /// `Immediate`->`Ref` that needs an `alloc` to get the location.
234    fn codegen_transmute_operand(
235        &mut self,
236        bx: &mut Bx,
237        operand: OperandRef<'tcx, Bx::Value>,
238        cast: TyAndLayout<'tcx>,
239    ) -> Option<OperandValue<Bx::Value>> {
240        // Check for transmutes that are always UB.
241        if operand.layout.size != cast.size
242            || operand.layout.is_uninhabited()
243            || cast.is_uninhabited()
244        {
245            if !operand.layout.is_uninhabited() {
246                // Since this is known statically and the input could have existed
247                // without already having hit UB, might as well trap for it.
248                bx.abort();
249            }
250
251            // Because this transmute is UB, return something easy to generate,
252            // since it's fine that later uses of the value are probably UB.
253            return Some(OperandValue::poison(bx, cast));
254        }
255
256        let operand_kind = self.value_kind(operand.layout);
257        let cast_kind = self.value_kind(cast);
258
259        match operand.val {
260            OperandValue::Ref(source_place_val) => {
261                assert_eq!(source_place_val.llextra, None);
262                assert_matches!(operand_kind, OperandValueKind::Ref);
263                Some(bx.load_operand(source_place_val.with_type(cast)).val)
264            }
265            OperandValue::ZeroSized => {
266                let OperandValueKind::ZeroSized = operand_kind else {
267                    bug!("Found {operand_kind:?} for operand {operand:?}");
268                };
269                if let OperandValueKind::ZeroSized = cast_kind {
270                    Some(OperandValue::ZeroSized)
271                } else {
272                    None
273                }
274            }
275            OperandValue::Immediate(imm) => {
276                let OperandValueKind::Immediate(from_scalar) = operand_kind else {
277                    bug!("Found {operand_kind:?} for operand {operand:?}");
278                };
279                if let OperandValueKind::Immediate(to_scalar) = cast_kind
280                    && from_scalar.size(self.cx) == to_scalar.size(self.cx)
281                {
282                    let from_backend_ty = bx.backend_type(operand.layout);
283                    let to_backend_ty = bx.backend_type(cast);
284                    Some(OperandValue::Immediate(self.transmute_immediate(
285                        bx,
286                        imm,
287                        from_scalar,
288                        from_backend_ty,
289                        to_scalar,
290                        to_backend_ty,
291                    )))
292                } else {
293                    None
294                }
295            }
296            OperandValue::Pair(imm_a, imm_b) => {
297                let OperandValueKind::Pair(in_a, in_b) = operand_kind else {
298                    bug!("Found {operand_kind:?} for operand {operand:?}");
299                };
300                if let OperandValueKind::Pair(out_a, out_b) = cast_kind
301                    && in_a.size(self.cx) == out_a.size(self.cx)
302                    && in_b.size(self.cx) == out_b.size(self.cx)
303                {
304                    let in_a_ibty = bx.scalar_pair_element_backend_type(operand.layout, 0, false);
305                    let in_b_ibty = bx.scalar_pair_element_backend_type(operand.layout, 1, false);
306                    let out_a_ibty = bx.scalar_pair_element_backend_type(cast, 0, false);
307                    let out_b_ibty = bx.scalar_pair_element_backend_type(cast, 1, false);
308                    Some(OperandValue::Pair(
309                        self.transmute_immediate(bx, imm_a, in_a, in_a_ibty, out_a, out_a_ibty),
310                        self.transmute_immediate(bx, imm_b, in_b, in_b_ibty, out_b, out_b_ibty),
311                    ))
312                } else {
313                    None
314                }
315            }
316        }
317    }
318
319    /// Cast one of the immediates from an [`OperandValue::Immediate`]
320    /// or an [`OperandValue::Pair`] to an immediate of the target type.
321    ///
322    /// Returns `None` if the cast is not possible.
323    fn cast_immediate(
324        &self,
325        bx: &mut Bx,
326        mut imm: Bx::Value,
327        from_scalar: abi::Scalar,
328        from_backend_ty: Bx::Type,
329        to_scalar: abi::Scalar,
330        to_backend_ty: Bx::Type,
331    ) -> Option<Bx::Value> {
332        use abi::Primitive::*;
333
334        // When scalars are passed by value, there's no metadata recording their
335        // valid ranges. For example, `char`s are passed as just `i32`, with no
336        // way for LLVM to know that they're 0x10FFFF at most. Thus we assume
337        // the range of the input value too, not just the output range.
338        self.assume_scalar_range(bx, imm, from_scalar, from_backend_ty);
339
340        imm = match (from_scalar.primitive(), to_scalar.primitive()) {
341            (Int(_, is_signed), Int(..)) => bx.intcast(imm, to_backend_ty, is_signed),
342            (Float(_), Float(_)) => {
343                let srcsz = bx.cx().float_width(from_backend_ty);
344                let dstsz = bx.cx().float_width(to_backend_ty);
345                if dstsz > srcsz {
346                    bx.fpext(imm, to_backend_ty)
347                } else if srcsz > dstsz {
348                    bx.fptrunc(imm, to_backend_ty)
349                } else {
350                    imm
351                }
352            }
353            (Int(_, is_signed), Float(_)) => {
354                if is_signed {
355                    bx.sitofp(imm, to_backend_ty)
356                } else {
357                    bx.uitofp(imm, to_backend_ty)
358                }
359            }
360            (Pointer(..), Pointer(..)) => bx.pointercast(imm, to_backend_ty),
361            (Int(_, is_signed), Pointer(..)) => {
362                let usize_imm = bx.intcast(imm, bx.cx().type_isize(), is_signed);
363                bx.inttoptr(usize_imm, to_backend_ty)
364            }
365            (Float(_), Int(_, is_signed)) => bx.cast_float_to_int(is_signed, imm, to_backend_ty),
366            _ => return None,
367        };
368        Some(imm)
369    }
370
371    /// Transmutes one of the immediates from an [`OperandValue::Immediate`]
372    /// or an [`OperandValue::Pair`] to an immediate of the target type.
373    ///
374    /// `to_backend_ty` must be the *non*-immediate backend type (so it will be
375    /// `i8`, not `i1`, for `bool`-like types.)
376    fn transmute_immediate(
377        &self,
378        bx: &mut Bx,
379        mut imm: Bx::Value,
380        from_scalar: abi::Scalar,
381        from_backend_ty: Bx::Type,
382        to_scalar: abi::Scalar,
383        to_backend_ty: Bx::Type,
384    ) -> Bx::Value {
385        assert_eq!(from_scalar.size(self.cx), to_scalar.size(self.cx));
386
387        use abi::Primitive::*;
388        imm = bx.from_immediate(imm);
389
390        // If we have a scalar, we must already know its range. Either
391        //
392        // 1) It's a parameter with `range` parameter metadata,
393        // 2) It's something we `load`ed with `!range` metadata, or
394        // 3) After a transmute we `assume`d the range (see below).
395        //
396        // That said, last time we tried removing this, it didn't actually help
397        // the rustc-perf results, so might as well keep doing it
398        // <https://github.com/rust-lang/rust/pull/135610#issuecomment-2599275182>
399        self.assume_scalar_range(bx, imm, from_scalar, from_backend_ty);
400
401        imm = match (from_scalar.primitive(), to_scalar.primitive()) {
402            (Int(..) | Float(_), Int(..) | Float(_)) => bx.bitcast(imm, to_backend_ty),
403            (Pointer(..), Pointer(..)) => bx.pointercast(imm, to_backend_ty),
404            (Int(..), Pointer(..)) => bx.ptradd(bx.const_null(bx.type_ptr()), imm),
405            (Pointer(..), Int(..)) => {
406                // FIXME: this exposes the provenance, which shouldn't be necessary.
407                bx.ptrtoint(imm, to_backend_ty)
408            }
409            (Float(_), Pointer(..)) => {
410                let int_imm = bx.bitcast(imm, bx.cx().type_isize());
411                bx.ptradd(bx.const_null(bx.type_ptr()), int_imm)
412            }
413            (Pointer(..), Float(_)) => {
414                // FIXME: this exposes the provenance, which shouldn't be necessary.
415                let int_imm = bx.ptrtoint(imm, bx.cx().type_isize());
416                bx.bitcast(int_imm, to_backend_ty)
417            }
418        };
419
420        // This `assume` remains important for cases like (a conceptual)
421        //    transmute::<u32, NonZeroU32>(x) == 0
422        // since it's never passed to something with parameter metadata (especially
423        // after MIR inlining) so the only way to tell the backend about the
424        // constraint that the `transmute` introduced is to `assume` it.
425        self.assume_scalar_range(bx, imm, to_scalar, to_backend_ty);
426
427        imm = bx.to_immediate_scalar(imm, to_scalar);
428        imm
429    }
430
431    fn assume_scalar_range(
432        &self,
433        bx: &mut Bx,
434        imm: Bx::Value,
435        scalar: abi::Scalar,
436        backend_ty: Bx::Type,
437    ) {
438        if matches!(self.cx.sess().opts.optimize, OptLevel::No) || scalar.is_always_valid(self.cx) {
439            return;
440        }
441
442        match scalar.primitive() {
443            abi::Primitive::Int(..) => {
444                let range = scalar.valid_range(self.cx);
445                bx.assume_integer_range(imm, backend_ty, range);
446            }
447            abi::Primitive::Pointer(abi::AddressSpace::DATA)
448                if !scalar.valid_range(self.cx).contains(0) =>
449            {
450                bx.assume_nonnull(imm);
451            }
452            abi::Primitive::Pointer(..) | abi::Primitive::Float(..) => {}
453        }
454    }
455
456    pub(crate) fn codegen_rvalue_unsized(
457        &mut self,
458        bx: &mut Bx,
459        indirect_dest: PlaceRef<'tcx, Bx::Value>,
460        rvalue: &mir::Rvalue<'tcx>,
461    ) {
462        debug!(
463            "codegen_rvalue_unsized(indirect_dest.llval={:?}, rvalue={:?})",
464            indirect_dest.val.llval, rvalue
465        );
466
467        match *rvalue {
468            mir::Rvalue::Use(ref operand) => {
469                let cg_operand = self.codegen_operand(bx, operand);
470                cg_operand.val.store_unsized(bx, indirect_dest);
471            }
472
473            _ => bug!("unsized assignment other than `Rvalue::Use`"),
474        }
475    }
476
477    pub(crate) fn codegen_rvalue_operand(
478        &mut self,
479        bx: &mut Bx,
480        rvalue: &mir::Rvalue<'tcx>,
481    ) -> OperandRef<'tcx, Bx::Value> {
482        assert!(
483            self.rvalue_creates_operand(rvalue, DUMMY_SP),
484            "cannot codegen {rvalue:?} to operand",
485        );
486
487        match *rvalue {
488            mir::Rvalue::Cast(ref kind, ref source, mir_cast_ty) => {
489                let operand = self.codegen_operand(bx, source);
490                debug!("cast operand is {:?}", operand);
491                let cast = bx.cx().layout_of(self.monomorphize(mir_cast_ty));
492
493                let val = match *kind {
494                    mir::CastKind::PointerExposeProvenance => {
495                        assert!(bx.cx().is_backend_immediate(cast));
496                        let llptr = operand.immediate();
497                        let llcast_ty = bx.cx().immediate_backend_type(cast);
498                        let lladdr = bx.ptrtoint(llptr, llcast_ty);
499                        OperandValue::Immediate(lladdr)
500                    }
501                    mir::CastKind::PointerCoercion(PointerCoercion::ReifyFnPointer, _) => {
502                        match *operand.layout.ty.kind() {
503                            ty::FnDef(def_id, args) => {
504                                let instance = ty::Instance::resolve_for_fn_ptr(
505                                    bx.tcx(),
506                                    bx.typing_env(),
507                                    def_id,
508                                    args,
509                                )
510                                .unwrap();
511                                OperandValue::Immediate(bx.get_fn_addr(instance))
512                            }
513                            _ => bug!("{} cannot be reified to a fn ptr", operand.layout.ty),
514                        }
515                    }
516                    mir::CastKind::PointerCoercion(PointerCoercion::ClosureFnPointer(_), _) => {
517                        match *operand.layout.ty.kind() {
518                            ty::Closure(def_id, args) => {
519                                let instance = Instance::resolve_closure(
520                                    bx.cx().tcx(),
521                                    def_id,
522                                    args,
523                                    ty::ClosureKind::FnOnce,
524                                );
525                                OperandValue::Immediate(bx.cx().get_fn_addr(instance))
526                            }
527                            _ => bug!("{} cannot be cast to a fn ptr", operand.layout.ty),
528                        }
529                    }
530                    mir::CastKind::PointerCoercion(PointerCoercion::UnsafeFnPointer, _) => {
531                        // This is a no-op at the LLVM level.
532                        operand.val
533                    }
534                    mir::CastKind::PointerCoercion(PointerCoercion::Unsize, _) => {
535                        assert!(bx.cx().is_backend_scalar_pair(cast));
536                        let (lldata, llextra) = operand.val.pointer_parts();
537                        let (lldata, llextra) =
538                            base::unsize_ptr(bx, lldata, operand.layout.ty, cast.ty, llextra);
539                        OperandValue::Pair(lldata, llextra)
540                    }
541                    mir::CastKind::PointerCoercion(
542                        PointerCoercion::MutToConstPointer | PointerCoercion::ArrayToPointer, _
543                    ) => {
544                        bug!("{kind:?} is for borrowck, and should never appear in codegen");
545                    }
546                    mir::CastKind::PtrToPtr
547                        if bx.cx().is_backend_scalar_pair(operand.layout) =>
548                    {
549                        if let OperandValue::Pair(data_ptr, meta) = operand.val {
550                            if bx.cx().is_backend_scalar_pair(cast) {
551                                OperandValue::Pair(data_ptr, meta)
552                            } else {
553                                // Cast of wide-ptr to thin-ptr is an extraction of data-ptr.
554                                OperandValue::Immediate(data_ptr)
555                            }
556                        } else {
557                            bug!("unexpected non-pair operand");
558                        }
559                    }
560                    mir::CastKind::PointerCoercion(PointerCoercion::DynStar, _) => {
561                        let (lldata, llextra) = operand.val.pointer_parts();
562                        let (lldata, llextra) =
563                            base::cast_to_dyn_star(bx, lldata, operand.layout, cast.ty, llextra);
564                        OperandValue::Pair(lldata, llextra)
565                    }
566                    | mir::CastKind::IntToInt
567                    | mir::CastKind::FloatToInt
568                    | mir::CastKind::FloatToFloat
569                    | mir::CastKind::IntToFloat
570                    | mir::CastKind::PtrToPtr
571                    | mir::CastKind::FnPtrToPtr
572                    // Since int2ptr can have arbitrary integer types as input (so we have to do
573                    // sign extension and all that), it is currently best handled in the same code
574                    // path as the other integer-to-X casts.
575                    | mir::CastKind::PointerWithExposedProvenance => {
576                        let imm = operand.immediate();
577                        let operand_kind = self.value_kind(operand.layout);
578                        let OperandValueKind::Immediate(from_scalar) = operand_kind else {
579                            bug!("Found {operand_kind:?} for operand {operand:?}");
580                        };
581                        let from_backend_ty = bx.cx().immediate_backend_type(operand.layout);
582
583                        assert!(bx.cx().is_backend_immediate(cast));
584                        let to_backend_ty = bx.cx().immediate_backend_type(cast);
585                        if operand.layout.is_uninhabited() {
586                            let val = OperandValue::Immediate(bx.cx().const_poison(to_backend_ty));
587                            return OperandRef { val, layout: cast };
588                        }
589                        let cast_kind = self.value_kind(cast);
590                        let OperandValueKind::Immediate(to_scalar) = cast_kind else {
591                            bug!("Found {cast_kind:?} for operand {cast:?}");
592                        };
593
594                        self.cast_immediate(bx, imm, from_scalar, from_backend_ty, to_scalar, to_backend_ty)
595                            .map(OperandValue::Immediate)
596                            .unwrap_or_else(|| {
597                                bug!("Unsupported cast of {operand:?} to {cast:?}");
598                            })
599                    }
600                    mir::CastKind::Transmute => {
601                        self.codegen_transmute_operand(bx, operand, cast).unwrap_or_else(|| {
602                            bug!("Unsupported transmute-as-operand of {operand:?} to {cast:?}");
603                        })
604                    }
605                };
606                OperandRef { val, layout: cast }
607            }
608
609            mir::Rvalue::Ref(_, bk, place) => {
610                let mk_ref = move |tcx: TyCtxt<'tcx>, ty: Ty<'tcx>| {
611                    Ty::new_ref(tcx, tcx.lifetimes.re_erased, ty, bk.to_mutbl_lossy())
612                };
613                self.codegen_place_to_pointer(bx, place, mk_ref)
614            }
615
616            mir::Rvalue::CopyForDeref(place) => {
617                self.codegen_operand(bx, &mir::Operand::Copy(place))
618            }
619            mir::Rvalue::RawPtr(kind, place) => {
620                let mk_ptr = move |tcx: TyCtxt<'tcx>, ty: Ty<'tcx>| {
621                    Ty::new_ptr(tcx, ty, kind.to_mutbl_lossy())
622                };
623                self.codegen_place_to_pointer(bx, place, mk_ptr)
624            }
625
626            mir::Rvalue::Len(place) => {
627                let size = self.evaluate_array_len(bx, place);
628                OperandRef {
629                    val: OperandValue::Immediate(size),
630                    layout: bx.cx().layout_of(bx.tcx().types.usize),
631                }
632            }
633
634            mir::Rvalue::BinaryOp(op_with_overflow, box (ref lhs, ref rhs))
635                if let Some(op) = op_with_overflow.overflowing_to_wrapping() =>
636            {
637                let lhs = self.codegen_operand(bx, lhs);
638                let rhs = self.codegen_operand(bx, rhs);
639                let result = self.codegen_scalar_checked_binop(
640                    bx,
641                    op,
642                    lhs.immediate(),
643                    rhs.immediate(),
644                    lhs.layout.ty,
645                );
646                let val_ty = op.ty(bx.tcx(), lhs.layout.ty, rhs.layout.ty);
647                let operand_ty = Ty::new_tup(bx.tcx(), &[val_ty, bx.tcx().types.bool]);
648                OperandRef { val: result, layout: bx.cx().layout_of(operand_ty) }
649            }
650            mir::Rvalue::BinaryOp(op, box (ref lhs, ref rhs)) => {
651                let lhs = self.codegen_operand(bx, lhs);
652                let rhs = self.codegen_operand(bx, rhs);
653                let llresult = match (lhs.val, rhs.val) {
654                    (
655                        OperandValue::Pair(lhs_addr, lhs_extra),
656                        OperandValue::Pair(rhs_addr, rhs_extra),
657                    ) => self.codegen_wide_ptr_binop(
658                        bx,
659                        op,
660                        lhs_addr,
661                        lhs_extra,
662                        rhs_addr,
663                        rhs_extra,
664                        lhs.layout.ty,
665                    ),
666
667                    (OperandValue::Immediate(lhs_val), OperandValue::Immediate(rhs_val)) => {
668                        self.codegen_scalar_binop(bx, op, lhs_val, rhs_val, lhs.layout.ty)
669                    }
670
671                    _ => bug!(),
672                };
673                OperandRef {
674                    val: OperandValue::Immediate(llresult),
675                    layout: bx.cx().layout_of(op.ty(bx.tcx(), lhs.layout.ty, rhs.layout.ty)),
676                }
677            }
678
679            mir::Rvalue::UnaryOp(op, ref operand) => {
680                let operand = self.codegen_operand(bx, operand);
681                let is_float = operand.layout.ty.is_floating_point();
682                let (val, layout) = match op {
683                    mir::UnOp::Not => {
684                        let llval = bx.not(operand.immediate());
685                        (OperandValue::Immediate(llval), operand.layout)
686                    }
687                    mir::UnOp::Neg => {
688                        let llval = if is_float {
689                            bx.fneg(operand.immediate())
690                        } else {
691                            bx.neg(operand.immediate())
692                        };
693                        (OperandValue::Immediate(llval), operand.layout)
694                    }
695                    mir::UnOp::PtrMetadata => {
696                        assert!(operand.layout.ty.is_raw_ptr() || operand.layout.ty.is_ref(),);
697                        let (_, meta) = operand.val.pointer_parts();
698                        assert_eq!(operand.layout.fields.count() > 1, meta.is_some());
699                        if let Some(meta) = meta {
700                            (OperandValue::Immediate(meta), operand.layout.field(self.cx, 1))
701                        } else {
702                            (OperandValue::ZeroSized, bx.cx().layout_of(bx.tcx().types.unit))
703                        }
704                    }
705                };
706                assert!(
707                    val.is_expected_variant_for_type(self.cx, layout),
708                    "Made wrong variant {val:?} for type {layout:?}",
709                );
710                OperandRef { val, layout }
711            }
712
713            mir::Rvalue::Discriminant(ref place) => {
714                let discr_ty = rvalue.ty(self.mir, bx.tcx());
715                let discr_ty = self.monomorphize(discr_ty);
716                let discr = self.codegen_place(bx, place.as_ref()).codegen_get_discr(bx, discr_ty);
717                OperandRef {
718                    val: OperandValue::Immediate(discr),
719                    layout: self.cx.layout_of(discr_ty),
720                }
721            }
722
723            mir::Rvalue::NullaryOp(ref null_op, ty) => {
724                let ty = self.monomorphize(ty);
725                let layout = bx.cx().layout_of(ty);
726                let val = match null_op {
727                    mir::NullOp::SizeOf => {
728                        assert!(bx.cx().type_is_sized(ty));
729                        let val = layout.size.bytes();
730                        bx.cx().const_usize(val)
731                    }
732                    mir::NullOp::AlignOf => {
733                        assert!(bx.cx().type_is_sized(ty));
734                        let val = layout.align.abi.bytes();
735                        bx.cx().const_usize(val)
736                    }
737                    mir::NullOp::OffsetOf(fields) => {
738                        let val = bx
739                            .tcx()
740                            .offset_of_subfield(bx.typing_env(), layout, fields.iter())
741                            .bytes();
742                        bx.cx().const_usize(val)
743                    }
744                    mir::NullOp::UbChecks => {
745                        let val = bx.tcx().sess.ub_checks();
746                        bx.cx().const_bool(val)
747                    }
748                    mir::NullOp::ContractChecks => {
749                        let val = bx.tcx().sess.contract_checks();
750                        bx.cx().const_bool(val)
751                    }
752                };
753                let tcx = self.cx.tcx();
754                OperandRef {
755                    val: OperandValue::Immediate(val),
756                    layout: self.cx.layout_of(tcx.types.usize),
757                }
758            }
759
760            mir::Rvalue::ThreadLocalRef(def_id) => {
761                assert!(bx.cx().tcx().is_static(def_id));
762                let layout = bx.layout_of(bx.cx().tcx().static_ptr_ty(def_id, bx.typing_env()));
763                let static_ = if !def_id.is_local() && bx.cx().tcx().needs_thread_local_shim(def_id)
764                {
765                    let instance = ty::Instance {
766                        def: ty::InstanceKind::ThreadLocalShim(def_id),
767                        args: ty::GenericArgs::empty(),
768                    };
769                    let fn_ptr = bx.get_fn_addr(instance);
770                    let fn_abi = bx.fn_abi_of_instance(instance, ty::List::empty());
771                    let fn_ty = bx.fn_decl_backend_type(fn_abi);
772                    let fn_attrs = if bx.tcx().def_kind(instance.def_id()).has_codegen_attrs() {
773                        Some(bx.tcx().codegen_fn_attrs(instance.def_id()))
774                    } else {
775                        None
776                    };
777                    bx.call(fn_ty, fn_attrs, Some(fn_abi), fn_ptr, &[], None, Some(instance))
778                } else {
779                    bx.get_static(def_id)
780                };
781                OperandRef { val: OperandValue::Immediate(static_), layout }
782            }
783            mir::Rvalue::Use(ref operand) => self.codegen_operand(bx, operand),
784            mir::Rvalue::Repeat(..) => bug!("{rvalue:?} in codegen_rvalue_operand"),
785            mir::Rvalue::Aggregate(_, ref fields) => {
786                let ty = rvalue.ty(self.mir, self.cx.tcx());
787                let ty = self.monomorphize(ty);
788                let layout = self.cx.layout_of(ty);
789
790                // `rvalue_creates_operand` has arranged that we only get here if
791                // we can build the aggregate immediate from the field immediates.
792                let mut inputs = ArrayVec::<Bx::Value, 2>::new();
793                let mut input_scalars = ArrayVec::<abi::Scalar, 2>::new();
794                for field_idx in layout.fields.index_by_increasing_offset() {
795                    let field_idx = FieldIdx::from_usize(field_idx);
796                    let op = self.codegen_operand(bx, &fields[field_idx]);
797                    let values = op.val.immediates_or_place().left_or_else(|p| {
798                        bug!("Field {field_idx:?} is {p:?} making {layout:?}");
799                    });
800                    let scalars = self.value_kind(op.layout).scalars().unwrap();
801                    assert_eq!(values.len(), scalars.len());
802                    inputs.extend(values);
803                    input_scalars.extend(scalars);
804                }
805
806                let output_scalars = self.value_kind(layout).scalars().unwrap();
807                itertools::izip!(&mut inputs, input_scalars, output_scalars).for_each(
808                    |(v, in_s, out_s)| {
809                        if in_s != out_s {
810                            // We have to be really careful about bool here, because
811                            // `(bool,)` stays i1 but `Cell<bool>` becomes i8.
812                            *v = bx.from_immediate(*v);
813                            *v = bx.to_immediate_scalar(*v, out_s);
814                        }
815                    },
816                );
817
818                let val = OperandValue::from_immediates(inputs);
819                assert!(
820                    val.is_expected_variant_for_type(self.cx, layout),
821                    "Made wrong variant {val:?} for type {layout:?}",
822                );
823                OperandRef { val, layout }
824            }
825            mir::Rvalue::ShallowInitBox(ref operand, content_ty) => {
826                let operand = self.codegen_operand(bx, operand);
827                let val = operand.immediate();
828
829                let content_ty = self.monomorphize(content_ty);
830                let box_layout = bx.cx().layout_of(Ty::new_box(bx.tcx(), content_ty));
831
832                OperandRef { val: OperandValue::Immediate(val), layout: box_layout }
833            }
834            mir::Rvalue::WrapUnsafeBinder(ref operand, binder_ty) => {
835                let operand = self.codegen_operand(bx, operand);
836                let binder_ty = self.monomorphize(binder_ty);
837                let layout = bx.cx().layout_of(binder_ty);
838                OperandRef { val: operand.val, layout }
839            }
840        }
841    }
842
843    fn evaluate_array_len(&mut self, bx: &mut Bx, place: mir::Place<'tcx>) -> Bx::Value {
844        // ZST are passed as operands and require special handling
845        // because codegen_place() panics if Local is operand.
846        if let Some(index) = place.as_local() {
847            if let LocalRef::Operand(op) = self.locals[index] {
848                if let ty::Array(_, n) = op.layout.ty.kind() {
849                    let n = n
850                        .try_to_target_usize(bx.tcx())
851                        .expect("expected monomorphic const in codegen");
852                    return bx.cx().const_usize(n);
853                }
854            }
855        }
856        // use common size calculation for non zero-sized types
857        let cg_value = self.codegen_place(bx, place.as_ref());
858        cg_value.len(bx.cx())
859    }
860
861    /// Codegen an `Rvalue::RawPtr` or `Rvalue::Ref`
862    fn codegen_place_to_pointer(
863        &mut self,
864        bx: &mut Bx,
865        place: mir::Place<'tcx>,
866        mk_ptr_ty: impl FnOnce(TyCtxt<'tcx>, Ty<'tcx>) -> Ty<'tcx>,
867    ) -> OperandRef<'tcx, Bx::Value> {
868        let cg_place = self.codegen_place(bx, place.as_ref());
869        let val = cg_place.val.address();
870
871        let ty = cg_place.layout.ty;
872        assert!(
873            if bx.cx().type_has_metadata(ty) {
874                matches!(val, OperandValue::Pair(..))
875            } else {
876                matches!(val, OperandValue::Immediate(..))
877            },
878            "Address of place was unexpectedly {val:?} for pointee type {ty:?}",
879        );
880
881        OperandRef { val, layout: self.cx.layout_of(mk_ptr_ty(self.cx.tcx(), ty)) }
882    }
883
884    fn codegen_scalar_binop(
885        &mut self,
886        bx: &mut Bx,
887        op: mir::BinOp,
888        lhs: Bx::Value,
889        rhs: Bx::Value,
890        input_ty: Ty<'tcx>,
891    ) -> Bx::Value {
892        let is_float = input_ty.is_floating_point();
893        let is_signed = input_ty.is_signed();
894        match op {
895            mir::BinOp::Add => {
896                if is_float {
897                    bx.fadd(lhs, rhs)
898                } else {
899                    bx.add(lhs, rhs)
900                }
901            }
902            mir::BinOp::AddUnchecked => {
903                if is_signed {
904                    bx.unchecked_sadd(lhs, rhs)
905                } else {
906                    bx.unchecked_uadd(lhs, rhs)
907                }
908            }
909            mir::BinOp::Sub => {
910                if is_float {
911                    bx.fsub(lhs, rhs)
912                } else {
913                    bx.sub(lhs, rhs)
914                }
915            }
916            mir::BinOp::SubUnchecked => {
917                if is_signed {
918                    bx.unchecked_ssub(lhs, rhs)
919                } else {
920                    bx.unchecked_usub(lhs, rhs)
921                }
922            }
923            mir::BinOp::Mul => {
924                if is_float {
925                    bx.fmul(lhs, rhs)
926                } else {
927                    bx.mul(lhs, rhs)
928                }
929            }
930            mir::BinOp::MulUnchecked => {
931                if is_signed {
932                    bx.unchecked_smul(lhs, rhs)
933                } else {
934                    bx.unchecked_umul(lhs, rhs)
935                }
936            }
937            mir::BinOp::Div => {
938                if is_float {
939                    bx.fdiv(lhs, rhs)
940                } else if is_signed {
941                    bx.sdiv(lhs, rhs)
942                } else {
943                    bx.udiv(lhs, rhs)
944                }
945            }
946            mir::BinOp::Rem => {
947                if is_float {
948                    bx.frem(lhs, rhs)
949                } else if is_signed {
950                    bx.srem(lhs, rhs)
951                } else {
952                    bx.urem(lhs, rhs)
953                }
954            }
955            mir::BinOp::BitOr => bx.or(lhs, rhs),
956            mir::BinOp::BitAnd => bx.and(lhs, rhs),
957            mir::BinOp::BitXor => bx.xor(lhs, rhs),
958            mir::BinOp::Offset => {
959                let pointee_type = input_ty
960                    .builtin_deref(true)
961                    .unwrap_or_else(|| bug!("deref of non-pointer {:?}", input_ty));
962                let pointee_layout = bx.cx().layout_of(pointee_type);
963                if pointee_layout.is_zst() {
964                    // `Offset` works in terms of the size of pointee,
965                    // so offsetting a pointer to ZST is a noop.
966                    lhs
967                } else {
968                    let llty = bx.cx().backend_type(pointee_layout);
969                    bx.inbounds_gep(llty, lhs, &[rhs])
970                }
971            }
972            mir::BinOp::Shl | mir::BinOp::ShlUnchecked => {
973                let rhs = base::build_shift_expr_rhs(bx, lhs, rhs, op == mir::BinOp::ShlUnchecked);
974                bx.shl(lhs, rhs)
975            }
976            mir::BinOp::Shr | mir::BinOp::ShrUnchecked => {
977                let rhs = base::build_shift_expr_rhs(bx, lhs, rhs, op == mir::BinOp::ShrUnchecked);
978                if is_signed { bx.ashr(lhs, rhs) } else { bx.lshr(lhs, rhs) }
979            }
980            mir::BinOp::Ne
981            | mir::BinOp::Lt
982            | mir::BinOp::Gt
983            | mir::BinOp::Eq
984            | mir::BinOp::Le
985            | mir::BinOp::Ge => {
986                if is_float {
987                    bx.fcmp(base::bin_op_to_fcmp_predicate(op), lhs, rhs)
988                } else {
989                    bx.icmp(base::bin_op_to_icmp_predicate(op, is_signed), lhs, rhs)
990                }
991            }
992            mir::BinOp::Cmp => {
993                use std::cmp::Ordering;
994                assert!(!is_float);
995                let pred = |op| base::bin_op_to_icmp_predicate(op, is_signed);
996                if bx.cx().tcx().sess.opts.optimize == OptLevel::No {
997                    // FIXME: This actually generates tighter assembly, and is a classic trick
998                    // <https://graphics.stanford.edu/~seander/bithacks.html#CopyIntegerSign>
999                    // However, as of 2023-11 it optimizes worse in things like derived
1000                    // `PartialOrd`, so only use it in debug for now. Once LLVM can handle it
1001                    // better (see <https://github.com/llvm/llvm-project/issues/73417>), it'll
1002                    // be worth trying it in optimized builds as well.
1003                    let is_gt = bx.icmp(pred(mir::BinOp::Gt), lhs, rhs);
1004                    let gtext = bx.zext(is_gt, bx.type_i8());
1005                    let is_lt = bx.icmp(pred(mir::BinOp::Lt), lhs, rhs);
1006                    let ltext = bx.zext(is_lt, bx.type_i8());
1007                    bx.unchecked_ssub(gtext, ltext)
1008                } else {
1009                    // These operations are those expected by `tests/codegen/integer-cmp.rs`,
1010                    // from <https://github.com/rust-lang/rust/pull/63767>.
1011                    let is_lt = bx.icmp(pred(mir::BinOp::Lt), lhs, rhs);
1012                    let is_ne = bx.icmp(pred(mir::BinOp::Ne), lhs, rhs);
1013                    let ge = bx.select(
1014                        is_ne,
1015                        bx.cx().const_i8(Ordering::Greater as i8),
1016                        bx.cx().const_i8(Ordering::Equal as i8),
1017                    );
1018                    bx.select(is_lt, bx.cx().const_i8(Ordering::Less as i8), ge)
1019                }
1020            }
1021            mir::BinOp::AddWithOverflow
1022            | mir::BinOp::SubWithOverflow
1023            | mir::BinOp::MulWithOverflow => {
1024                bug!("{op:?} needs to return a pair, so call codegen_scalar_checked_binop instead")
1025            }
1026        }
1027    }
1028
1029    fn codegen_wide_ptr_binop(
1030        &mut self,
1031        bx: &mut Bx,
1032        op: mir::BinOp,
1033        lhs_addr: Bx::Value,
1034        lhs_extra: Bx::Value,
1035        rhs_addr: Bx::Value,
1036        rhs_extra: Bx::Value,
1037        _input_ty: Ty<'tcx>,
1038    ) -> Bx::Value {
1039        match op {
1040            mir::BinOp::Eq => {
1041                let lhs = bx.icmp(IntPredicate::IntEQ, lhs_addr, rhs_addr);
1042                let rhs = bx.icmp(IntPredicate::IntEQ, lhs_extra, rhs_extra);
1043                bx.and(lhs, rhs)
1044            }
1045            mir::BinOp::Ne => {
1046                let lhs = bx.icmp(IntPredicate::IntNE, lhs_addr, rhs_addr);
1047                let rhs = bx.icmp(IntPredicate::IntNE, lhs_extra, rhs_extra);
1048                bx.or(lhs, rhs)
1049            }
1050            mir::BinOp::Le | mir::BinOp::Lt | mir::BinOp::Ge | mir::BinOp::Gt => {
1051                // a OP b ~ a.0 STRICT(OP) b.0 | (a.0 == b.0 && a.1 OP a.1)
1052                let (op, strict_op) = match op {
1053                    mir::BinOp::Lt => (IntPredicate::IntULT, IntPredicate::IntULT),
1054                    mir::BinOp::Le => (IntPredicate::IntULE, IntPredicate::IntULT),
1055                    mir::BinOp::Gt => (IntPredicate::IntUGT, IntPredicate::IntUGT),
1056                    mir::BinOp::Ge => (IntPredicate::IntUGE, IntPredicate::IntUGT),
1057                    _ => bug!(),
1058                };
1059                let lhs = bx.icmp(strict_op, lhs_addr, rhs_addr);
1060                let and_lhs = bx.icmp(IntPredicate::IntEQ, lhs_addr, rhs_addr);
1061                let and_rhs = bx.icmp(op, lhs_extra, rhs_extra);
1062                let rhs = bx.and(and_lhs, and_rhs);
1063                bx.or(lhs, rhs)
1064            }
1065            _ => {
1066                bug!("unexpected wide ptr binop");
1067            }
1068        }
1069    }
1070
1071    fn codegen_scalar_checked_binop(
1072        &mut self,
1073        bx: &mut Bx,
1074        op: mir::BinOp,
1075        lhs: Bx::Value,
1076        rhs: Bx::Value,
1077        input_ty: Ty<'tcx>,
1078    ) -> OperandValue<Bx::Value> {
1079        let (val, of) = match op {
1080            // These are checked using intrinsics
1081            mir::BinOp::Add | mir::BinOp::Sub | mir::BinOp::Mul => {
1082                let oop = match op {
1083                    mir::BinOp::Add => OverflowOp::Add,
1084                    mir::BinOp::Sub => OverflowOp::Sub,
1085                    mir::BinOp::Mul => OverflowOp::Mul,
1086                    _ => unreachable!(),
1087                };
1088                bx.checked_binop(oop, input_ty, lhs, rhs)
1089            }
1090            _ => bug!("Operator `{:?}` is not a checkable operator", op),
1091        };
1092
1093        OperandValue::Pair(val, of)
1094    }
1095
1096    pub(crate) fn rvalue_creates_operand(&self, rvalue: &mir::Rvalue<'tcx>, span: Span) -> bool {
1097        match *rvalue {
1098            mir::Rvalue::Cast(mir::CastKind::Transmute, ref operand, cast_ty) => {
1099                let operand_ty = operand.ty(self.mir, self.cx.tcx());
1100                let cast_layout = self.cx.layout_of(self.monomorphize(cast_ty));
1101                let operand_layout = self.cx.layout_of(self.monomorphize(operand_ty));
1102
1103                match (self.value_kind(operand_layout), self.value_kind(cast_layout)) {
1104                    // Can always load from a pointer as needed
1105                    (OperandValueKind::Ref, _) => true,
1106
1107                    // ZST-to-ZST is the easiest thing ever
1108                    (OperandValueKind::ZeroSized, OperandValueKind::ZeroSized) => true,
1109
1110                    // But if only one of them is a ZST the sizes can't match
1111                    (OperandValueKind::ZeroSized, _) | (_, OperandValueKind::ZeroSized) => false,
1112
1113                    // Need to generate an `alloc` to get a pointer from an immediate
1114                    (OperandValueKind::Immediate(..) | OperandValueKind::Pair(..), OperandValueKind::Ref) => false,
1115
1116                    // When we have scalar immediates, we can only convert things
1117                    // where the sizes match, to avoid endianness questions.
1118                    (OperandValueKind::Immediate(a), OperandValueKind::Immediate(b)) =>
1119                        a.size(self.cx) == b.size(self.cx),
1120                    (OperandValueKind::Pair(a0, a1), OperandValueKind::Pair(b0, b1)) =>
1121                        a0.size(self.cx) == b0.size(self.cx) && a1.size(self.cx) == b1.size(self.cx),
1122
1123                    // Send mixings between scalars and pairs through the memory route
1124                    // FIXME: Maybe this could use insertvalue/extractvalue instead?
1125                    (OperandValueKind::Immediate(..), OperandValueKind::Pair(..)) |
1126                    (OperandValueKind::Pair(..), OperandValueKind::Immediate(..)) => false,
1127                }
1128            }
1129            mir::Rvalue::Ref(..) |
1130            mir::Rvalue::CopyForDeref(..) |
1131            mir::Rvalue::RawPtr(..) |
1132            mir::Rvalue::Len(..) |
1133            mir::Rvalue::Cast(..) | // (*)
1134            mir::Rvalue::ShallowInitBox(..) | // (*)
1135            mir::Rvalue::BinaryOp(..) |
1136            mir::Rvalue::UnaryOp(..) |
1137            mir::Rvalue::Discriminant(..) |
1138            mir::Rvalue::NullaryOp(..) |
1139            mir::Rvalue::ThreadLocalRef(_) |
1140            mir::Rvalue::Use(..) |
1141            mir::Rvalue::WrapUnsafeBinder(..) => // (*)
1142                true,
1143            // Arrays are always aggregates, so it's not worth checking anything here.
1144            // (If it's really `[(); N]` or `[T; 0]` and we use the place path, fine.)
1145            mir::Rvalue::Repeat(..) => false,
1146            mir::Rvalue::Aggregate(ref kind, _) => {
1147                let allowed_kind = match **kind {
1148                    // This always produces a `ty::RawPtr`, so will be Immediate or Pair
1149                    mir::AggregateKind::RawPtr(..) => true,
1150                    mir::AggregateKind::Array(..) => false,
1151                    mir::AggregateKind::Tuple => true,
1152                    mir::AggregateKind::Adt(def_id, ..) => {
1153                        let adt_def = self.cx.tcx().adt_def(def_id);
1154                        adt_def.is_struct() && !adt_def.repr().simd()
1155                    }
1156                    mir::AggregateKind::Closure(..) => true,
1157                    // FIXME: Can we do this for simple coroutines too?
1158                    mir::AggregateKind::Coroutine(..) | mir::AggregateKind::CoroutineClosure(..) => false,
1159                };
1160                allowed_kind && {
1161                let ty = rvalue.ty(self.mir, self.cx.tcx());
1162                let ty = self.monomorphize(ty);
1163                    let layout = self.cx.spanned_layout_of(ty, span);
1164                    !self.cx.is_backend_ref(layout)
1165                }
1166            }
1167        }
1168
1169        // (*) this is only true if the type is suitable
1170    }
1171
1172    /// Gets which variant of [`OperandValue`] is expected for a particular type.
1173    fn value_kind(&self, layout: TyAndLayout<'tcx>) -> OperandValueKind {
1174        if layout.is_zst() {
1175            OperandValueKind::ZeroSized
1176        } else if self.cx.is_backend_immediate(layout) {
1177            assert!(!self.cx.is_backend_scalar_pair(layout));
1178            OperandValueKind::Immediate(match layout.backend_repr {
1179                abi::BackendRepr::Scalar(s) => s,
1180                abi::BackendRepr::Vector { element, .. } => element,
1181                x => span_bug!(self.mir.span, "Couldn't translate {x:?} as backend immediate"),
1182            })
1183        } else if self.cx.is_backend_scalar_pair(layout) {
1184            let abi::BackendRepr::ScalarPair(s1, s2) = layout.backend_repr else {
1185                span_bug!(
1186                    self.mir.span,
1187                    "Couldn't translate {:?} as backend scalar pair",
1188                    layout.backend_repr,
1189                );
1190            };
1191            OperandValueKind::Pair(s1, s2)
1192        } else {
1193            OperandValueKind::Ref
1194        }
1195    }
1196}
1197
1198/// The variants of this match [`OperandValue`], giving details about the
1199/// backend values that will be held in that other type.
1200#[derive(Debug, Copy, Clone)]
1201enum OperandValueKind {
1202    Ref,
1203    Immediate(abi::Scalar),
1204    Pair(abi::Scalar, abi::Scalar),
1205    ZeroSized,
1206}
1207
1208impl OperandValueKind {
1209    fn scalars(self) -> Option<ArrayVec<abi::Scalar, 2>> {
1210        Some(match self {
1211            OperandValueKind::ZeroSized => ArrayVec::new(),
1212            OperandValueKind::Immediate(a) => ArrayVec::from_iter([a]),
1213            OperandValueKind::Pair(a, b) => [a, b].into(),
1214            OperandValueKind::Ref => return None,
1215        })
1216    }
1217}