]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/mir/operand.rs
Auto merge of #47804 - retep007:recursive-requirements, r=pnkfelix
[rust.git] / src / librustc_trans / mir / operand.rs
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.
4 //
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.
10
11 use llvm::ValueRef;
12 use rustc::ty::layout::{self, Align, LayoutOf, TyLayout};
13 use rustc::mir;
14 use rustc_data_structures::indexed_vec::Idx;
15
16 use base;
17 use common::{self, CodegenCx, C_undef, C_usize};
18 use builder::Builder;
19 use value::Value;
20 use type_of::LayoutLlvmExt;
21 use type_::Type;
22
23 use std::fmt;
24 use std::ptr;
25
26 use super::{FunctionCx, LocalRef};
27 use super::place::PlaceRef;
28
29 /// The representation of a Rust value. The enum variant is in fact
30 /// uniquely determined by the value's type, but is kept as a
31 /// safety check.
32 #[derive(Copy, Clone)]
33 pub enum OperandValue {
34     /// A reference to the actual operand. The data is guaranteed
35     /// to be valid for the operand's lifetime.
36     Ref(ValueRef, Align),
37     /// A single LLVM value.
38     Immediate(ValueRef),
39     /// A pair of immediate LLVM values. Used by fat pointers too.
40     Pair(ValueRef, ValueRef)
41 }
42
43 impl fmt::Debug for OperandValue {
44     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
45         match *self {
46             OperandValue::Ref(r, align) => {
47                 write!(f, "Ref({:?}, {:?})", Value(r), align)
48             }
49             OperandValue::Immediate(i) => {
50                 write!(f, "Immediate({:?})", Value(i))
51             }
52             OperandValue::Pair(a, b) => {
53                 write!(f, "Pair({:?}, {:?})", Value(a), Value(b))
54             }
55         }
56     }
57 }
58
59 /// An `OperandRef` is an "SSA" reference to a Rust value, along with
60 /// its type.
61 ///
62 /// NOTE: unless you know a value's type exactly, you should not
63 /// generate LLVM opcodes acting on it and instead act via methods,
64 /// to avoid nasty edge cases. In particular, using `Builder::store`
65 /// directly is sure to cause problems -- use `OperandRef::store`
66 /// instead.
67 #[derive(Copy, Clone)]
68 pub struct OperandRef<'tcx> {
69     // The value.
70     pub val: OperandValue,
71
72     // The layout of value, based on its Rust type.
73     pub layout: TyLayout<'tcx>,
74 }
75
76 impl<'tcx> fmt::Debug for OperandRef<'tcx> {
77     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
78         write!(f, "OperandRef({:?} @ {:?})", self.val, self.layout)
79     }
80 }
81
82 impl<'a, 'tcx> OperandRef<'tcx> {
83     pub fn new_zst(cx: &CodegenCx<'a, 'tcx>,
84                    layout: TyLayout<'tcx>) -> OperandRef<'tcx> {
85         assert!(layout.is_zst());
86         OperandRef {
87             val: OperandValue::Immediate(C_undef(layout.immediate_llvm_type(cx))),
88             layout
89         }
90     }
91
92     /// Asserts that this operand refers to a scalar and returns
93     /// a reference to its value.
94     pub fn immediate(self) -> ValueRef {
95         match self.val {
96             OperandValue::Immediate(s) => s,
97             _ => bug!("not immediate: {:?}", self)
98         }
99     }
100
101     pub fn deref(self, cx: &CodegenCx<'a, 'tcx>) -> PlaceRef<'tcx> {
102         let projected_ty = self.layout.ty.builtin_deref(true)
103             .unwrap_or_else(|| bug!("deref of non-pointer {:?}", self)).ty;
104         let (llptr, llextra) = match self.val {
105             OperandValue::Immediate(llptr) => (llptr, ptr::null_mut()),
106             OperandValue::Pair(llptr, llextra) => (llptr, llextra),
107             OperandValue::Ref(..) => bug!("Deref of by-Ref operand {:?}", self)
108         };
109         let layout = cx.layout_of(projected_ty);
110         PlaceRef {
111             llval: llptr,
112             llextra,
113             layout,
114             align: layout.align,
115         }
116     }
117
118     /// If this operand is a `Pair`, we return an aggregate with the two values.
119     /// For other cases, see `immediate`.
120     pub fn immediate_or_packed_pair(self, bx: &Builder<'a, 'tcx>) -> ValueRef {
121         if let OperandValue::Pair(a, b) = self.val {
122             let llty = self.layout.llvm_type(bx.cx);
123             debug!("Operand::immediate_or_packed_pair: packing {:?} into {:?}",
124                    self, llty);
125             // Reconstruct the immediate aggregate.
126             let mut llpair = C_undef(llty);
127             llpair = bx.insert_value(llpair, a, 0);
128             llpair = bx.insert_value(llpair, b, 1);
129             llpair
130         } else {
131             self.immediate()
132         }
133     }
134
135     /// If the type is a pair, we return a `Pair`, otherwise, an `Immediate`.
136     pub fn from_immediate_or_packed_pair(bx: &Builder<'a, 'tcx>,
137                                          llval: ValueRef,
138                                          layout: TyLayout<'tcx>)
139                                          -> OperandRef<'tcx> {
140         let val = if layout.is_llvm_scalar_pair() {
141             debug!("Operand::from_immediate_or_packed_pair: unpacking {:?} @ {:?}",
142                     llval, layout);
143
144             // Deconstruct the immediate aggregate.
145             OperandValue::Pair(bx.extract_value(llval, 0),
146                                bx.extract_value(llval, 1))
147         } else {
148             OperandValue::Immediate(llval)
149         };
150         OperandRef { val, layout }
151     }
152
153     pub fn extract_field(&self, bx: &Builder<'a, 'tcx>, i: usize) -> OperandRef<'tcx> {
154         let field = self.layout.field(bx.cx, i);
155         let offset = self.layout.fields.offset(i);
156
157         let mut val = match (self.val, &self.layout.abi) {
158             // If we're uninhabited, or the field is ZST, it has no data.
159             _ if self.layout.abi == layout::Abi::Uninhabited || field.is_zst() => {
160                 return OperandRef {
161                     val: OperandValue::Immediate(C_undef(field.immediate_llvm_type(bx.cx))),
162                     layout: field
163                 };
164             }
165
166             // Newtype of a scalar, scalar pair or vector.
167             (OperandValue::Immediate(_), _) |
168             (OperandValue::Pair(..), _) if field.size == self.layout.size => {
169                 assert_eq!(offset.bytes(), 0);
170                 self.val
171             }
172
173             // Extract a scalar component from a pair.
174             (OperandValue::Pair(a_llval, b_llval), &layout::Abi::ScalarPair(ref a, ref b)) => {
175                 if offset.bytes() == 0 {
176                     assert_eq!(field.size, a.value.size(bx.cx));
177                     OperandValue::Immediate(a_llval)
178                 } else {
179                     assert_eq!(offset, a.value.size(bx.cx)
180                         .abi_align(b.value.align(bx.cx)));
181                     assert_eq!(field.size, b.value.size(bx.cx));
182                     OperandValue::Immediate(b_llval)
183                 }
184             }
185
186             // `#[repr(simd)]` types are also immediate.
187             (OperandValue::Immediate(llval), &layout::Abi::Vector { .. }) => {
188                 OperandValue::Immediate(
189                     bx.extract_element(llval, C_usize(bx.cx, i as u64)))
190             }
191
192             _ => bug!("OperandRef::extract_field({:?}): not applicable", self)
193         };
194
195         // HACK(eddyb) have to bitcast pointers until LLVM removes pointee types.
196         match val {
197             OperandValue::Immediate(ref mut llval) => {
198                 *llval = bx.bitcast(*llval, field.immediate_llvm_type(bx.cx));
199             }
200             OperandValue::Pair(ref mut a, ref mut b) => {
201                 *a = bx.bitcast(*a, field.scalar_pair_element_llvm_type(bx.cx, 0));
202                 *b = bx.bitcast(*b, field.scalar_pair_element_llvm_type(bx.cx, 1));
203             }
204             OperandValue::Ref(..) => bug!()
205         }
206
207         OperandRef {
208             val,
209             layout: field
210         }
211     }
212 }
213
214 impl<'a, 'tcx> OperandValue {
215     pub fn store(self, bx: &Builder<'a, 'tcx>, dest: PlaceRef<'tcx>) {
216         debug!("OperandRef::store: operand={:?}, dest={:?}", self, dest);
217         // Avoid generating stores of zero-sized values, because the only way to have a zero-sized
218         // value is through `undef`, and store itself is useless.
219         if dest.layout.is_zst() {
220             return;
221         }
222         match self {
223             OperandValue::Ref(r, source_align) =>
224                 base::memcpy_ty(bx, dest.llval, r, dest.layout,
225                                 source_align.min(dest.align)),
226             OperandValue::Immediate(s) => {
227                 bx.store(base::from_immediate(bx, s), dest.llval, dest.align);
228             }
229             OperandValue::Pair(a, b) => {
230                 for (i, &x) in [a, b].iter().enumerate() {
231                     let mut llptr = bx.struct_gep(dest.llval, i as u64);
232                     // Make sure to always store i1 as i8.
233                     if common::val_ty(x) == Type::i1(bx.cx) {
234                         llptr = bx.pointercast(llptr, Type::i8p(bx.cx));
235                     }
236                     bx.store(base::from_immediate(bx, x), llptr, dest.align);
237                 }
238             }
239         }
240     }
241 }
242
243 impl<'a, 'tcx> FunctionCx<'a, 'tcx> {
244     fn maybe_trans_consume_direct(&mut self,
245                                   bx: &Builder<'a, 'tcx>,
246                                   place: &mir::Place<'tcx>)
247                                    -> Option<OperandRef<'tcx>>
248     {
249         debug!("maybe_trans_consume_direct(place={:?})", place);
250
251         // watch out for locals that do not have an
252         // alloca; they are handled somewhat differently
253         if let mir::Place::Local(index) = *place {
254             match self.locals[index] {
255                 LocalRef::Operand(Some(o)) => {
256                     return Some(o);
257                 }
258                 LocalRef::Operand(None) => {
259                     bug!("use of {:?} before def", place);
260                 }
261                 LocalRef::Place(..) => {
262                     // use path below
263                 }
264             }
265         }
266
267         // Moves out of scalar and scalar pair fields are trivial.
268         if let &mir::Place::Projection(ref proj) = place {
269             if let Some(o) = self.maybe_trans_consume_direct(bx, &proj.base) {
270                 match proj.elem {
271                     mir::ProjectionElem::Field(ref f, _) => {
272                         return Some(o.extract_field(bx, f.index()));
273                     }
274                     mir::ProjectionElem::Index(_) |
275                     mir::ProjectionElem::ConstantIndex { .. } => {
276                         // ZSTs don't require any actual memory access.
277                         // FIXME(eddyb) deduplicate this with the identical
278                         // checks in `trans_consume` and `extract_field`.
279                         let elem = o.layout.field(bx.cx, 0);
280                         if elem.is_zst() {
281                             return Some(OperandRef::new_zst(bx.cx, elem));
282                         }
283                     }
284                     _ => {}
285                 }
286             }
287         }
288
289         None
290     }
291
292     pub fn trans_consume(&mut self,
293                          bx: &Builder<'a, 'tcx>,
294                          place: &mir::Place<'tcx>)
295                          -> OperandRef<'tcx>
296     {
297         debug!("trans_consume(place={:?})", place);
298
299         let ty = self.monomorphized_place_ty(place);
300         let layout = bx.cx.layout_of(ty);
301
302         // ZSTs don't require any actual memory access.
303         if layout.is_zst() {
304             return OperandRef::new_zst(bx.cx, layout);
305         }
306
307         if let Some(o) = self.maybe_trans_consume_direct(bx, place) {
308             return o;
309         }
310
311         // for most places, to consume them we just load them
312         // out from their home
313         self.trans_place(bx, place).load(bx)
314     }
315
316     pub fn trans_operand(&mut self,
317                          bx: &Builder<'a, 'tcx>,
318                          operand: &mir::Operand<'tcx>)
319                          -> OperandRef<'tcx>
320     {
321         debug!("trans_operand(operand={:?})", operand);
322
323         match *operand {
324             mir::Operand::Copy(ref place) |
325             mir::Operand::Move(ref place) => {
326                 self.trans_consume(bx, place)
327             }
328
329             mir::Operand::Constant(ref constant) => {
330                 let val = self.trans_constant(&bx, constant);
331                 let operand = val.to_operand(bx.cx);
332                 if let OperandValue::Ref(ptr, align) = operand.val {
333                     // If this is a OperandValue::Ref to an immediate constant, load it.
334                     PlaceRef::new_sized(ptr, operand.layout, align).load(bx)
335                 } else {
336                     operand
337                 }
338             }
339         }
340     }
341 }