rustc_codegen_ssa/mir/
operand.rs

1use std::assert_matches::assert_matches;
2use std::fmt;
3
4use arrayvec::ArrayVec;
5use either::Either;
6use rustc_abi as abi;
7use rustc_abi::{Align, BackendRepr, Size};
8use rustc_middle::bug;
9use rustc_middle::mir::interpret::{Pointer, Scalar, alloc_range};
10use rustc_middle::mir::{self, ConstValue};
11use rustc_middle::ty::Ty;
12use rustc_middle::ty::layout::{LayoutOf, TyAndLayout};
13use tracing::debug;
14
15use super::place::{PlaceRef, PlaceValue};
16use super::{FunctionCx, LocalRef};
17use crate::traits::*;
18use crate::{MemFlags, size_of_val};
19
20/// The representation of a Rust value. The enum variant is in fact
21/// uniquely determined by the value's type, but is kept as a
22/// safety check.
23#[derive(Copy, Clone, Debug)]
24pub enum OperandValue<V> {
25    /// A reference to the actual operand. The data is guaranteed
26    /// to be valid for the operand's lifetime.
27    /// The second value, if any, is the extra data (vtable or length)
28    /// which indicates that it refers to an unsized rvalue.
29    ///
30    /// An `OperandValue` *must* be this variant for any type for which
31    /// [`LayoutTypeCodegenMethods::is_backend_ref`] returns `true`.
32    /// (That basically amounts to "isn't one of the other variants".)
33    ///
34    /// This holds a [`PlaceValue`] (like a [`PlaceRef`] does) with a pointer
35    /// to the location holding the value. The type behind that pointer is the
36    /// one returned by [`LayoutTypeCodegenMethods::backend_type`].
37    Ref(PlaceValue<V>),
38    /// A single LLVM immediate value.
39    ///
40    /// An `OperandValue` *must* be this variant for any type for which
41    /// [`LayoutTypeCodegenMethods::is_backend_immediate`] returns `true`.
42    /// The backend value in this variant must be the *immediate* backend type,
43    /// as returned by [`LayoutTypeCodegenMethods::immediate_backend_type`].
44    Immediate(V),
45    /// A pair of immediate LLVM values. Used by wide pointers too.
46    ///
47    /// An `OperandValue` *must* be this variant for any type for which
48    /// [`LayoutTypeCodegenMethods::is_backend_scalar_pair`] returns `true`.
49    /// The backend values in this variant must be the *immediate* backend types,
50    /// as returned by [`LayoutTypeCodegenMethods::scalar_pair_element_backend_type`]
51    /// with `immediate: true`.
52    Pair(V, V),
53    /// A value taking no bytes, and which therefore needs no LLVM value at all.
54    ///
55    /// If you ever need a `V` to pass to something, get a fresh poison value
56    /// from [`ConstCodegenMethods::const_poison`].
57    ///
58    /// An `OperandValue` *must* be this variant for any type for which
59    /// `is_zst` on its `Layout` returns `true`. Note however that
60    /// these values can still require alignment.
61    ZeroSized,
62}
63
64impl<V: CodegenObject> OperandValue<V> {
65    /// If this is ZeroSized/Immediate/Pair, return an array of the 0/1/2 values.
66    /// If this is Ref, return the place.
67    #[inline]
68    pub(crate) fn immediates_or_place(self) -> Either<ArrayVec<V, 2>, PlaceValue<V>> {
69        match self {
70            OperandValue::ZeroSized => Either::Left(ArrayVec::new()),
71            OperandValue::Immediate(a) => Either::Left(ArrayVec::from_iter([a])),
72            OperandValue::Pair(a, b) => Either::Left([a, b].into()),
73            OperandValue::Ref(p) => Either::Right(p),
74        }
75    }
76
77    /// Given an array of 0/1/2 immediate values, return ZeroSized/Immediate/Pair.
78    #[inline]
79    pub(crate) fn from_immediates(immediates: ArrayVec<V, 2>) -> Self {
80        let mut it = immediates.into_iter();
81        let Some(a) = it.next() else {
82            return OperandValue::ZeroSized;
83        };
84        let Some(b) = it.next() else {
85            return OperandValue::Immediate(a);
86        };
87        OperandValue::Pair(a, b)
88    }
89
90    /// Treat this value as a pointer and return the data pointer and
91    /// optional metadata as backend values.
92    ///
93    /// If you're making a place, use [`Self::deref`] instead.
94    pub(crate) fn pointer_parts(self) -> (V, Option<V>) {
95        match self {
96            OperandValue::Immediate(llptr) => (llptr, None),
97            OperandValue::Pair(llptr, llextra) => (llptr, Some(llextra)),
98            _ => bug!("OperandValue cannot be a pointer: {self:?}"),
99        }
100    }
101
102    /// Treat this value as a pointer and return the place to which it points.
103    ///
104    /// The pointer immediate doesn't inherently know its alignment,
105    /// so you need to pass it in. If you want to get it from a type's ABI
106    /// alignment, then maybe you want [`OperandRef::deref`] instead.
107    ///
108    /// This is the inverse of [`PlaceValue::address`].
109    pub(crate) fn deref(self, align: Align) -> PlaceValue<V> {
110        let (llval, llextra) = self.pointer_parts();
111        PlaceValue { llval, llextra, align }
112    }
113
114    pub(crate) fn is_expected_variant_for_type<'tcx, Cx: LayoutTypeCodegenMethods<'tcx>>(
115        &self,
116        cx: &Cx,
117        ty: TyAndLayout<'tcx>,
118    ) -> bool {
119        match self {
120            OperandValue::ZeroSized => ty.is_zst(),
121            OperandValue::Immediate(_) => cx.is_backend_immediate(ty),
122            OperandValue::Pair(_, _) => cx.is_backend_scalar_pair(ty),
123            OperandValue::Ref(_) => cx.is_backend_ref(ty),
124        }
125    }
126}
127
128/// An `OperandRef` is an "SSA" reference to a Rust value, along with
129/// its type.
130///
131/// NOTE: unless you know a value's type exactly, you should not
132/// generate LLVM opcodes acting on it and instead act via methods,
133/// to avoid nasty edge cases. In particular, using `Builder::store`
134/// directly is sure to cause problems -- use `OperandRef::store`
135/// instead.
136#[derive(Copy, Clone)]
137pub struct OperandRef<'tcx, V> {
138    /// The value.
139    pub val: OperandValue<V>,
140
141    /// The layout of value, based on its Rust type.
142    pub layout: TyAndLayout<'tcx>,
143}
144
145impl<V: CodegenObject> fmt::Debug for OperandRef<'_, V> {
146    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147        write!(f, "OperandRef({:?} @ {:?})", self.val, self.layout)
148    }
149}
150
151impl<'a, 'tcx, V: CodegenObject> OperandRef<'tcx, V> {
152    pub fn zero_sized(layout: TyAndLayout<'tcx>) -> OperandRef<'tcx, V> {
153        assert!(layout.is_zst());
154        OperandRef { val: OperandValue::ZeroSized, layout }
155    }
156
157    pub(crate) fn from_const<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
158        bx: &mut Bx,
159        val: mir::ConstValue<'tcx>,
160        ty: Ty<'tcx>,
161    ) -> Self {
162        let layout = bx.layout_of(ty);
163
164        let val = match val {
165            ConstValue::Scalar(x) => {
166                let BackendRepr::Scalar(scalar) = layout.backend_repr else {
167                    bug!("from_const: invalid ByVal layout: {:#?}", layout);
168                };
169                let llval = bx.scalar_to_backend(x, scalar, bx.immediate_backend_type(layout));
170                OperandValue::Immediate(llval)
171            }
172            ConstValue::ZeroSized => return OperandRef::zero_sized(layout),
173            ConstValue::Slice { data, meta } => {
174                let BackendRepr::ScalarPair(a_scalar, _) = layout.backend_repr else {
175                    bug!("from_const: invalid ScalarPair layout: {:#?}", layout);
176                };
177                let a = Scalar::from_pointer(
178                    Pointer::new(bx.tcx().reserve_and_set_memory_alloc(data).into(), Size::ZERO),
179                    &bx.tcx(),
180                );
181                let a_llval = bx.scalar_to_backend(
182                    a,
183                    a_scalar,
184                    bx.scalar_pair_element_backend_type(layout, 0, true),
185                );
186                let b_llval = bx.const_usize(meta);
187                OperandValue::Pair(a_llval, b_llval)
188            }
189            ConstValue::Indirect { alloc_id, offset } => {
190                let alloc = bx.tcx().global_alloc(alloc_id).unwrap_memory();
191                return Self::from_const_alloc(bx, layout, alloc, offset);
192            }
193        };
194
195        OperandRef { val, layout }
196    }
197
198    fn from_const_alloc<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
199        bx: &mut Bx,
200        layout: TyAndLayout<'tcx>,
201        alloc: rustc_middle::mir::interpret::ConstAllocation<'tcx>,
202        offset: Size,
203    ) -> Self {
204        let alloc_align = alloc.inner().align;
205        assert!(alloc_align >= layout.align.abi);
206
207        let read_scalar = |start, size, s: abi::Scalar, ty| {
208            match alloc.0.read_scalar(
209                bx,
210                alloc_range(start, size),
211                /*read_provenance*/ matches!(s.primitive(), abi::Primitive::Pointer(_)),
212            ) {
213                Ok(val) => bx.scalar_to_backend(val, s, ty),
214                Err(_) => bx.const_poison(ty),
215            }
216        };
217
218        // It may seem like all types with `Scalar` or `ScalarPair` ABI are fair game at this point.
219        // However, `MaybeUninit<u64>` is considered a `Scalar` as far as its layout is concerned --
220        // and yet cannot be represented by an interpreter `Scalar`, since we have to handle the
221        // case where some of the bytes are initialized and others are not. So, we need an extra
222        // check that walks over the type of `mplace` to make sure it is truly correct to treat this
223        // like a `Scalar` (or `ScalarPair`).
224        match layout.backend_repr {
225            BackendRepr::Scalar(s @ abi::Scalar::Initialized { .. }) => {
226                let size = s.size(bx);
227                assert_eq!(size, layout.size, "abi::Scalar size does not match layout size");
228                let val = read_scalar(offset, size, s, bx.immediate_backend_type(layout));
229                OperandRef { val: OperandValue::Immediate(val), layout }
230            }
231            BackendRepr::ScalarPair(
232                a @ abi::Scalar::Initialized { .. },
233                b @ abi::Scalar::Initialized { .. },
234            ) => {
235                let (a_size, b_size) = (a.size(bx), b.size(bx));
236                let b_offset = (offset + a_size).align_to(b.align(bx).abi);
237                assert!(b_offset.bytes() > 0);
238                let a_val = read_scalar(
239                    offset,
240                    a_size,
241                    a,
242                    bx.scalar_pair_element_backend_type(layout, 0, true),
243                );
244                let b_val = read_scalar(
245                    b_offset,
246                    b_size,
247                    b,
248                    bx.scalar_pair_element_backend_type(layout, 1, true),
249                );
250                OperandRef { val: OperandValue::Pair(a_val, b_val), layout }
251            }
252            _ if layout.is_zst() => OperandRef::zero_sized(layout),
253            _ => {
254                // Neither a scalar nor scalar pair. Load from a place
255                // FIXME: should we cache `const_data_from_alloc` to avoid repeating this for the
256                // same `ConstAllocation`?
257                let init = bx.const_data_from_alloc(alloc);
258                let base_addr = bx.static_addr_of(init, alloc_align, None);
259
260                let llval = bx.const_ptr_byte_offset(base_addr, offset);
261                bx.load_operand(PlaceRef::new_sized(llval, layout))
262            }
263        }
264    }
265
266    /// Asserts that this operand refers to a scalar and returns
267    /// a reference to its value.
268    pub fn immediate(self) -> V {
269        match self.val {
270            OperandValue::Immediate(s) => s,
271            _ => bug!("not immediate: {:?}", self),
272        }
273    }
274
275    /// Asserts that this operand is a pointer (or reference) and returns
276    /// the place to which it points.  (This requires no code to be emitted
277    /// as we represent places using the pointer to the place.)
278    ///
279    /// This uses [`Ty::builtin_deref`] to include the type of the place and
280    /// assumes the place is aligned to the pointee's usual ABI alignment.
281    ///
282    /// If you don't need the type, see [`OperandValue::pointer_parts`]
283    /// or [`OperandValue::deref`].
284    pub fn deref<Cx: CodegenMethods<'tcx>>(self, cx: &Cx) -> PlaceRef<'tcx, V> {
285        if self.layout.ty.is_box() {
286            // Derefer should have removed all Box derefs
287            bug!("dereferencing {:?} in codegen", self.layout.ty);
288        }
289
290        let projected_ty = self
291            .layout
292            .ty
293            .builtin_deref(true)
294            .unwrap_or_else(|| bug!("deref of non-pointer {:?}", self));
295
296        let layout = cx.layout_of(projected_ty);
297        self.val.deref(layout.align.abi).with_type(layout)
298    }
299
300    /// If this operand is a `Pair`, we return an aggregate with the two values.
301    /// For other cases, see `immediate`.
302    pub fn immediate_or_packed_pair<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
303        self,
304        bx: &mut Bx,
305    ) -> V {
306        if let OperandValue::Pair(a, b) = self.val {
307            let llty = bx.cx().immediate_backend_type(self.layout);
308            debug!("Operand::immediate_or_packed_pair: packing {:?} into {:?}", self, llty);
309            // Reconstruct the immediate aggregate.
310            let mut llpair = bx.cx().const_poison(llty);
311            llpair = bx.insert_value(llpair, a, 0);
312            llpair = bx.insert_value(llpair, b, 1);
313            llpair
314        } else {
315            self.immediate()
316        }
317    }
318
319    /// If the type is a pair, we return a `Pair`, otherwise, an `Immediate`.
320    pub fn from_immediate_or_packed_pair<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
321        bx: &mut Bx,
322        llval: V,
323        layout: TyAndLayout<'tcx>,
324    ) -> Self {
325        let val = if let BackendRepr::ScalarPair(..) = layout.backend_repr {
326            debug!("Operand::from_immediate_or_packed_pair: unpacking {:?} @ {:?}", llval, layout);
327
328            // Deconstruct the immediate aggregate.
329            let a_llval = bx.extract_value(llval, 0);
330            let b_llval = bx.extract_value(llval, 1);
331            OperandValue::Pair(a_llval, b_llval)
332        } else {
333            OperandValue::Immediate(llval)
334        };
335        OperandRef { val, layout }
336    }
337
338    pub(crate) fn extract_field<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
339        &self,
340        bx: &mut Bx,
341        i: usize,
342    ) -> Self {
343        let field = self.layout.field(bx.cx(), i);
344        let offset = self.layout.fields.offset(i);
345
346        let mut val = match (self.val, self.layout.backend_repr) {
347            // If the field is ZST, it has no data.
348            _ if field.is_zst() => OperandValue::ZeroSized,
349
350            // Newtype of a scalar, scalar pair or vector.
351            (OperandValue::Immediate(_) | OperandValue::Pair(..), _)
352                if field.size == self.layout.size =>
353            {
354                assert_eq!(offset.bytes(), 0);
355                self.val
356            }
357
358            // Extract a scalar component from a pair.
359            (OperandValue::Pair(a_llval, b_llval), BackendRepr::ScalarPair(a, b)) => {
360                if offset.bytes() == 0 {
361                    assert_eq!(field.size, a.size(bx.cx()));
362                    OperandValue::Immediate(a_llval)
363                } else {
364                    assert_eq!(offset, a.size(bx.cx()).align_to(b.align(bx.cx()).abi));
365                    assert_eq!(field.size, b.size(bx.cx()));
366                    OperandValue::Immediate(b_llval)
367                }
368            }
369
370            // `#[repr(simd)]` types are also immediate.
371            (OperandValue::Immediate(llval), BackendRepr::Vector { .. }) => {
372                OperandValue::Immediate(bx.extract_element(llval, bx.cx().const_usize(i as u64)))
373            }
374
375            _ => bug!("OperandRef::extract_field({:?}): not applicable", self),
376        };
377
378        match (&mut val, field.backend_repr) {
379            (OperandValue::ZeroSized, _) => {}
380            (
381                OperandValue::Immediate(llval),
382                BackendRepr::Scalar(_) | BackendRepr::ScalarPair(..) | BackendRepr::Vector { .. },
383            ) => {
384                // Bools in union fields needs to be truncated.
385                *llval = bx.to_immediate(*llval, field);
386            }
387            (OperandValue::Pair(a, b), BackendRepr::ScalarPair(a_abi, b_abi)) => {
388                // Bools in union fields needs to be truncated.
389                *a = bx.to_immediate_scalar(*a, a_abi);
390                *b = bx.to_immediate_scalar(*b, b_abi);
391            }
392            // Newtype vector of array, e.g. #[repr(simd)] struct S([i32; 4]);
393            (OperandValue::Immediate(llval), BackendRepr::Memory { sized: true }) => {
394                assert_matches!(self.layout.backend_repr, BackendRepr::Vector { .. });
395
396                let llfield_ty = bx.cx().backend_type(field);
397
398                // Can't bitcast an aggregate, so round trip through memory.
399                let llptr = bx.alloca(field.size, field.align.abi);
400                bx.store(*llval, llptr, field.align.abi);
401                *llval = bx.load(llfield_ty, llptr, field.align.abi);
402            }
403            (
404                OperandValue::Immediate(_),
405                BackendRepr::Uninhabited | BackendRepr::Memory { sized: false },
406            ) => {
407                bug!()
408            }
409            (OperandValue::Pair(..), _) => bug!(),
410            (OperandValue::Ref(..), _) => bug!(),
411        }
412
413        OperandRef { val, layout: field }
414    }
415}
416
417impl<'a, 'tcx, V: CodegenObject> OperandValue<V> {
418    /// Returns an `OperandValue` that's generally UB to use in any way.
419    ///
420    /// Depending on the `layout`, returns `ZeroSized` for ZSTs, an `Immediate` or
421    /// `Pair` containing poison value(s), or a `Ref` containing a poison pointer.
422    ///
423    /// Supports sized types only.
424    pub fn poison<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
425        bx: &mut Bx,
426        layout: TyAndLayout<'tcx>,
427    ) -> OperandValue<V> {
428        assert!(layout.is_sized());
429        if layout.is_zst() {
430            OperandValue::ZeroSized
431        } else if bx.cx().is_backend_immediate(layout) {
432            let ibty = bx.cx().immediate_backend_type(layout);
433            OperandValue::Immediate(bx.const_poison(ibty))
434        } else if bx.cx().is_backend_scalar_pair(layout) {
435            let ibty0 = bx.cx().scalar_pair_element_backend_type(layout, 0, true);
436            let ibty1 = bx.cx().scalar_pair_element_backend_type(layout, 1, true);
437            OperandValue::Pair(bx.const_poison(ibty0), bx.const_poison(ibty1))
438        } else {
439            let ptr = bx.cx().type_ptr();
440            OperandValue::Ref(PlaceValue::new_sized(bx.const_poison(ptr), layout.align.abi))
441        }
442    }
443
444    pub fn store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
445        self,
446        bx: &mut Bx,
447        dest: PlaceRef<'tcx, V>,
448    ) {
449        self.store_with_flags(bx, dest, MemFlags::empty());
450    }
451
452    pub fn volatile_store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
453        self,
454        bx: &mut Bx,
455        dest: PlaceRef<'tcx, V>,
456    ) {
457        self.store_with_flags(bx, dest, MemFlags::VOLATILE);
458    }
459
460    pub fn unaligned_volatile_store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
461        self,
462        bx: &mut Bx,
463        dest: PlaceRef<'tcx, V>,
464    ) {
465        self.store_with_flags(bx, dest, MemFlags::VOLATILE | MemFlags::UNALIGNED);
466    }
467
468    pub fn nontemporal_store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
469        self,
470        bx: &mut Bx,
471        dest: PlaceRef<'tcx, V>,
472    ) {
473        self.store_with_flags(bx, dest, MemFlags::NONTEMPORAL);
474    }
475
476    pub(crate) fn store_with_flags<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
477        self,
478        bx: &mut Bx,
479        dest: PlaceRef<'tcx, V>,
480        flags: MemFlags,
481    ) {
482        debug!("OperandRef::store: operand={:?}, dest={:?}", self, dest);
483        match self {
484            OperandValue::ZeroSized => {
485                // Avoid generating stores of zero-sized values, because the only way to have a
486                // zero-sized value is through `undef`/`poison`, and the store itself is useless.
487            }
488            OperandValue::Ref(val) => {
489                assert!(dest.layout.is_sized(), "cannot directly store unsized values");
490                if val.llextra.is_some() {
491                    bug!("cannot directly store unsized values");
492                }
493                bx.typed_place_copy_with_flags(dest.val, val, dest.layout, flags);
494            }
495            OperandValue::Immediate(s) => {
496                let val = bx.from_immediate(s);
497                bx.store_with_flags(val, dest.val.llval, dest.val.align, flags);
498            }
499            OperandValue::Pair(a, b) => {
500                let BackendRepr::ScalarPair(a_scalar, b_scalar) = dest.layout.backend_repr else {
501                    bug!("store_with_flags: invalid ScalarPair layout: {:#?}", dest.layout);
502                };
503                let b_offset = a_scalar.size(bx).align_to(b_scalar.align(bx).abi);
504
505                let val = bx.from_immediate(a);
506                let align = dest.val.align;
507                bx.store_with_flags(val, dest.val.llval, align, flags);
508
509                let llptr = bx.inbounds_ptradd(dest.val.llval, bx.const_usize(b_offset.bytes()));
510                let val = bx.from_immediate(b);
511                let align = dest.val.align.restrict_for_offset(b_offset);
512                bx.store_with_flags(val, llptr, align, flags);
513            }
514        }
515    }
516
517    pub fn store_unsized<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
518        self,
519        bx: &mut Bx,
520        indirect_dest: PlaceRef<'tcx, V>,
521    ) {
522        debug!("OperandRef::store_unsized: operand={:?}, indirect_dest={:?}", self, indirect_dest);
523        // `indirect_dest` must have `*mut T` type. We extract `T` out of it.
524        let unsized_ty = indirect_dest
525            .layout
526            .ty
527            .builtin_deref(true)
528            .unwrap_or_else(|| bug!("indirect_dest has non-pointer type: {:?}", indirect_dest));
529
530        let OperandValue::Ref(PlaceValue { llval: llptr, llextra: Some(llextra), .. }) = self
531        else {
532            bug!("store_unsized called with a sized value (or with an extern type)")
533        };
534
535        // Allocate an appropriate region on the stack, and copy the value into it. Since alloca
536        // doesn't support dynamic alignment, we allocate an extra align - 1 bytes, and align the
537        // pointer manually.
538        let (size, align) = size_of_val::size_and_align_of_dst(bx, unsized_ty, Some(llextra));
539        let one = bx.const_usize(1);
540        let align_minus_1 = bx.sub(align, one);
541        let size_extra = bx.add(size, align_minus_1);
542        let min_align = Align::ONE;
543        let alloca = bx.dynamic_alloca(size_extra, min_align);
544        let address = bx.ptrtoint(alloca, bx.type_isize());
545        let neg_address = bx.neg(address);
546        let offset = bx.and(neg_address, align_minus_1);
547        let dst = bx.inbounds_ptradd(alloca, offset);
548        bx.memcpy(dst, min_align, llptr, min_align, size, MemFlags::empty());
549
550        // Store the allocated region and the extra to the indirect place.
551        let indirect_operand = OperandValue::Pair(dst, llextra);
552        indirect_operand.store(bx, indirect_dest);
553    }
554}
555
556impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
557    fn maybe_codegen_consume_direct(
558        &mut self,
559        bx: &mut Bx,
560        place_ref: mir::PlaceRef<'tcx>,
561    ) -> Option<OperandRef<'tcx, Bx::Value>> {
562        debug!("maybe_codegen_consume_direct(place_ref={:?})", place_ref);
563
564        match self.locals[place_ref.local] {
565            LocalRef::Operand(mut o) => {
566                // Moves out of scalar and scalar pair fields are trivial.
567                for elem in place_ref.projection.iter() {
568                    match elem {
569                        mir::ProjectionElem::Field(ref f, _) => {
570                            assert!(
571                                !o.layout.ty.is_any_ptr(),
572                                "Bad PlaceRef: destructing pointers should use cast/PtrMetadata, \
573                                 but tried to access field {f:?} of pointer {o:?}",
574                            );
575                            o = o.extract_field(bx, f.index());
576                        }
577                        mir::ProjectionElem::Index(_)
578                        | mir::ProjectionElem::ConstantIndex { .. } => {
579                            // ZSTs don't require any actual memory access.
580                            // FIXME(eddyb) deduplicate this with the identical
581                            // checks in `codegen_consume` and `extract_field`.
582                            let elem = o.layout.field(bx.cx(), 0);
583                            if elem.is_zst() {
584                                o = OperandRef::zero_sized(elem);
585                            } else {
586                                return None;
587                            }
588                        }
589                        _ => return None,
590                    }
591                }
592
593                Some(o)
594            }
595            LocalRef::PendingOperand => {
596                bug!("use of {:?} before def", place_ref);
597            }
598            LocalRef::Place(..) | LocalRef::UnsizedPlace(..) => {
599                // watch out for locals that do not have an
600                // alloca; they are handled somewhat differently
601                None
602            }
603        }
604    }
605
606    pub fn codegen_consume(
607        &mut self,
608        bx: &mut Bx,
609        place_ref: mir::PlaceRef<'tcx>,
610    ) -> OperandRef<'tcx, Bx::Value> {
611        debug!("codegen_consume(place_ref={:?})", place_ref);
612
613        let ty = self.monomorphized_place_ty(place_ref);
614        let layout = bx.cx().layout_of(ty);
615
616        // ZSTs don't require any actual memory access.
617        if layout.is_zst() {
618            return OperandRef::zero_sized(layout);
619        }
620
621        if let Some(o) = self.maybe_codegen_consume_direct(bx, place_ref) {
622            return o;
623        }
624
625        // for most places, to consume them we just load them
626        // out from their home
627        let place = self.codegen_place(bx, place_ref);
628        bx.load_operand(place)
629    }
630
631    pub fn codegen_operand(
632        &mut self,
633        bx: &mut Bx,
634        operand: &mir::Operand<'tcx>,
635    ) -> OperandRef<'tcx, Bx::Value> {
636        debug!("codegen_operand(operand={:?})", operand);
637
638        match *operand {
639            mir::Operand::Copy(ref place) | mir::Operand::Move(ref place) => {
640                self.codegen_consume(bx, place.as_ref())
641            }
642
643            mir::Operand::Constant(ref constant) => {
644                let constant_ty = self.monomorphize(constant.ty());
645                // Most SIMD vector constants should be passed as immediates.
646                // (In particular, some intrinsics really rely on this.)
647                if constant_ty.is_simd() {
648                    // However, some SIMD types do not actually use the vector ABI
649                    // (in particular, packed SIMD types do not). Ensure we exclude those.
650                    let layout = bx.layout_of(constant_ty);
651                    if let BackendRepr::Vector { .. } = layout.backend_repr {
652                        let (llval, ty) = self.immediate_const_vector(bx, constant);
653                        return OperandRef {
654                            val: OperandValue::Immediate(llval),
655                            layout: bx.layout_of(ty),
656                        };
657                    }
658                }
659                self.eval_mir_constant_to_operand(bx, constant)
660            }
661        }
662    }
663}