]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/mir/operand.rs
Implement simple codegen for unsized rvalues.
[rust.git] / src / librustc_codegen_llvm / 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 rustc::mir::interpret::ConstEvalErr;
12 use rustc::mir;
13 use rustc::mir::interpret::{ConstValue, ScalarMaybeUndef};
14 use rustc::ty;
15 use rustc::ty::layout::{self, Align, LayoutOf, TyLayout};
16 use rustc_data_structures::indexed_vec::Idx;
17 use rustc_data_structures::sync::Lrc;
18
19 use base;
20 use common::{CodegenCx, C_undef, C_usize};
21 use builder::{Builder, MemFlags};
22 use value::Value;
23 use type_of::LayoutLlvmExt;
24 use type_::Type;
25 use glue;
26
27 use std::fmt;
28
29 use super::{FunctionCx, LocalRef};
30 use super::constant::scalar_to_llvm;
31 use super::place::PlaceRef;
32
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
35 /// safety check.
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)
49 }
50
51 /// An `OperandRef` is an "SSA" reference to a Rust value, along with
52 /// its type.
53 ///
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`
58 /// instead.
59 #[derive(Copy, Clone)]
60 pub struct OperandRef<'ll, 'tcx> {
61     // The value.
62     pub val: OperandValue<'ll>,
63
64     // The layout of value, based on its Rust type.
65     pub layout: TyLayout<'tcx>,
66 }
67
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)
71     }
72 }
73
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());
78         OperandRef {
79             val: OperandValue::Immediate(C_undef(layout.immediate_llvm_type(cx))),
80             layout
81         }
82     }
83
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);
88
89         if layout.is_zst() {
90             return Ok(OperandRef::new_zst(bx.cx, layout));
91         }
92
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)
99                 };
100                 let llval = scalar_to_llvm(
101                     bx.cx,
102                     x,
103                     scalar,
104                     layout.immediate_llvm_type(bx.cx),
105                 );
106                 OperandValue::Immediate(llval)
107             },
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)
112                 };
113                 let a_llval = scalar_to_llvm(
114                     bx.cx,
115                     a,
116                     a_scalar,
117                     layout.scalar_pair_element_llvm_type(bx.cx, 0, true),
118                 );
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(
122                         bx.cx,
123                         b,
124                         b_scalar,
125                         b_layout,
126                     ),
127                     ScalarMaybeUndef::Undef => C_undef(b_layout),
128                 };
129                 OperandValue::Pair(a_llval, b_llval)
130             },
131             ConstValue::ByRef(alloc, offset) => {
132                 return Ok(PlaceRef::from_const_alloc(bx, layout, alloc, offset).load(bx));
133             },
134         };
135
136         Ok(OperandRef {
137             val,
138             layout
139         })
140     }
141
142     /// Asserts that this operand refers to a scalar and returns
143     /// a reference to its value.
144     pub fn immediate(self) -> &'ll Value {
145         match self.val {
146             OperandValue::Immediate(s) => s,
147             _ => bug!("not immediate: {:?}", self)
148         }
149     }
150
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)
159         };
160         let layout = cx.layout_of(projected_ty);
161         PlaceRef {
162             llval: llptr,
163             llextra,
164             layout,
165             align: layout.align,
166         }
167     }
168
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 {:?}",
175                    self, llty);
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);
180             llpair
181         } else {
182             self.immediate()
183         }
184     }
185
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>,
188                                          llval: &'ll Value,
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 {:?} @ {:?}",
193                     llval, layout);
194
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)
199         } else {
200             OperandValue::Immediate(llval)
201         };
202         OperandRef { val, layout }
203     }
204
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);
208
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);
213             }
214
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);
219                 self.val
220             }
221
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)
227                 } else {
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)
232                 }
233             }
234
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)))
239             }
240
241             _ => bug!("OperandRef::extract_field({:?}): not applicable", self)
242         };
243
244         // HACK(eddyb) have to bitcast pointers until LLVM removes pointee types.
245         match val {
246             OperandValue::Immediate(ref mut llval) => {
247                 *llval = bx.bitcast(*llval, field.immediate_llvm_type(bx.cx));
248             }
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));
252             }
253             OperandValue::Ref(..) |
254             OperandValue::UnsizedRef(..) => bug!()
255         }
256
257         OperandRef {
258             val,
259             layout: field
260         }
261     }
262 }
263
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());
267     }
268
269     pub fn volatile_store(self, bx: &Builder<'a, 'll, 'tcx>, dest: PlaceRef<'ll, 'tcx>) {
270         self.store_with_flags(bx, dest, MemFlags::VOLATILE);
271     }
272
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);
275     }
276
277     pub fn nontemporal_store(self, bx: &Builder<'a, 'll, 'tcx>, dest: PlaceRef<'ll, 'tcx>) {
278         self.store_with_flags(bx, dest, MemFlags::NONTEMPORAL);
279     }
280
281     fn store_with_flags(
282         self,
283         bx: &Builder<'a, 'll, 'tcx>,
284         dest: PlaceRef<'ll, 'tcx>,
285         flags: MemFlags,
286     ) {
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() {
291             return;
292         }
293         match self {
294             OperandValue::Ref(r, source_align) => {
295                 base::memcpy_ty(bx, dest.llval, r, dest.layout,
296                                 source_align.min(dest.align), flags)
297             }
298             OperandValue::UnsizedRef(..) => {
299                 bug!("cannot directly store unsized values");
300             }
301             OperandValue::Immediate(s) => {
302                 let val = base::from_immediate(bx, s);
303                 bx.store_with_flags(val, dest.llval, dest.align, flags);
304             }
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);
310                 }
311             }
312         }
313     }
314
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();
318
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;
322
323         let (llptr, llextra) =
324             if let OperandValue::UnsizedRef(llptr, llextra) = self {
325                 (llptr, llextra)
326             } else {
327                 bug!("store_unsized called with a sized value")
328             };
329
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();
333
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);
338
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);
342     }
343 }
344
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>>
350     {
351         debug!("maybe_codegen_consume_direct(place={:?})", place);
352
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)) => {
358                     return Some(o);
359                 }
360                 LocalRef::Operand(None) => {
361                     bug!("use of {:?} before def", place);
362                 }
363                 LocalRef::Place(..) | LocalRef::UnsizedPlace(..) => {
364                     // use path below
365                 }
366             }
367         }
368
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) {
372                 match proj.elem {
373                     mir::ProjectionElem::Field(ref f, _) => {
374                         return Some(o.extract_field(bx, f.index()));
375                     }
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);
382                         if elem.is_zst() {
383                             return Some(OperandRef::new_zst(bx.cx, elem));
384                         }
385                     }
386                     _ => {}
387                 }
388             }
389         }
390
391         None
392     }
393
394     pub fn codegen_consume(&mut self,
395                          bx: &Builder<'a, 'll, 'tcx>,
396                          place: &mir::Place<'tcx>)
397                          -> OperandRef<'ll, 'tcx>
398     {
399         debug!("codegen_consume(place={:?})", place);
400
401         let ty = self.monomorphized_place_ty(place);
402         let layout = bx.cx.layout_of(ty);
403
404         // ZSTs don't require any actual memory access.
405         if layout.is_zst() {
406             return OperandRef::new_zst(bx.cx, layout);
407         }
408
409         if let Some(o) = self.maybe_codegen_consume_direct(bx, place) {
410             return o;
411         }
412
413         // for most places, to consume them we just load them
414         // out from their home
415         self.codegen_place(bx, place).load(bx)
416     }
417
418     pub fn codegen_operand(&mut self,
419                          bx: &Builder<'a, 'll, 'tcx>,
420                          operand: &mir::Operand<'tcx>)
421                          -> OperandRef<'ll, 'tcx>
422     {
423         debug!("codegen_operand(operand={:?})", operand);
424
425         match *operand {
426             mir::Operand::Copy(ref place) |
427             mir::Operand::Move(ref place) => {
428                 self.codegen_consume(bx, place)
429             }
430
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| {
436                         err.report_as_error(
437                             bx.tcx().at(constant.span),
438                             "could not evaluate constant operand",
439                         );
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);
446                         PlaceRef::new_sized(
447                             C_undef(layout.llvm_type(bx.cx).ptr_to()),
448                             layout,
449                             layout.align,
450                         ).load(bx)
451                     })
452             }
453         }
454     }
455 }