1 use super::place::PlaceRef;
2 use super::{FunctionCx, LocalRef};
10 use rustc::mir::interpret::{ConstValue, ErrorHandled, Pointer, Scalar};
12 use rustc::ty::layout::{self, Align, LayoutOf, Size, TyLayout};
16 /// The representation of a Rust value. The enum variant is in fact
17 /// uniquely determined by the value's type, but is kept as a
19 #[derive(Copy, Clone, Debug)]
20 pub enum OperandValue<V> {
21 /// A reference to the actual operand. The data is guaranteed
22 /// to be valid for the operand's lifetime.
23 /// The second value, if any, is the extra data (vtable or length)
24 /// which indicates that it refers to an unsized rvalue.
25 Ref(V, Option<V>, Align),
26 /// A single LLVM value.
28 /// A pair of immediate LLVM values. Used by fat pointers too.
32 /// An `OperandRef` is an "SSA" reference to a Rust value, along with
35 /// NOTE: unless you know a value's type exactly, you should not
36 /// generate LLVM opcodes acting on it and instead act via methods,
37 /// to avoid nasty edge cases. In particular, using `Builder::store`
38 /// directly is sure to cause problems -- use `OperandRef::store`
40 #[derive(Copy, Clone)]
41 pub struct OperandRef<'tcx, V> {
43 pub val: OperandValue<V>,
45 // The layout of value, based on its Rust type.
46 pub layout: TyLayout<'tcx>,
49 impl<V: CodegenObject> fmt::Debug for OperandRef<'tcx, V> {
50 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51 write!(f, "OperandRef({:?} @ {:?})", self.val, self.layout)
55 impl<'a, 'tcx, V: CodegenObject> OperandRef<'tcx, V> {
56 pub fn new_zst<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
58 layout: TyLayout<'tcx>,
59 ) -> OperandRef<'tcx, V> {
60 assert!(layout.is_zst());
62 val: OperandValue::Immediate(bx.const_undef(bx.immediate_backend_type(layout))),
67 pub fn from_const<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
69 val: &'tcx ty::Const<'tcx>,
71 let layout = bx.layout_of(val.ty);
74 return OperandRef::new_zst(bx, layout);
77 let val_val = match val.val {
78 ty::ConstKind::Value(val_val) => val_val,
79 _ => bug!("encountered bad ConstKind in codegen"),
82 let val = match val_val {
83 ConstValue::Scalar(x) => {
84 let scalar = match layout.abi {
85 layout::Abi::Scalar(ref x) => x,
86 _ => bug!("from_const: invalid ByVal layout: {:#?}", layout),
88 let llval = bx.scalar_to_backend(x, scalar, bx.immediate_backend_type(layout));
89 OperandValue::Immediate(llval)
91 ConstValue::Slice { data, start, end } => {
92 let a_scalar = match layout.abi {
93 layout::Abi::ScalarPair(ref a, _) => a,
94 _ => bug!("from_const: invalid ScalarPair layout: {:#?}", layout),
96 let a = Scalar::from(Pointer::new(
97 bx.tcx().alloc_map.lock().create_memory_alloc(data),
98 Size::from_bytes(start as u64),
101 let a_llval = bx.scalar_to_backend(
104 bx.scalar_pair_element_backend_type(layout, 0, true),
106 let b_llval = bx.const_usize((end - start) as u64);
107 OperandValue::Pair(a_llval, b_llval)
109 ConstValue::ByRef { alloc, offset } => {
110 return bx.load_operand(bx.from_const_alloc(layout, alloc, offset));
114 OperandRef { val, layout }
117 /// Asserts that this operand refers to a scalar and returns
118 /// a reference to its value.
119 pub fn immediate(self) -> V {
121 OperandValue::Immediate(s) => s,
122 _ => bug!("not immediate: {:?}", self),
126 pub fn deref<Cx: LayoutTypeMethods<'tcx>>(self, cx: &Cx) -> PlaceRef<'tcx, V> {
127 let projected_ty = self
131 .unwrap_or_else(|| bug!("deref of non-pointer {:?}", self))
133 let (llptr, llextra) = match self.val {
134 OperandValue::Immediate(llptr) => (llptr, None),
135 OperandValue::Pair(llptr, llextra) => (llptr, Some(llextra)),
136 OperandValue::Ref(..) => bug!("Deref of by-Ref operand {:?}", self),
138 let layout = cx.layout_of(projected_ty);
139 PlaceRef { llval: llptr, llextra, layout, align: layout.align.abi }
142 /// If this operand is a `Pair`, we return an aggregate with the two values.
143 /// For other cases, see `immediate`.
144 pub fn immediate_or_packed_pair<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
148 if let OperandValue::Pair(a, b) = self.val {
149 let llty = bx.cx().backend_type(self.layout);
150 debug!("Operand::immediate_or_packed_pair: packing {:?} into {:?}", self, llty);
151 // Reconstruct the immediate aggregate.
152 let mut llpair = bx.cx().const_undef(llty);
153 let imm_a = base::from_immediate(bx, a);
154 let imm_b = base::from_immediate(bx, b);
155 llpair = bx.insert_value(llpair, imm_a, 0);
156 llpair = bx.insert_value(llpair, imm_b, 1);
163 /// If the type is a pair, we return a `Pair`, otherwise, an `Immediate`.
164 pub fn from_immediate_or_packed_pair<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
167 layout: TyLayout<'tcx>,
169 let val = if let layout::Abi::ScalarPair(ref a, ref b) = layout.abi {
170 debug!("Operand::from_immediate_or_packed_pair: unpacking {:?} @ {:?}", llval, layout);
172 // Deconstruct the immediate aggregate.
173 let a_llval = bx.extract_value(llval, 0);
174 let a_llval = base::to_immediate_scalar(bx, a_llval, a);
175 let b_llval = bx.extract_value(llval, 1);
176 let b_llval = base::to_immediate_scalar(bx, b_llval, b);
177 OperandValue::Pair(a_llval, b_llval)
179 OperandValue::Immediate(llval)
181 OperandRef { val, layout }
184 pub fn extract_field<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
189 let field = self.layout.field(bx.cx(), i);
190 let offset = self.layout.fields.offset(i);
192 let mut val = match (self.val, &self.layout.abi) {
193 // If the field is ZST, it has no data.
194 _ if field.is_zst() => {
195 return OperandRef::new_zst(bx, field);
198 // Newtype of a scalar, scalar pair or vector.
199 (OperandValue::Immediate(_), _) | (OperandValue::Pair(..), _)
200 if field.size == self.layout.size =>
202 assert_eq!(offset.bytes(), 0);
206 // Extract a scalar component from a pair.
207 (OperandValue::Pair(a_llval, b_llval), &layout::Abi::ScalarPair(ref a, ref b)) => {
208 if offset.bytes() == 0 {
209 assert_eq!(field.size, a.value.size(bx.cx()));
210 OperandValue::Immediate(a_llval)
212 assert_eq!(offset, a.value.size(bx.cx()).align_to(b.value.align(bx.cx()).abi));
213 assert_eq!(field.size, b.value.size(bx.cx()));
214 OperandValue::Immediate(b_llval)
218 // `#[repr(simd)]` types are also immediate.
219 (OperandValue::Immediate(llval), &layout::Abi::Vector { .. }) => {
220 OperandValue::Immediate(bx.extract_element(llval, bx.cx().const_usize(i as u64)))
223 _ => bug!("OperandRef::extract_field({:?}): not applicable", self),
226 // HACK(eddyb) have to bitcast pointers until LLVM removes pointee types.
227 // Bools in union fields needs to be truncated.
228 let to_immediate_or_cast = |bx: &mut Bx, val, ty| {
229 if ty == bx.cx().type_i1() { bx.trunc(val, ty) } else { bx.bitcast(val, ty) }
233 OperandValue::Immediate(ref mut llval) => {
234 *llval = to_immediate_or_cast(bx, *llval, bx.cx().immediate_backend_type(field));
236 OperandValue::Pair(ref mut a, ref mut b) => {
237 *a = to_immediate_or_cast(
240 bx.cx().scalar_pair_element_backend_type(field, 0, true),
242 *b = to_immediate_or_cast(
245 bx.cx().scalar_pair_element_backend_type(field, 1, true),
248 OperandValue::Ref(..) => bug!(),
251 OperandRef { val, layout: field }
255 impl<'a, 'tcx, V: CodegenObject> OperandValue<V> {
256 pub fn store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
259 dest: PlaceRef<'tcx, V>,
261 self.store_with_flags(bx, dest, MemFlags::empty());
264 pub fn volatile_store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
267 dest: PlaceRef<'tcx, V>,
269 self.store_with_flags(bx, dest, MemFlags::VOLATILE);
272 pub fn unaligned_volatile_store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
275 dest: PlaceRef<'tcx, V>,
277 self.store_with_flags(bx, dest, MemFlags::VOLATILE | MemFlags::UNALIGNED);
280 pub fn nontemporal_store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
283 dest: PlaceRef<'tcx, V>,
285 self.store_with_flags(bx, dest, MemFlags::NONTEMPORAL);
288 fn store_with_flags<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
291 dest: PlaceRef<'tcx, V>,
294 debug!("OperandRef::store: operand={:?}, dest={:?}", self, dest);
295 // Avoid generating stores of zero-sized values, because the only way to have a zero-sized
296 // value is through `undef`, and store itself is useless.
297 if dest.layout.is_zst() {
301 OperandValue::Ref(r, None, source_align) => {
302 base::memcpy_ty(bx, dest.llval, dest.align, r, source_align, dest.layout, flags)
304 OperandValue::Ref(_, Some(_), _) => {
305 bug!("cannot directly store unsized values");
307 OperandValue::Immediate(s) => {
308 let val = base::from_immediate(bx, s);
309 bx.store_with_flags(val, dest.llval, dest.align, flags);
311 OperandValue::Pair(a, b) => {
312 let (a_scalar, b_scalar) = match dest.layout.abi {
313 layout::Abi::ScalarPair(ref a, ref b) => (a, b),
314 _ => bug!("store_with_flags: invalid ScalarPair layout: {:#?}", dest.layout),
316 let b_offset = a_scalar.value.size(bx).align_to(b_scalar.value.align(bx).abi);
318 let llptr = bx.struct_gep(dest.llval, 0);
319 let val = base::from_immediate(bx, a);
320 let align = dest.align;
321 bx.store_with_flags(val, llptr, align, flags);
323 let llptr = bx.struct_gep(dest.llval, 1);
324 let val = base::from_immediate(bx, b);
325 let align = dest.align.restrict_for_offset(b_offset);
326 bx.store_with_flags(val, llptr, align, flags);
331 pub fn store_unsized<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
334 indirect_dest: PlaceRef<'tcx, V>,
336 debug!("OperandRef::store_unsized: operand={:?}, indirect_dest={:?}", self, indirect_dest);
337 let flags = MemFlags::empty();
339 // `indirect_dest` must have `*mut T` type. We extract `T` out of it.
340 let unsized_ty = indirect_dest
344 .unwrap_or_else(|| bug!("indirect_dest has non-pointer type: {:?}", indirect_dest))
347 let (llptr, llextra) = if let OperandValue::Ref(llptr, Some(llextra), _) = self {
350 bug!("store_unsized called with a sized value")
353 // FIXME: choose an appropriate alignment, or use dynamic align somehow
354 let max_align = Align::from_bits(128).unwrap();
355 let min_align = Align::from_bits(8).unwrap();
357 // Allocate an appropriate region on the stack, and copy the value into it
358 let (llsize, _) = glue::size_and_align_of_dst(bx, unsized_ty, Some(llextra));
359 let lldst = bx.array_alloca(bx.cx().type_i8(), llsize, max_align);
360 bx.memcpy(lldst, max_align, llptr, min_align, llsize, flags);
362 // Store the allocated region and the extra to the indirect place.
363 let indirect_operand = OperandValue::Pair(lldst, llextra);
364 indirect_operand.store(bx, indirect_dest);
368 impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
369 fn maybe_codegen_consume_direct(
372 place_ref: &mir::PlaceRef<'_, 'tcx>,
373 ) -> Option<OperandRef<'tcx, Bx::Value>> {
374 debug!("maybe_codegen_consume_direct(place_ref={:?})", place_ref);
376 match self.locals[*place_ref.local] {
377 LocalRef::Operand(Some(mut o)) => {
378 // Moves out of scalar and scalar pair fields are trivial.
379 for elem in place_ref.projection.iter() {
381 mir::ProjectionElem::Field(ref f, _) => {
382 o = o.extract_field(bx, f.index());
384 mir::ProjectionElem::Index(_)
385 | mir::ProjectionElem::ConstantIndex { .. } => {
386 // ZSTs don't require any actual memory access.
387 // FIXME(eddyb) deduplicate this with the identical
388 // checks in `codegen_consume` and `extract_field`.
389 let elem = o.layout.field(bx.cx(), 0);
391 o = OperandRef::new_zst(bx, elem);
402 LocalRef::Operand(None) => {
403 bug!("use of {:?} before def", place_ref);
405 LocalRef::Place(..) | LocalRef::UnsizedPlace(..) => {
406 // watch out for locals that do not have an
407 // alloca; they are handled somewhat differently
413 pub fn codegen_consume(
416 place_ref: &mir::PlaceRef<'_, 'tcx>,
417 ) -> OperandRef<'tcx, Bx::Value> {
418 debug!("codegen_consume(place_ref={:?})", place_ref);
420 let ty = self.monomorphized_place_ty(place_ref);
421 let layout = bx.cx().layout_of(ty);
423 // ZSTs don't require any actual memory access.
425 return OperandRef::new_zst(bx, layout);
428 if let Some(o) = self.maybe_codegen_consume_direct(bx, place_ref) {
432 // for most places, to consume them we just load them
433 // out from their home
434 let place = self.codegen_place(bx, place_ref);
435 bx.load_operand(place)
438 pub fn codegen_operand(
441 operand: &mir::Operand<'tcx>,
442 ) -> OperandRef<'tcx, Bx::Value> {
443 debug!("codegen_operand(operand={:?})", operand);
446 mir::Operand::Copy(ref place) | mir::Operand::Move(ref place) => {
447 self.codegen_consume(bx, &place.as_ref())
450 mir::Operand::Constant(ref constant) => {
451 self.eval_mir_constant_to_operand(bx, constant).unwrap_or_else(|err| {
453 // errored or at least linted
454 ErrorHandled::Reported => {}
455 ErrorHandled::TooGeneric => bug!("codgen encountered polymorphic constant"),
457 // Allow RalfJ to sleep soundly knowing that even refactorings that remove
458 // the above error (or silence it under some conditions) will not cause UB.
460 // We still have to return an operand but it doesn't matter,
461 // this code is unreachable.
462 let ty = self.monomorphize(&constant.literal.ty);
463 let layout = bx.cx().layout_of(ty);
464 bx.load_operand(PlaceRef::new_sized(
465 bx.cx().const_undef(bx.cx().type_ptr_to(bx.cx().backend_type(layout))),