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 llvm::{ValueRef, LLVMConstInBoundsGEP};
12 use rustc::mir::interpret::ConstEvalErr;
14 use rustc::mir::interpret::ConstValue;
16 use rustc::ty::layout::{self, Align, LayoutOf, TyLayout};
17 use rustc_data_structures::indexed_vec::Idx;
18 use rustc_data_structures::sync::Lrc;
21 use common::{CodegenCx, C_null, C_undef, C_usize};
22 use builder::{Builder, MemFlags};
24 use type_of::LayoutLlvmExt;
31 use super::{FunctionCx, LocalRef};
32 use super::constant::{scalar_to_llvm, const_alloc_to_llvm};
33 use super::place::PlaceRef;
35 /// The representation of a Rust value. The enum variant is in fact
36 /// uniquely determined by the value's type, but is kept as a
38 #[derive(Copy, Clone)]
39 pub enum OperandValue {
40 /// A reference to the actual operand. The data is guaranteed
41 /// to be valid for the operand's lifetime.
43 /// A single LLVM value.
45 /// A pair of immediate LLVM values. Used by fat pointers too.
46 Pair(ValueRef, ValueRef)
49 impl fmt::Debug for OperandValue {
50 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
52 OperandValue::Ref(r, align) => {
53 write!(f, "Ref({:?}, {:?})", Value(r), align)
55 OperandValue::Immediate(i) => {
56 write!(f, "Immediate({:?})", Value(i))
58 OperandValue::Pair(a, b) => {
59 write!(f, "Pair({:?}, {:?})", Value(a), Value(b))
65 /// An `OperandRef` is an "SSA" reference to a Rust value, along with
68 /// NOTE: unless you know a value's type exactly, you should not
69 /// generate LLVM opcodes acting on it and instead act via methods,
70 /// to avoid nasty edge cases. In particular, using `Builder::store`
71 /// directly is sure to cause problems -- use `OperandRef::store`
73 #[derive(Copy, Clone)]
74 pub struct OperandRef<'tcx> {
76 pub val: OperandValue,
78 // The layout of value, based on its Rust type.
79 pub layout: TyLayout<'tcx>,
82 impl<'tcx> fmt::Debug for OperandRef<'tcx> {
83 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
84 write!(f, "OperandRef({:?} @ {:?})", self.val, self.layout)
88 impl<'a, 'tcx> OperandRef<'tcx> {
89 pub fn new_zst(cx: &CodegenCx<'a, 'tcx>,
90 layout: TyLayout<'tcx>) -> OperandRef<'tcx> {
91 assert!(layout.is_zst());
93 val: OperandValue::Immediate(C_undef(layout.immediate_llvm_type(cx))),
98 pub fn from_const(bx: &Builder<'a, 'tcx>,
99 val: &'tcx ty::Const<'tcx>)
100 -> Result<OperandRef<'tcx>, Lrc<ConstEvalErr<'tcx>>> {
101 let layout = bx.cx.layout_of(val.ty);
104 return Ok(OperandRef::new_zst(bx.cx, layout));
107 let val = match val.val {
108 ConstValue::Unevaluated(..) => bug!(),
109 ConstValue::Scalar(x) => {
110 let scalar = match layout.abi {
111 layout::Abi::Scalar(ref x) => x,
112 _ => bug!("from_const: invalid ByVal layout: {:#?}", layout)
114 let llval = scalar_to_llvm(
118 layout.immediate_llvm_type(bx.cx),
120 OperandValue::Immediate(llval)
122 ConstValue::ScalarPair(a, b) => {
123 let (a_scalar, b_scalar) = match layout.abi {
124 layout::Abi::ScalarPair(ref a, ref b) => (a, b),
125 _ => bug!("from_const: invalid ScalarPair layout: {:#?}", layout)
127 let a_llval = scalar_to_llvm(
131 layout.scalar_pair_element_llvm_type(bx.cx, 0, true),
133 let b_llval = scalar_to_llvm(
137 layout.scalar_pair_element_llvm_type(bx.cx, 1, true),
139 OperandValue::Pair(a_llval, b_llval)
141 ConstValue::ByRef(alloc, offset) => {
142 let init = const_alloc_to_llvm(bx.cx, alloc);
143 let base_addr = consts::addr_of(bx.cx, init, layout.align, "byte_str");
145 let llval = unsafe { LLVMConstInBoundsGEP(
146 consts::bitcast(base_addr, Type::i8p(bx.cx)),
147 &C_usize(bx.cx, offset.bytes()),
150 let llval = consts::bitcast(llval, layout.llvm_type(bx.cx).ptr_to());
151 return Ok(PlaceRef::new_sized(llval, layout, alloc.align).load(bx));
161 /// Asserts that this operand refers to a scalar and returns
162 /// a reference to its value.
163 pub fn immediate(self) -> ValueRef {
165 OperandValue::Immediate(s) => s,
166 _ => bug!("not immediate: {:?}", self)
170 pub fn deref(self, cx: &CodegenCx<'a, 'tcx>) -> PlaceRef<'tcx> {
171 let projected_ty = self.layout.ty.builtin_deref(true)
172 .unwrap_or_else(|| bug!("deref of non-pointer {:?}", self)).ty;
173 let (llptr, llextra) = match self.val {
174 OperandValue::Immediate(llptr) => (llptr, ptr::null_mut()),
175 OperandValue::Pair(llptr, llextra) => (llptr, llextra),
176 OperandValue::Ref(..) => bug!("Deref of by-Ref operand {:?}", self)
178 let layout = cx.layout_of(projected_ty);
187 /// If this operand is a `Pair`, we return an aggregate with the two values.
188 /// For other cases, see `immediate`.
189 pub fn immediate_or_packed_pair(self, bx: &Builder<'a, 'tcx>) -> ValueRef {
190 if let OperandValue::Pair(a, b) = self.val {
191 let llty = self.layout.llvm_type(bx.cx);
192 debug!("Operand::immediate_or_packed_pair: packing {:?} into {:?}",
194 // Reconstruct the immediate aggregate.
195 let mut llpair = C_undef(llty);
196 llpair = bx.insert_value(llpair, base::from_immediate(bx, a), 0);
197 llpair = bx.insert_value(llpair, base::from_immediate(bx, b), 1);
204 /// If the type is a pair, we return a `Pair`, otherwise, an `Immediate`.
205 pub fn from_immediate_or_packed_pair(bx: &Builder<'a, 'tcx>,
207 layout: TyLayout<'tcx>)
208 -> OperandRef<'tcx> {
209 let val = if let layout::Abi::ScalarPair(ref a, ref b) = layout.abi {
210 debug!("Operand::from_immediate_or_packed_pair: unpacking {:?} @ {:?}",
213 // Deconstruct the immediate aggregate.
214 let a_llval = base::to_immediate_scalar(bx, bx.extract_value(llval, 0), a);
215 let b_llval = base::to_immediate_scalar(bx, bx.extract_value(llval, 1), b);
216 OperandValue::Pair(a_llval, b_llval)
218 OperandValue::Immediate(llval)
220 OperandRef { val, layout }
223 pub fn extract_field(&self, bx: &Builder<'a, 'tcx>, i: usize) -> OperandRef<'tcx> {
224 let field = self.layout.field(bx.cx, i);
225 let offset = self.layout.fields.offset(i);
227 let mut val = match (self.val, &self.layout.abi) {
228 // If the field is ZST, it has no data.
229 _ if field.is_zst() => {
230 return OperandRef::new_zst(bx.cx, field);
233 // Newtype of a scalar, scalar pair or vector.
234 (OperandValue::Immediate(_), _) |
235 (OperandValue::Pair(..), _) if field.size == self.layout.size => {
236 assert_eq!(offset.bytes(), 0);
240 // Extract a scalar component from a pair.
241 (OperandValue::Pair(a_llval, b_llval), &layout::Abi::ScalarPair(ref a, ref b)) => {
242 if offset.bytes() == 0 {
243 assert_eq!(field.size, a.value.size(bx.cx));
244 OperandValue::Immediate(a_llval)
246 assert_eq!(offset, a.value.size(bx.cx)
247 .abi_align(b.value.align(bx.cx)));
248 assert_eq!(field.size, b.value.size(bx.cx));
249 OperandValue::Immediate(b_llval)
253 // `#[repr(simd)]` types are also immediate.
254 (OperandValue::Immediate(llval), &layout::Abi::Vector { .. }) => {
255 OperandValue::Immediate(
256 bx.extract_element(llval, C_usize(bx.cx, i as u64)))
259 _ => bug!("OperandRef::extract_field({:?}): not applicable", self)
262 // HACK(eddyb) have to bitcast pointers until LLVM removes pointee types.
264 OperandValue::Immediate(ref mut llval) => {
265 *llval = bx.bitcast(*llval, field.immediate_llvm_type(bx.cx));
267 OperandValue::Pair(ref mut a, ref mut b) => {
268 *a = bx.bitcast(*a, field.scalar_pair_element_llvm_type(bx.cx, 0, true));
269 *b = bx.bitcast(*b, field.scalar_pair_element_llvm_type(bx.cx, 1, true));
271 OperandValue::Ref(..) => bug!()
281 impl<'a, 'tcx> OperandValue {
282 pub fn store(self, bx: &Builder<'a, 'tcx>, dest: PlaceRef<'tcx>) {
283 self.store_with_flags(bx, dest, MemFlags::empty());
286 pub fn volatile_store(self, bx: &Builder<'a, 'tcx>, dest: PlaceRef<'tcx>) {
287 self.store_with_flags(bx, dest, MemFlags::VOLATILE);
290 pub fn nontemporal_store(self, bx: &Builder<'a, 'tcx>, dest: PlaceRef<'tcx>) {
291 self.store_with_flags(bx, dest, MemFlags::NONTEMPORAL);
294 fn store_with_flags(self, bx: &Builder<'a, 'tcx>, dest: PlaceRef<'tcx>, flags: MemFlags) {
295 debug!("OperandRef::store: operand={:?}, dest={:?}", self, dest);
296 // Avoid generating stores of zero-sized values, because the only way to have a zero-sized
297 // value is through `undef`, and store itself is useless.
298 if dest.layout.is_zst() {
302 OperandValue::Ref(r, source_align) => {
303 base::memcpy_ty(bx, dest.llval, r, dest.layout,
304 source_align.min(dest.align), flags)
306 OperandValue::Immediate(s) => {
307 let val = base::from_immediate(bx, s);
308 bx.store_with_flags(val, dest.llval, dest.align, flags);
310 OperandValue::Pair(a, b) => {
311 for (i, &x) in [a, b].iter().enumerate() {
312 let llptr = bx.struct_gep(dest.llval, i as u64);
313 let val = base::from_immediate(bx, x);
314 bx.store_with_flags(val, llptr, dest.align, flags);
321 impl<'a, 'tcx> FunctionCx<'a, 'tcx> {
322 fn maybe_codegen_consume_direct(&mut self,
323 bx: &Builder<'a, 'tcx>,
324 place: &mir::Place<'tcx>)
325 -> Option<OperandRef<'tcx>>
327 debug!("maybe_codegen_consume_direct(place={:?})", place);
329 // watch out for locals that do not have an
330 // alloca; they are handled somewhat differently
331 if let mir::Place::Local(index) = *place {
332 match self.locals[index] {
333 LocalRef::Operand(Some(o)) => {
336 LocalRef::Operand(None) => {
337 bug!("use of {:?} before def", place);
339 LocalRef::Place(..) => {
345 // Moves out of scalar and scalar pair fields are trivial.
346 if let &mir::Place::Projection(ref proj) = place {
347 if let Some(o) = self.maybe_codegen_consume_direct(bx, &proj.base) {
349 mir::ProjectionElem::Field(ref f, _) => {
350 return Some(o.extract_field(bx, f.index()));
352 mir::ProjectionElem::Index(_) |
353 mir::ProjectionElem::ConstantIndex { .. } => {
354 // ZSTs don't require any actual memory access.
355 // FIXME(eddyb) deduplicate this with the identical
356 // checks in `codegen_consume` and `extract_field`.
357 let elem = o.layout.field(bx.cx, 0);
359 return Some(OperandRef::new_zst(bx.cx, elem));
370 pub fn codegen_consume(&mut self,
371 bx: &Builder<'a, 'tcx>,
372 place: &mir::Place<'tcx>)
375 debug!("codegen_consume(place={:?})", place);
377 let ty = self.monomorphized_place_ty(place);
378 let layout = bx.cx.layout_of(ty);
380 // ZSTs don't require any actual memory access.
382 return OperandRef::new_zst(bx.cx, layout);
385 if let Some(o) = self.maybe_codegen_consume_direct(bx, place) {
389 // for most places, to consume them we just load them
390 // out from their home
391 self.codegen_place(bx, place).load(bx)
394 pub fn codegen_operand(&mut self,
395 bx: &Builder<'a, 'tcx>,
396 operand: &mir::Operand<'tcx>)
399 debug!("codegen_operand(operand={:?})", operand);
402 mir::Operand::Copy(ref place) |
403 mir::Operand::Move(ref place) => {
404 self.codegen_consume(bx, place)
407 mir::Operand::Constant(ref constant) => {
408 let ty = self.monomorphize(&constant.ty);
409 self.eval_mir_constant(bx, constant)
410 .and_then(|c| OperandRef::from_const(bx, c))
411 .unwrap_or_else(|err| {
412 match constant.literal {
413 mir::Literal::Promoted { .. } => {
414 // FIXME: generate a panic here
416 mir::Literal::Value { .. } => {
418 bx.tcx().at(constant.span),
419 "could not evaluate constant operand",
423 // We've errored, so we don't have to produce working code.
424 let layout = bx.cx.layout_of(ty);
426 C_null(layout.llvm_type(bx.cx).ptr_to()),