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#[derive(Copy, Clone, Debug)]
24pub enum OperandValue<V> {
25 Ref(PlaceValue<V>),
38 Immediate(V),
45 Pair(V, V),
53 ZeroSized,
62}
63
64impl<V: CodegenObject> OperandValue<V> {
65 #[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 #[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 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 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#[derive(Copy, Clone)]
137pub struct OperandRef<'tcx, V> {
138 pub val: OperandValue<V>,
140
141 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 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 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 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 pub fn immediate(self) -> V {
269 match self.val {
270 OperandValue::Immediate(s) => s,
271 _ => bug!("not immediate: {:?}", self),
272 }
273 }
274
275 pub fn deref<Cx: CodegenMethods<'tcx>>(self, cx: &Cx) -> PlaceRef<'tcx, V> {
285 if self.layout.ty.is_box() {
286 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 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 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 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 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 field.is_zst() => OperandValue::ZeroSized,
349
350 (OperandValue::Immediate(_) | OperandValue::Pair(..), _)
352 if field.size == self.layout.size =>
353 {
354 assert_eq!(offset.bytes(), 0);
355 self.val
356 }
357
358 (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 (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 *llval = bx.to_immediate(*llval, field);
386 }
387 (OperandValue::Pair(a, b), BackendRepr::ScalarPair(a_abi, b_abi)) => {
388 *a = bx.to_immediate_scalar(*a, a_abi);
390 *b = bx.to_immediate_scalar(*b, b_abi);
391 }
392 (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 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 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 }
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 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 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 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 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 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 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 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 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 if constant_ty.is_simd() {
648 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}