1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use rustc::mir::interpret::ConstEvalErr;
13 use rustc::mir::interpret::{ConstValue, ScalarMaybeUndef};
15 use rustc::ty::layout::{self, Align, LayoutOf, TyLayout};
16 use rustc_data_structures::indexed_vec::Idx;
17 use rustc_data_structures::sync::Lrc;
20 use common::{CodegenCx, C_undef, C_usize};
21 use builder::{Builder, MemFlags};
23 use type_of::LayoutLlvmExt;
29 use super::{FunctionCx, LocalRef};
30 use super::constant::scalar_to_llvm;
31 use super::place::PlaceRef;
33 /// The representation of a Rust value. The enum variant is in fact
34 /// uniquely determined by the value's type, but is kept as a
36 #[derive(Copy, Clone, Debug)]
37 pub enum OperandValue<'ll> {
38 /// A reference to the actual operand. The data is guaranteed
39 /// to be valid for the operand's lifetime.
40 Ref(&'ll Value, Align),
41 /// A reference to the unsized operand. The data is guaranteed
42 /// to be valid for the operand's lifetime.
43 /// The second field is the extra.
44 UnsizedRef(&'ll Value, &'ll Value),
45 /// A single LLVM value.
46 Immediate(&'ll Value),
47 /// A pair of immediate LLVM values. Used by fat pointers too.
48 Pair(&'ll Value, &'ll Value)
51 /// An `OperandRef` is an "SSA" reference to a Rust value, along with
54 /// NOTE: unless you know a value's type exactly, you should not
55 /// generate LLVM opcodes acting on it and instead act via methods,
56 /// to avoid nasty edge cases. In particular, using `Builder::store`
57 /// directly is sure to cause problems -- use `OperandRef::store`
59 #[derive(Copy, Clone)]
60 pub struct OperandRef<'ll, 'tcx> {
62 pub val: OperandValue<'ll>,
64 // The layout of value, based on its Rust type.
65 pub layout: TyLayout<'tcx>,
68 impl fmt::Debug for OperandRef<'ll, 'tcx> {
69 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
70 write!(f, "OperandRef({:?} @ {:?})", self.val, self.layout)
74 impl OperandRef<'ll, 'tcx> {
75 pub fn new_zst(cx: &CodegenCx<'ll, 'tcx>,
76 layout: TyLayout<'tcx>) -> OperandRef<'ll, 'tcx> {
77 assert!(layout.is_zst());
79 val: OperandValue::Immediate(C_undef(layout.immediate_llvm_type(cx))),
84 pub fn from_const(bx: &Builder<'a, 'll, 'tcx>,
85 val: &'tcx ty::Const<'tcx>)
86 -> Result<OperandRef<'ll, 'tcx>, Lrc<ConstEvalErr<'tcx>>> {
87 let layout = bx.cx.layout_of(val.ty);
90 return Ok(OperandRef::new_zst(bx.cx, layout));
93 let val = match val.val {
94 ConstValue::Unevaluated(..) => bug!(),
95 ConstValue::Scalar(x) => {
96 let scalar = match layout.abi {
97 layout::Abi::Scalar(ref x) => x,
98 _ => bug!("from_const: invalid ByVal layout: {:#?}", layout)
100 let llval = scalar_to_llvm(
104 layout.immediate_llvm_type(bx.cx),
106 OperandValue::Immediate(llval)
108 ConstValue::ScalarPair(a, b) => {
109 let (a_scalar, b_scalar) = match layout.abi {
110 layout::Abi::ScalarPair(ref a, ref b) => (a, b),
111 _ => bug!("from_const: invalid ScalarPair layout: {:#?}", layout)
113 let a_llval = scalar_to_llvm(
117 layout.scalar_pair_element_llvm_type(bx.cx, 0, true),
119 let b_layout = layout.scalar_pair_element_llvm_type(bx.cx, 1, true);
120 let b_llval = match b {
121 ScalarMaybeUndef::Scalar(b) => scalar_to_llvm(
127 ScalarMaybeUndef::Undef => C_undef(b_layout),
129 OperandValue::Pair(a_llval, b_llval)
131 ConstValue::ByRef(alloc, offset) => {
132 return Ok(PlaceRef::from_const_alloc(bx, layout, alloc, offset).load(bx));
142 /// Asserts that this operand refers to a scalar and returns
143 /// a reference to its value.
144 pub fn immediate(self) -> &'ll Value {
146 OperandValue::Immediate(s) => s,
147 _ => bug!("not immediate: {:?}", self)
151 pub fn deref(self, cx: &CodegenCx<'ll, 'tcx>) -> PlaceRef<'ll, 'tcx> {
152 let projected_ty = self.layout.ty.builtin_deref(true)
153 .unwrap_or_else(|| bug!("deref of non-pointer {:?}", self)).ty;
154 let (llptr, llextra) = match self.val {
155 OperandValue::Immediate(llptr) => (llptr, None),
156 OperandValue::Pair(llptr, llextra) => (llptr, Some(llextra)),
157 OperandValue::Ref(..) |
158 OperandValue::UnsizedRef(..) => bug!("Deref of by-Ref operand {:?}", self)
160 let layout = cx.layout_of(projected_ty);
169 /// If this operand is a `Pair`, we return an aggregate with the two values.
170 /// For other cases, see `immediate`.
171 pub fn immediate_or_packed_pair(self, bx: &Builder<'a, 'll, 'tcx>) -> &'ll Value {
172 if let OperandValue::Pair(a, b) = self.val {
173 let llty = self.layout.llvm_type(bx.cx);
174 debug!("Operand::immediate_or_packed_pair: packing {:?} into {:?}",
176 // Reconstruct the immediate aggregate.
177 let mut llpair = C_undef(llty);
178 llpair = bx.insert_value(llpair, base::from_immediate(bx, a), 0);
179 llpair = bx.insert_value(llpair, base::from_immediate(bx, b), 1);
186 /// If the type is a pair, we return a `Pair`, otherwise, an `Immediate`.
187 pub fn from_immediate_or_packed_pair(bx: &Builder<'a, 'll, 'tcx>,
189 layout: TyLayout<'tcx>)
190 -> OperandRef<'ll, 'tcx> {
191 let val = if let layout::Abi::ScalarPair(ref a, ref b) = layout.abi {
192 debug!("Operand::from_immediate_or_packed_pair: unpacking {:?} @ {:?}",
195 // Deconstruct the immediate aggregate.
196 let a_llval = base::to_immediate_scalar(bx, bx.extract_value(llval, 0), a);
197 let b_llval = base::to_immediate_scalar(bx, bx.extract_value(llval, 1), b);
198 OperandValue::Pair(a_llval, b_llval)
200 OperandValue::Immediate(llval)
202 OperandRef { val, layout }
205 pub fn extract_field(&self, bx: &Builder<'a, 'll, 'tcx>, i: usize) -> OperandRef<'ll, 'tcx> {
206 let field = self.layout.field(bx.cx, i);
207 let offset = self.layout.fields.offset(i);
209 let mut val = match (self.val, &self.layout.abi) {
210 // If the field is ZST, it has no data.
211 _ if field.is_zst() => {
212 return OperandRef::new_zst(bx.cx, field);
215 // Newtype of a scalar, scalar pair or vector.
216 (OperandValue::Immediate(_), _) |
217 (OperandValue::Pair(..), _) if field.size == self.layout.size => {
218 assert_eq!(offset.bytes(), 0);
222 // Extract a scalar component from a pair.
223 (OperandValue::Pair(a_llval, b_llval), &layout::Abi::ScalarPair(ref a, ref b)) => {
224 if offset.bytes() == 0 {
225 assert_eq!(field.size, a.value.size(bx.cx));
226 OperandValue::Immediate(a_llval)
228 assert_eq!(offset, a.value.size(bx.cx)
229 .abi_align(b.value.align(bx.cx)));
230 assert_eq!(field.size, b.value.size(bx.cx));
231 OperandValue::Immediate(b_llval)
235 // `#[repr(simd)]` types are also immediate.
236 (OperandValue::Immediate(llval), &layout::Abi::Vector { .. }) => {
237 OperandValue::Immediate(
238 bx.extract_element(llval, C_usize(bx.cx, i as u64)))
241 _ => bug!("OperandRef::extract_field({:?}): not applicable", self)
244 // HACK(eddyb) have to bitcast pointers until LLVM removes pointee types.
246 OperandValue::Immediate(ref mut llval) => {
247 *llval = bx.bitcast(*llval, field.immediate_llvm_type(bx.cx));
249 OperandValue::Pair(ref mut a, ref mut b) => {
250 *a = bx.bitcast(*a, field.scalar_pair_element_llvm_type(bx.cx, 0, true));
251 *b = bx.bitcast(*b, field.scalar_pair_element_llvm_type(bx.cx, 1, true));
253 OperandValue::Ref(..) |
254 OperandValue::UnsizedRef(..) => bug!()
264 impl OperandValue<'ll> {
265 pub fn store(self, bx: &Builder<'a, 'll, 'tcx>, dest: PlaceRef<'ll, 'tcx>) {
266 self.store_with_flags(bx, dest, MemFlags::empty());
269 pub fn volatile_store(self, bx: &Builder<'a, 'll, 'tcx>, dest: PlaceRef<'ll, 'tcx>) {
270 self.store_with_flags(bx, dest, MemFlags::VOLATILE);
273 pub fn unaligned_volatile_store(self, bx: &Builder<'a, 'll, 'tcx>, dest: PlaceRef<'ll, 'tcx>) {
274 self.store_with_flags(bx, dest, MemFlags::VOLATILE | MemFlags::UNALIGNED);
277 pub fn nontemporal_store(self, bx: &Builder<'a, 'll, 'tcx>, dest: PlaceRef<'ll, 'tcx>) {
278 self.store_with_flags(bx, dest, MemFlags::NONTEMPORAL);
283 bx: &Builder<'a, 'll, 'tcx>,
284 dest: PlaceRef<'ll, 'tcx>,
287 debug!("OperandRef::store: operand={:?}, dest={:?}", self, dest);
288 // Avoid generating stores of zero-sized values, because the only way to have a zero-sized
289 // value is through `undef`, and store itself is useless.
290 if dest.layout.is_zst() {
294 OperandValue::Ref(r, source_align) => {
295 base::memcpy_ty(bx, dest.llval, r, dest.layout,
296 source_align.min(dest.align), flags)
298 OperandValue::UnsizedRef(..) => {
299 bug!("cannot directly store unsized values");
301 OperandValue::Immediate(s) => {
302 let val = base::from_immediate(bx, s);
303 bx.store_with_flags(val, dest.llval, dest.align, flags);
305 OperandValue::Pair(a, b) => {
306 for (i, &x) in [a, b].iter().enumerate() {
307 let llptr = bx.struct_gep(dest.llval, i as u64);
308 let val = base::from_immediate(bx, x);
309 bx.store_with_flags(val, llptr, dest.align, flags);
315 pub fn store_unsized(self, bx: &Builder<'a, 'll, 'tcx>, indirect_dest: PlaceRef<'ll, 'tcx>) {
316 debug!("OperandRef::store_unsized: operand={:?}, indirect_dest={:?}", self, indirect_dest);
317 let flags = MemFlags::empty();
319 // `indirect_dest` must have `*mut T` type. We extract `T` out of it.
320 let unsized_ty = indirect_dest.layout.ty.builtin_deref(true)
321 .unwrap_or_else(|| bug!("indirect_dest has non-pointer type: {:?}", indirect_dest)).ty;
323 let (llptr, llextra) =
324 if let OperandValue::UnsizedRef(llptr, llextra) = self {
327 bug!("store_unsized called with a sized value")
330 // FIXME: choose an appropriate alignment, or use dynamic align somehow
331 let max_align = Align::from_bits(128, 128).unwrap();
332 let min_align = Align::from_bits(8, 8).unwrap();
334 // Allocate an appropriate region on the stack, and copy the value into it
335 let (llsize, _) = glue::size_and_align_of_dst(&bx, unsized_ty, Some(llextra));
336 let lldst = bx.array_alloca(Type::i8(bx.cx), llsize, "unsized_tmp", max_align);
337 base::call_memcpy(&bx, lldst, llptr, llsize, min_align, flags);
339 // Store the allocated region and the extra to the indirect place.
340 let indirect_operand = OperandValue::Pair(lldst, llextra);
341 indirect_operand.store(&bx, indirect_dest);
345 impl FunctionCx<'a, 'll, 'tcx> {
346 fn maybe_codegen_consume_direct(&mut self,
347 bx: &Builder<'a, 'll, 'tcx>,
348 place: &mir::Place<'tcx>)
349 -> Option<OperandRef<'ll, 'tcx>>
351 debug!("maybe_codegen_consume_direct(place={:?})", place);
353 // watch out for locals that do not have an
354 // alloca; they are handled somewhat differently
355 if let mir::Place::Local(index) = *place {
356 match self.locals[index] {
357 LocalRef::Operand(Some(o)) => {
360 LocalRef::Operand(None) => {
361 bug!("use of {:?} before def", place);
363 LocalRef::Place(..) | LocalRef::UnsizedPlace(..) => {
369 // Moves out of scalar and scalar pair fields are trivial.
370 if let &mir::Place::Projection(ref proj) = place {
371 if let Some(o) = self.maybe_codegen_consume_direct(bx, &proj.base) {
373 mir::ProjectionElem::Field(ref f, _) => {
374 return Some(o.extract_field(bx, f.index()));
376 mir::ProjectionElem::Index(_) |
377 mir::ProjectionElem::ConstantIndex { .. } => {
378 // ZSTs don't require any actual memory access.
379 // FIXME(eddyb) deduplicate this with the identical
380 // checks in `codegen_consume` and `extract_field`.
381 let elem = o.layout.field(bx.cx, 0);
383 return Some(OperandRef::new_zst(bx.cx, elem));
394 pub fn codegen_consume(&mut self,
395 bx: &Builder<'a, 'll, 'tcx>,
396 place: &mir::Place<'tcx>)
397 -> OperandRef<'ll, 'tcx>
399 debug!("codegen_consume(place={:?})", place);
401 let ty = self.monomorphized_place_ty(place);
402 let layout = bx.cx.layout_of(ty);
404 // ZSTs don't require any actual memory access.
406 return OperandRef::new_zst(bx.cx, layout);
409 if let Some(o) = self.maybe_codegen_consume_direct(bx, place) {
413 // for most places, to consume them we just load them
414 // out from their home
415 self.codegen_place(bx, place).load(bx)
418 pub fn codegen_operand(&mut self,
419 bx: &Builder<'a, 'll, 'tcx>,
420 operand: &mir::Operand<'tcx>)
421 -> OperandRef<'ll, 'tcx>
423 debug!("codegen_operand(operand={:?})", operand);
426 mir::Operand::Copy(ref place) |
427 mir::Operand::Move(ref place) => {
428 self.codegen_consume(bx, place)
431 mir::Operand::Constant(ref constant) => {
432 let ty = self.monomorphize(&constant.ty);
433 self.eval_mir_constant(bx, constant)
434 .and_then(|c| OperandRef::from_const(bx, c))
435 .unwrap_or_else(|err| {
437 bx.tcx().at(constant.span),
438 "could not evaluate constant operand",
440 // Allow RalfJ to sleep soundly knowing that even refactorings that remove
441 // the above error (or silence it under some conditions) will not cause UB
442 let fnname = bx.cx.get_intrinsic(&("llvm.trap"));
443 bx.call(fnname, &[], None);
444 // We've errored, so we don't have to produce working code.
445 let layout = bx.cx.layout_of(ty);
447 C_undef(layout.llvm_type(bx.cx).ptr_to()),