]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/mir/operand.rs
771a88238b2b73a66cbcdb319bebbf97e9ce5c98
[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::{self, Ty};
13 use rustc::ty::layout::{Layout, LayoutTyper};
14 use rustc::mir;
15 use rustc::mir::tcx::LvalueTy;
16 use rustc_data_structures::indexed_vec::Idx;
17
18 use base;
19 use common;
20 use builder::Builder;
21 use value::Value;
22 use type_of;
23 use type_::Type;
24
25 use std::fmt;
26 use std::ptr;
27
28 use super::{MirContext, LocalRef};
29 use super::lvalue::{Alignment, LvalueRef};
30
31 /// The representation of a Rust value. The enum variant is in fact
32 /// uniquely determined by the value's type, but is kept as a
33 /// safety check.
34 #[derive(Copy, Clone)]
35 pub enum OperandValue {
36     /// A reference to the actual operand. The data is guaranteed
37     /// to be valid for the operand's lifetime.
38     Ref(ValueRef, Alignment),
39     /// A single LLVM value.
40     Immediate(ValueRef),
41     /// A pair of immediate LLVM values. Used by fat pointers too.
42     Pair(ValueRef, ValueRef)
43 }
44
45 /// An `OperandRef` is an "SSA" reference to a Rust value, along with
46 /// its type.
47 ///
48 /// NOTE: unless you know a value's type exactly, you should not
49 /// generate LLVM opcodes acting on it and instead act via methods,
50 /// to avoid nasty edge cases. In particular, using `Builder.store`
51 /// directly is sure to cause problems -- use `MirContext.store_operand`
52 /// instead.
53 #[derive(Copy, Clone)]
54 pub struct OperandRef<'tcx> {
55     // The value.
56     pub val: OperandValue,
57
58     // The type of value being returned.
59     pub ty: Ty<'tcx>
60 }
61
62 impl<'tcx> fmt::Debug for OperandRef<'tcx> {
63     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
64         match self.val {
65             OperandValue::Ref(r, align) => {
66                 write!(f, "OperandRef(Ref({:?}, {:?}) @ {:?})",
67                        Value(r), align, self.ty)
68             }
69             OperandValue::Immediate(i) => {
70                 write!(f, "OperandRef(Immediate({:?}) @ {:?})",
71                        Value(i), self.ty)
72             }
73             OperandValue::Pair(a, b) => {
74                 write!(f, "OperandRef(Pair({:?}, {:?}) @ {:?})",
75                        Value(a), Value(b), self.ty)
76             }
77         }
78     }
79 }
80
81 impl<'a, 'tcx> OperandRef<'tcx> {
82     /// Asserts that this operand refers to a scalar and returns
83     /// a reference to its value.
84     pub fn immediate(self) -> ValueRef {
85         match self.val {
86             OperandValue::Immediate(s) => s,
87             _ => bug!("not immediate: {:?}", self)
88         }
89     }
90
91     pub fn deref(self) -> LvalueRef<'tcx> {
92         let projected_ty = self.ty.builtin_deref(true, ty::NoPreference)
93             .unwrap().ty;
94         let (llptr, llextra) = match self.val {
95             OperandValue::Immediate(llptr) => (llptr, ptr::null_mut()),
96             OperandValue::Pair(llptr, llextra) => (llptr, llextra),
97             OperandValue::Ref(..) => bug!("Deref of by-Ref operand {:?}", self)
98         };
99         LvalueRef {
100             llval: llptr,
101             llextra: llextra,
102             ty: LvalueTy::from_ty(projected_ty),
103             alignment: Alignment::AbiAligned,
104         }
105     }
106
107     /// If this operand is a Pair, we return an
108     /// Immediate aggregate with the two values.
109     pub fn pack_if_pair(mut self, bcx: &Builder<'a, 'tcx>) -> OperandRef<'tcx> {
110         if let OperandValue::Pair(a, b) = self.val {
111             // Reconstruct the immediate aggregate.
112             let llty = type_of::type_of(bcx.ccx, self.ty);
113             let mut llpair = common::C_undef(llty);
114             let elems = [a, b];
115             for i in 0..2 {
116                 let mut elem = elems[i];
117                 // Extend boolean i1's to i8.
118                 if common::val_ty(elem) == Type::i1(bcx.ccx) {
119                     elem = bcx.zext(elem, Type::i8(bcx.ccx));
120                 }
121                 llpair = bcx.insert_value(llpair, elem, i);
122             }
123             self.val = OperandValue::Immediate(llpair);
124         }
125         self
126     }
127
128     /// If this operand is a pair in an Immediate,
129     /// we return a Pair with the two halves.
130     pub fn unpack_if_pair(mut self, bcx: &Builder<'a, 'tcx>) -> OperandRef<'tcx> {
131         if let OperandValue::Immediate(llval) = self.val {
132             // Deconstruct the immediate aggregate.
133             if common::type_is_imm_pair(bcx.ccx, self.ty) {
134                 debug!("Operand::unpack_if_pair: unpacking {:?}", self);
135
136                 let mut a = bcx.extract_value(llval, 0);
137                 let mut b = bcx.extract_value(llval, 1);
138
139                 let pair_fields = common::type_pair_fields(bcx.ccx, self.ty);
140                 if let Some([a_ty, b_ty]) = pair_fields {
141                     if a_ty.is_bool() {
142                         a = bcx.trunc(a, Type::i1(bcx.ccx));
143                     }
144                     if b_ty.is_bool() {
145                         b = bcx.trunc(b, Type::i1(bcx.ccx));
146                     }
147                 }
148
149                 self.val = OperandValue::Pair(a, b);
150             }
151         }
152         self
153     }
154 }
155
156 impl<'a, 'tcx> MirContext<'a, 'tcx> {
157     pub fn trans_load(&mut self,
158                       bcx: &Builder<'a, 'tcx>,
159                       llval: ValueRef,
160                       align: Alignment,
161                       ty: Ty<'tcx>)
162                       -> OperandRef<'tcx>
163     {
164         debug!("trans_load: {:?} @ {:?}", Value(llval), ty);
165
166         let val = if common::type_is_fat_ptr(bcx.ccx, ty) {
167             let (lldata, llextra) = base::load_fat_ptr(bcx, llval, align, ty);
168             OperandValue::Pair(lldata, llextra)
169         } else if common::type_is_imm_pair(bcx.ccx, ty) {
170             let f_align = match *bcx.ccx.layout_of(ty) {
171                 Layout::Univariant { ref variant, .. } =>
172                     Alignment::from_packed(variant.packed) | align,
173                 _ => align
174             };
175             let [a_ty, b_ty] = common::type_pair_fields(bcx.ccx, ty).unwrap();
176             let a_ptr = bcx.struct_gep(llval, 0);
177             let b_ptr = bcx.struct_gep(llval, 1);
178
179             OperandValue::Pair(
180                 base::load_ty(bcx, a_ptr, f_align, a_ty),
181                 base::load_ty(bcx, b_ptr, f_align, b_ty)
182             )
183         } else if common::type_is_immediate(bcx.ccx, ty) {
184             OperandValue::Immediate(base::load_ty(bcx, llval, align, ty))
185         } else {
186             OperandValue::Ref(llval, align)
187         };
188
189         OperandRef { val: val, ty: ty }
190     }
191
192     pub fn trans_consume(&mut self,
193                          bcx: &Builder<'a, 'tcx>,
194                          lvalue: &mir::Lvalue<'tcx>)
195                          -> OperandRef<'tcx>
196     {
197         debug!("trans_consume(lvalue={:?})", lvalue);
198
199         // watch out for locals that do not have an
200         // alloca; they are handled somewhat differently
201         if let mir::Lvalue::Local(index) = *lvalue {
202             match self.locals[index] {
203                 LocalRef::Operand(Some(o)) => {
204                     return o;
205                 }
206                 LocalRef::Operand(None) => {
207                     bug!("use of {:?} before def", lvalue);
208                 }
209                 LocalRef::Lvalue(..) => {
210                     // use path below
211                 }
212             }
213         }
214
215         // Moves out of pair fields are trivial.
216         if let &mir::Lvalue::Projection(ref proj) = lvalue {
217             if let mir::Lvalue::Local(index) = proj.base {
218                 if let LocalRef::Operand(Some(o)) = self.locals[index] {
219                     match (o.val, &proj.elem) {
220                         (OperandValue::Pair(a, b),
221                          &mir::ProjectionElem::Field(ref f, ty)) => {
222                             let llval = [a, b][f.index()];
223                             let op = OperandRef {
224                                 val: OperandValue::Immediate(llval),
225                                 ty: self.monomorphize(&ty)
226                             };
227
228                             // Handle nested pairs.
229                             return op.unpack_if_pair(bcx);
230                         }
231                         _ => {}
232                     }
233                 }
234             }
235         }
236
237         // for most lvalues, to consume them we just load them
238         // out from their home
239         let tr_lvalue = self.trans_lvalue(bcx, lvalue);
240         let ty = tr_lvalue.ty.to_ty(bcx.tcx());
241         self.trans_load(bcx, tr_lvalue.llval, tr_lvalue.alignment, ty)
242     }
243
244     pub fn trans_operand(&mut self,
245                          bcx: &Builder<'a, 'tcx>,
246                          operand: &mir::Operand<'tcx>)
247                          -> OperandRef<'tcx>
248     {
249         debug!("trans_operand(operand={:?})", operand);
250
251         match *operand {
252             mir::Operand::Consume(ref lvalue) => {
253                 self.trans_consume(bcx, lvalue)
254             }
255
256             mir::Operand::Constant(ref constant) => {
257                 let val = self.trans_constant(&bcx, constant);
258                 let operand = val.to_operand(bcx.ccx);
259                 if let OperandValue::Ref(ptr, align) = operand.val {
260                     // If this is a OperandValue::Ref to an immediate constant, load it.
261                     self.trans_load(bcx, ptr, align, operand.ty)
262                 } else {
263                     operand
264                 }
265             }
266         }
267     }
268
269     pub fn store_operand(&mut self,
270                          bcx: &Builder<'a, 'tcx>,
271                          lldest: ValueRef,
272                          align: Option<u32>,
273                          operand: OperandRef<'tcx>) {
274         debug!("store_operand: operand={:?}, align={:?}", operand, align);
275         // Avoid generating stores of zero-sized values, because the only way to have a zero-sized
276         // value is through `undef`, and store itself is useless.
277         if common::type_is_zero_size(bcx.ccx, operand.ty) {
278             return;
279         }
280         match operand.val {
281             OperandValue::Ref(r, Alignment::Packed) =>
282                 base::memcpy_ty(bcx, lldest, r, operand.ty, Some(1)),
283             OperandValue::Ref(r, Alignment::AbiAligned) =>
284                 base::memcpy_ty(bcx, lldest, r, operand.ty, align),
285             OperandValue::Immediate(s) => {
286                 bcx.store(base::from_immediate(bcx, s), lldest, align);
287             }
288             OperandValue::Pair(a, b) => {
289                 let f_align = match *bcx.ccx.layout_of(operand.ty) {
290                     Layout::Univariant { ref variant, .. } if variant.packed => {
291                         Some(1)
292                     }
293                     _ => align
294                 };
295
296                 let a = base::from_immediate(bcx, a);
297                 let b = base::from_immediate(bcx, b);
298                 bcx.store(a, bcx.struct_gep(lldest, 0), f_align);
299                 bcx.store(b, bcx.struct_gep(lldest, 1), f_align);
300             }
301         }
302     }
303 }