1 use rustc::mir::interpret::{ConstValue, ErrorHandled};
4 use rustc::ty::layout::{self, Align, LayoutOf, TyLayout};
14 use super::{FunctionCx, LocalRef};
15 use super::place::PlaceRef;
17 /// The representation of a Rust value. The enum variant is in fact
18 /// uniquely determined by the value's type, but is kept as a
20 #[derive(Copy, Clone, Debug)]
21 pub enum OperandValue<V> {
22 /// A reference to the actual operand. The data is guaranteed
23 /// to be valid for the operand's lifetime.
24 /// The second value, if any, is the extra data (vtable or length)
25 /// which indicates that it refers to an unsized rvalue.
26 Ref(V, Option<V>, Align),
27 /// A single LLVM value.
29 /// A pair of immediate LLVM values. Used by fat pointers too.
33 /// An `OperandRef` is an "SSA" reference to a Rust value, along with
36 /// NOTE: unless you know a value's type exactly, you should not
37 /// generate LLVM opcodes acting on it and instead act via methods,
38 /// to avoid nasty edge cases. In particular, using `Builder::store`
39 /// directly is sure to cause problems -- use `OperandRef::store`
41 #[derive(Copy, Clone)]
42 pub struct OperandRef<'tcx, V> {
44 pub val: OperandValue<V>,
46 // The layout of value, based on its Rust type.
47 pub layout: TyLayout<'tcx>,
50 impl<V: CodegenObject> fmt::Debug for OperandRef<'tcx, V> {
51 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52 write!(f, "OperandRef({:?} @ {:?})", self.val, self.layout)
56 impl<'a, 'tcx: 'a, V: CodegenObject> OperandRef<'tcx, V> {
57 pub fn new_zst<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
59 layout: TyLayout<'tcx>
60 ) -> OperandRef<'tcx, V> {
61 assert!(layout.is_zst());
63 val: OperandValue::Immediate(bx.const_undef(bx.immediate_backend_type(layout))),
68 pub fn from_const<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
70 val: &'tcx ty::Const<'tcx>
71 ) -> Result<Self, ErrorHandled> {
72 let layout = bx.layout_of(val.ty);
75 return Ok(OperandRef::new_zst(bx, layout));
78 let val = match val.val {
79 ConstValue::Unevaluated(..) => bug!("unevaluated constant in `OperandRef::from_const`"),
80 ConstValue::Param(_) => bug!("encountered a ConstValue::Param in codegen"),
81 ConstValue::Infer(_) => bug!("encountered a ConstValue::Infer in codegen"),
82 ConstValue::Placeholder(_) => bug!("encountered a ConstValue::Placeholder in codegen"),
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(
91 bx.immediate_backend_type(layout),
93 OperandValue::Immediate(llval)
95 ConstValue::Slice(a, b) => {
96 let a_scalar = match layout.abi {
97 layout::Abi::ScalarPair(ref a, _) => a,
98 _ => bug!("from_const: invalid ScalarPair layout: {:#?}", layout)
100 let a_llval = bx.scalar_to_backend(
103 bx.scalar_pair_element_backend_type(layout, 0, true),
105 let b_llval = bx.const_usize(b);
106 OperandValue::Pair(a_llval, b_llval)
108 ConstValue::ByRef(ptr, alloc) => {
109 return Ok(bx.load_operand(bx.from_const_alloc(layout, alloc, ptr.offset)));
119 /// Asserts that this operand refers to a scalar and returns
120 /// a reference to its value.
121 pub fn immediate(self) -> V {
123 OperandValue::Immediate(s) => s,
124 _ => bug!("not immediate: {:?}", self)
128 pub fn deref<Cx: LayoutTypeMethods<'tcx>>(
131 ) -> PlaceRef<'tcx, V> {
132 let projected_ty = self.layout.ty.builtin_deref(true)
133 .unwrap_or_else(|| bug!("deref of non-pointer {:?}", self)).ty;
134 let (llptr, llextra) = match self.val {
135 OperandValue::Immediate(llptr) => (llptr, None),
136 OperandValue::Pair(llptr, llextra) => (llptr, Some(llextra)),
137 OperandValue::Ref(..) => bug!("Deref of by-Ref operand {:?}", self)
139 let layout = cx.layout_of(projected_ty);
144 align: layout.align.abi,
148 /// If this operand is a `Pair`, we return an aggregate with the two values.
149 /// For other cases, see `immediate`.
150 pub fn immediate_or_packed_pair<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
154 if let OperandValue::Pair(a, b) = self.val {
155 let llty = bx.cx().backend_type(self.layout);
156 debug!("Operand::immediate_or_packed_pair: packing {:?} into {:?}",
158 // Reconstruct the immediate aggregate.
159 let mut llpair = bx.cx().const_undef(llty);
160 let imm_a = base::from_immediate(bx, a);
161 let imm_b = base::from_immediate(bx, b);
162 llpair = bx.insert_value(llpair, imm_a, 0);
163 llpair = bx.insert_value(llpair, imm_b, 1);
170 /// If the type is a pair, we return a `Pair`, otherwise, an `Immediate`.
171 pub fn from_immediate_or_packed_pair<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
174 layout: TyLayout<'tcx>
176 let val = if let layout::Abi::ScalarPair(ref a, ref b) = layout.abi {
177 debug!("Operand::from_immediate_or_packed_pair: unpacking {:?} @ {:?}",
180 // Deconstruct the immediate aggregate.
181 let a_llval = bx.extract_value(llval, 0);
182 let a_llval = base::to_immediate_scalar(bx, a_llval, a);
183 let b_llval = bx.extract_value(llval, 1);
184 let b_llval = base::to_immediate_scalar(bx, b_llval, b);
185 OperandValue::Pair(a_llval, b_llval)
187 OperandValue::Immediate(llval)
189 OperandRef { val, layout }
192 pub fn extract_field<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
197 let field = self.layout.field(bx.cx(), i);
198 let offset = self.layout.fields.offset(i);
200 let mut val = match (self.val, &self.layout.abi) {
201 // If the field is ZST, it has no data.
202 _ if field.is_zst() => {
203 return OperandRef::new_zst(bx, field);
206 // Newtype of a scalar, scalar pair or vector.
207 (OperandValue::Immediate(_), _) |
208 (OperandValue::Pair(..), _) if field.size == self.layout.size => {
209 assert_eq!(offset.bytes(), 0);
213 // Extract a scalar component from a pair.
214 (OperandValue::Pair(a_llval, b_llval), &layout::Abi::ScalarPair(ref a, ref b)) => {
215 if offset.bytes() == 0 {
216 assert_eq!(field.size, a.value.size(bx.cx()));
217 OperandValue::Immediate(a_llval)
219 assert_eq!(offset, a.value.size(bx.cx())
220 .align_to(b.value.align(bx.cx()).abi));
221 assert_eq!(field.size, b.value.size(bx.cx()));
222 OperandValue::Immediate(b_llval)
226 // `#[repr(simd)]` types are also immediate.
227 (OperandValue::Immediate(llval), &layout::Abi::Vector { .. }) => {
228 OperandValue::Immediate(
229 bx.extract_element(llval, bx.cx().const_usize(i as u64)))
232 _ => bug!("OperandRef::extract_field({:?}): not applicable", self)
235 // HACK(eddyb) have to bitcast pointers until LLVM removes pointee types.
236 // Bools in union fields needs to be truncated.
237 let to_immediate_or_cast = |bx: &mut Bx, val, ty| {
238 if ty == bx.cx().type_i1() {
246 OperandValue::Immediate(ref mut llval) => {
247 *llval = to_immediate_or_cast(bx, *llval, bx.cx().immediate_backend_type(field));
249 OperandValue::Pair(ref mut a, ref mut b) => {
250 *a = to_immediate_or_cast(bx, *a, bx.cx()
251 .scalar_pair_element_backend_type(field, 0, true));
252 *b = to_immediate_or_cast(bx, *b, bx.cx()
253 .scalar_pair_element_backend_type(field, 1, true));
255 OperandValue::Ref(..) => bug!()
265 impl<'a, 'tcx: 'a, V: CodegenObject> OperandValue<V> {
266 pub fn store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
269 dest: PlaceRef<'tcx, V>
271 self.store_with_flags(bx, dest, MemFlags::empty());
274 pub fn volatile_store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
277 dest: PlaceRef<'tcx, V>
279 self.store_with_flags(bx, dest, MemFlags::VOLATILE);
282 pub fn unaligned_volatile_store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
285 dest: PlaceRef<'tcx, V>,
287 self.store_with_flags(bx, dest, MemFlags::VOLATILE | MemFlags::UNALIGNED);
290 pub fn nontemporal_store<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
293 dest: PlaceRef<'tcx, V>
295 self.store_with_flags(bx, dest, MemFlags::NONTEMPORAL);
298 fn store_with_flags<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
301 dest: PlaceRef<'tcx, V>,
304 debug!("OperandRef::store: operand={:?}, dest={:?}", self, dest);
305 // Avoid generating stores of zero-sized values, because the only way to have a zero-sized
306 // value is through `undef`, and store itself is useless.
307 if dest.layout.is_zst() {
311 OperandValue::Ref(r, None, source_align) => {
312 base::memcpy_ty(bx, dest.llval, dest.align, r, source_align,
315 OperandValue::Ref(_, Some(_), _) => {
316 bug!("cannot directly store unsized values");
318 OperandValue::Immediate(s) => {
319 let val = base::from_immediate(bx, s);
320 bx.store_with_flags(val, dest.llval, dest.align, flags);
322 OperandValue::Pair(a, b) => {
323 let (a_scalar, b_scalar) = match dest.layout.abi {
324 layout::Abi::ScalarPair(ref a, ref b) => (a, b),
325 _ => bug!("store_with_flags: invalid ScalarPair layout: {:#?}", dest.layout)
327 let b_offset = a_scalar.value.size(bx).align_to(b_scalar.value.align(bx).abi);
329 let llptr = bx.struct_gep(dest.llval, 0);
330 let val = base::from_immediate(bx, a);
331 let align = dest.align;
332 bx.store_with_flags(val, llptr, align, flags);
334 let llptr = bx.struct_gep(dest.llval, 1);
335 let val = base::from_immediate(bx, b);
336 let align = dest.align.restrict_for_offset(b_offset);
337 bx.store_with_flags(val, llptr, align, flags);
341 pub fn store_unsized<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
344 indirect_dest: PlaceRef<'tcx, V>
346 debug!("OperandRef::store_unsized: operand={:?}, indirect_dest={:?}", self, indirect_dest);
347 let flags = MemFlags::empty();
349 // `indirect_dest` must have `*mut T` type. We extract `T` out of it.
350 let unsized_ty = indirect_dest.layout.ty.builtin_deref(true)
351 .unwrap_or_else(|| bug!("indirect_dest has non-pointer type: {:?}", indirect_dest)).ty;
353 let (llptr, llextra) =
354 if let OperandValue::Ref(llptr, Some(llextra), _) = self {
357 bug!("store_unsized called with a sized value")
360 // FIXME: choose an appropriate alignment, or use dynamic align somehow
361 let max_align = Align::from_bits(128).unwrap();
362 let min_align = Align::from_bits(8).unwrap();
364 // Allocate an appropriate region on the stack, and copy the value into it
365 let (llsize, _) = glue::size_and_align_of_dst(bx, unsized_ty, Some(llextra));
366 let lldst = bx.array_alloca(bx.cx().type_i8(), llsize, "unsized_tmp", max_align);
367 bx.memcpy(lldst, max_align, llptr, min_align, llsize, flags);
369 // Store the allocated region and the extra to the indirect place.
370 let indirect_operand = OperandValue::Pair(lldst, llextra);
371 indirect_operand.store(bx, indirect_dest);
375 impl<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
376 fn maybe_codegen_consume_direct(
379 place: &mir::Place<'tcx>
380 ) -> Option<OperandRef<'tcx, Bx::Value>> {
381 debug!("maybe_codegen_consume_direct(place={:?})", place);
383 place.iterate(|place_base, place_projection| {
384 if let mir::PlaceBase::Local(index) = place_base {
385 match self.locals[*index] {
386 LocalRef::Operand(Some(mut o)) => {
387 // Moves out of scalar and scalar pair fields are trivial.
388 for proj in place_projection {
390 mir::ProjectionElem::Field(ref f, _) => {
391 o = o.extract_field(bx, f.index());
393 mir::ProjectionElem::Index(_) |
394 mir::ProjectionElem::ConstantIndex { .. } => {
395 // ZSTs don't require any actual memory access.
396 // FIXME(eddyb) deduplicate this with the identical
397 // checks in `codegen_consume` and `extract_field`.
398 let elem = o.layout.field(bx.cx(), 0);
400 o = OperandRef::new_zst(bx, elem);
411 LocalRef::Operand(None) => {
412 bug!("use of {:?} before def", place);
414 LocalRef::Place(..) | LocalRef::UnsizedPlace(..) => {
415 // watch out for locals that do not have an
416 // alloca; they are handled somewhat differently
426 pub fn codegen_consume(
429 place: &mir::Place<'tcx>
430 ) -> OperandRef<'tcx, Bx::Value> {
431 debug!("codegen_consume(place={:?})", place);
433 let ty = self.monomorphized_place_ty(place);
434 let layout = bx.cx().layout_of(ty);
436 // ZSTs don't require any actual memory access.
438 return OperandRef::new_zst(bx, layout);
441 if let Some(o) = self.maybe_codegen_consume_direct(bx, place) {
445 // for most places, to consume them we just load them
446 // out from their home
447 let place = self.codegen_place(bx, place);
448 bx.load_operand(place)
451 pub fn codegen_operand(
454 operand: &mir::Operand<'tcx>
455 ) -> OperandRef<'tcx, Bx::Value> {
456 debug!("codegen_operand(operand={:?})", operand);
459 mir::Operand::Copy(ref place) |
460 mir::Operand::Move(ref place) => {
461 self.codegen_consume(bx, place)
464 mir::Operand::Constant(ref constant) => {
465 let ty = self.monomorphize(&constant.ty);
466 self.eval_mir_constant(constant)
467 .and_then(|c| OperandRef::from_const(bx, c))
468 .unwrap_or_else(|err| {
470 // errored or at least linted
471 ErrorHandled::Reported => {},
472 ErrorHandled::TooGeneric => {
473 bug!("codgen encountered polymorphic constant")
476 // Allow RalfJ to sleep soundly knowing that even refactorings that remove
477 // the above error (or silence it under some conditions) will not cause UB
479 // We've errored, so we don't have to produce working code.
480 let layout = bx.cx().layout_of(ty);
481 bx.load_operand(PlaceRef::new_sized(
482 bx.cx().const_undef(bx.cx().type_ptr_to(bx.cx().backend_type(layout))),