]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/mir/operand.rs
Generalized base.rs#call_memcpy and everything that it uses
[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::{ConstValue, ErrorHandled};
12 use rustc::mir;
13 use rustc::ty;
14 use rustc::ty::layout::{self, Align, LayoutOf, TyLayout};
15
16 use base;
17 use common::{CodegenCx, C_undef, C_usize};
18 use builder::{Builder, MemFlags};
19 use value::{Value, ValueTrait};
20 use type_of::LayoutLlvmExt;
21 use type_::Type;
22 use glue;
23
24 use traits::BuilderMethods;
25
26 use std::fmt;
27
28 use super::{FunctionCx, LocalRef};
29 use super::constant::scalar_to_llvm;
30 use super::place::PlaceRef;
31
32 /// The representation of a Rust value. The enum variant is in fact
33 /// uniquely determined by the value's type, but is kept as a
34 /// safety check.
35 #[derive(Copy, Clone, Debug)]
36 pub enum OperandValue<V> {
37     /// A reference to the actual operand. The data is guaranteed
38     /// to be valid for the operand's lifetime.
39     /// The second value, if any, is the extra data (vtable or length)
40     /// which indicates that it refers to an unsized rvalue.
41     Ref(V, Option<V>, Align),
42     /// A single LLVM value.
43     Immediate(V),
44     /// A pair of immediate LLVM values. Used by fat pointers too.
45     Pair(V, V)
46 }
47
48 /// An `OperandRef` is an "SSA" reference to a Rust value, along with
49 /// its type.
50 ///
51 /// NOTE: unless you know a value's type exactly, you should not
52 /// generate LLVM opcodes acting on it and instead act via methods,
53 /// to avoid nasty edge cases. In particular, using `Builder::store`
54 /// directly is sure to cause problems -- use `OperandRef::store`
55 /// instead.
56 #[derive(Copy, Clone)]
57 pub struct OperandRef<'tcx, V> {
58     // The value.
59     pub val: OperandValue<V>,
60
61     // The layout of value, based on its Rust type.
62     pub layout: TyLayout<'tcx>,
63 }
64
65 impl<Value: ?Sized> fmt::Debug for OperandRef<'tcx, &'ll Value> where Value: ValueTrait {
66     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
67         write!(f, "OperandRef({:?} @ {:?})", self.val, self.layout)
68     }
69 }
70
71 impl OperandRef<'tcx, &'ll Value> {
72     pub fn new_zst(cx: &CodegenCx<'ll, 'tcx>,
73                    layout: TyLayout<'tcx>) -> OperandRef<'tcx, &'ll Value> {
74         assert!(layout.is_zst());
75         OperandRef {
76             val: OperandValue::Immediate(C_undef(layout.immediate_llvm_type(cx))),
77             layout
78         }
79     }
80
81     pub fn from_const(bx: &Builder<'a, 'll, 'tcx>,
82                       val: &'tcx ty::Const<'tcx>)
83                       -> Result<OperandRef<'tcx, &'ll Value>, ErrorHandled> {
84         let layout = bx.cx.layout_of(val.ty);
85
86         if layout.is_zst() {
87             return Ok(OperandRef::new_zst(bx.cx, layout));
88         }
89
90         let val = match val.val {
91             ConstValue::Unevaluated(..) => bug!(),
92             ConstValue::Scalar(x) => {
93                 let scalar = match layout.abi {
94                     layout::Abi::Scalar(ref x) => x,
95                     _ => bug!("from_const: invalid ByVal layout: {:#?}", layout)
96                 };
97                 let llval = scalar_to_llvm(
98                     bx.cx,
99                     x,
100                     scalar,
101                     layout.immediate_llvm_type(bx.cx),
102                 );
103                 OperandValue::Immediate(llval)
104             },
105             ConstValue::ScalarPair(a, b) => {
106                 let (a_scalar, b_scalar) = match layout.abi {
107                     layout::Abi::ScalarPair(ref a, ref b) => (a, b),
108                     _ => bug!("from_const: invalid ScalarPair layout: {:#?}", layout)
109                 };
110                 let a_llval = scalar_to_llvm(
111                     bx.cx,
112                     a,
113                     a_scalar,
114                     layout.scalar_pair_element_llvm_type(bx.cx, 0, true),
115                 );
116                 let b_layout = layout.scalar_pair_element_llvm_type(bx.cx, 1, true);
117                 let b_llval = scalar_to_llvm(
118                     bx.cx,
119                     b,
120                     b_scalar,
121                     b_layout,
122                 );
123                 OperandValue::Pair(a_llval, b_llval)
124             },
125             ConstValue::ByRef(_, alloc, offset) => {
126                 return Ok(PlaceRef::from_const_alloc(bx, layout, alloc, offset).load(bx));
127             },
128         };
129
130         Ok(OperandRef {
131             val,
132             layout
133         })
134     }
135
136     /// Asserts that this operand refers to a scalar and returns
137     /// a reference to its value.
138     pub fn immediate(self) -> &'ll Value {
139         match self.val {
140             OperandValue::Immediate(s) => s,
141             _ => bug!("not immediate: {:?}", self)
142         }
143     }
144
145     pub fn deref(self, cx: &CodegenCx<'ll, 'tcx>) -> PlaceRef<'tcx, &'ll Value> {
146         let projected_ty = self.layout.ty.builtin_deref(true)
147             .unwrap_or_else(|| bug!("deref of non-pointer {:?}", self)).ty;
148         let (llptr, llextra) = match self.val {
149             OperandValue::Immediate(llptr) => (llptr, None),
150             OperandValue::Pair(llptr, llextra) => (llptr, Some(llextra)),
151             OperandValue::Ref(..) => bug!("Deref of by-Ref operand {:?}", self)
152         };
153         let layout = cx.layout_of(projected_ty);
154         PlaceRef {
155             llval: llptr,
156             llextra,
157             layout,
158             align: layout.align,
159         }
160     }
161
162     /// If this operand is a `Pair`, we return an aggregate with the two values.
163     /// For other cases, see `immediate`.
164     pub fn immediate_or_packed_pair(self, bx: &Builder<'a, 'll, 'tcx>) -> &'ll Value {
165         if let OperandValue::Pair(a, b) = self.val {
166             let llty = self.layout.llvm_type(bx.cx);
167             debug!("Operand::immediate_or_packed_pair: packing {:?} into {:?}",
168                    self, llty);
169             // Reconstruct the immediate aggregate.
170             let mut llpair = C_undef(llty);
171             llpair = bx.insert_value(llpair, base::from_immediate(bx, a), 0);
172             llpair = bx.insert_value(llpair, base::from_immediate(bx, b), 1);
173             llpair
174         } else {
175             self.immediate()
176         }
177     }
178
179     /// If the type is a pair, we return a `Pair`, otherwise, an `Immediate`.
180     pub fn from_immediate_or_packed_pair(bx: &Builder<'a, 'll, 'tcx>,
181                                          llval: &'ll Value,
182                                          layout: TyLayout<'tcx>)
183                                          -> OperandRef<'tcx, &'ll Value> {
184         let val = if let layout::Abi::ScalarPair(ref a, ref b) = layout.abi {
185             debug!("Operand::from_immediate_or_packed_pair: unpacking {:?} @ {:?}",
186                     llval, layout);
187
188             // Deconstruct the immediate aggregate.
189             let a_llval = base::to_immediate_scalar(bx, bx.extract_value(llval, 0), a);
190             let b_llval = base::to_immediate_scalar(bx, bx.extract_value(llval, 1), b);
191             OperandValue::Pair(a_llval, b_llval)
192         } else {
193             OperandValue::Immediate(llval)
194         };
195         OperandRef { val, layout }
196     }
197
198     pub fn extract_field(
199         &self,
200         bx: &Builder<'a, 'll, 'tcx>,
201         i: usize,
202     ) -> OperandRef<'tcx, &'ll Value> {
203         let field = self.layout.field(bx.cx, i);
204         let offset = self.layout.fields.offset(i);
205
206         let mut val = match (self.val, &self.layout.abi) {
207             // If the field is ZST, it has no data.
208             _ if field.is_zst() => {
209                 return OperandRef::new_zst(bx.cx, field);
210             }
211
212             // Newtype of a scalar, scalar pair or vector.
213             (OperandValue::Immediate(_), _) |
214             (OperandValue::Pair(..), _) if field.size == self.layout.size => {
215                 assert_eq!(offset.bytes(), 0);
216                 self.val
217             }
218
219             // Extract a scalar component from a pair.
220             (OperandValue::Pair(a_llval, b_llval), &layout::Abi::ScalarPair(ref a, ref b)) => {
221                 if offset.bytes() == 0 {
222                     assert_eq!(field.size, a.value.size(bx.cx));
223                     OperandValue::Immediate(a_llval)
224                 } else {
225                     assert_eq!(offset, a.value.size(bx.cx)
226                         .abi_align(b.value.align(bx.cx)));
227                     assert_eq!(field.size, b.value.size(bx.cx));
228                     OperandValue::Immediate(b_llval)
229                 }
230             }
231
232             // `#[repr(simd)]` types are also immediate.
233             (OperandValue::Immediate(llval), &layout::Abi::Vector { .. }) => {
234                 OperandValue::Immediate(
235                     bx.extract_element(llval, C_usize(bx.cx, i as u64)))
236             }
237
238             _ => bug!("OperandRef::extract_field({:?}): not applicable", self)
239         };
240
241         // HACK(eddyb) have to bitcast pointers until LLVM removes pointee types.
242         match val {
243             OperandValue::Immediate(ref mut llval) => {
244                 *llval = bx.bitcast(*llval, field.immediate_llvm_type(bx.cx));
245             }
246             OperandValue::Pair(ref mut a, ref mut b) => {
247                 *a = bx.bitcast(*a, field.scalar_pair_element_llvm_type(bx.cx, 0, true));
248                 *b = bx.bitcast(*b, field.scalar_pair_element_llvm_type(bx.cx, 1, true));
249             }
250             OperandValue::Ref(..) => bug!()
251         }
252
253         OperandRef {
254             val,
255             layout: field
256         }
257     }
258 }
259
260 impl OperandValue<&'ll Value> {
261     pub fn store(self, bx: &Builder<'a, 'll, 'tcx>, dest: PlaceRef<'tcx, &'ll Value>) {
262         self.store_with_flags(bx, dest, MemFlags::empty());
263     }
264
265     pub fn volatile_store(
266         self,
267         bx: &Builder<'a, 'll, 'tcx, &'ll Value>,
268         dest: PlaceRef<'tcx, &'ll Value>
269     ) {
270         self.store_with_flags(bx, dest, MemFlags::VOLATILE);
271     }
272
273     pub fn unaligned_volatile_store(
274         self,
275         bx: &Builder<'a, 'll, 'tcx>,
276         dest: PlaceRef<'tcx, &'ll Value>,
277     ) {
278         self.store_with_flags(bx, dest, MemFlags::VOLATILE | MemFlags::UNALIGNED);
279     }
280 }
281
282 impl<'a, 'll: 'a, 'tcx: 'll, Value : ?Sized> OperandValue<&'ll Value> where
283     Value : ValueTrait,
284     Builder<'a, 'll, 'tcx, &'ll Value>: BuilderMethods<'a, 'll, 'tcx, Value>
285 {
286     pub fn nontemporal_store(
287         self,
288         bx: &Builder<'a, 'll, 'tcx, &'ll Value>,
289         dest: PlaceRef<'tcx, &'ll Value>
290     ) {
291         self.store_with_flags(bx, dest, MemFlags::NONTEMPORAL);
292     }
293
294     fn store_with_flags<Builder: BuilderMethods<'a, 'll, 'tcx, Value>>(
295         self,
296         bx: &Builder,
297         dest: PlaceRef<'tcx, &'ll Value>,
298         flags: MemFlags,
299     ) {
300         debug!("OperandRef::store: operand={:?}, dest={:?}", self, dest);
301         // Avoid generating stores of zero-sized values, because the only way to have a zero-sized
302         // value is through `undef`, and store itself is useless.
303         if dest.layout.is_zst() {
304             return;
305         }
306         match self {
307             OperandValue::Ref(r, None, source_align) => {
308                 base::memcpy_ty(bx, dest.llval, dest.align, r, source_align,
309                                 dest.layout, flags)
310             }
311             OperandValue::Ref(_, Some(_), _) => {
312                 bug!("cannot directly store unsized values");
313             }
314             OperandValue::Immediate(s) => {
315                 let val = base::from_immediate(bx, s);
316                 bx.store_with_flags(val, dest.llval, dest.align, flags);
317             }
318             OperandValue::Pair(a, b) => {
319                 for (i, &x) in [a, b].iter().enumerate() {
320                     let llptr = bx.struct_gep(dest.llval, i as u64);
321                     let val = base::from_immediate(bx, x);
322                     bx.store_with_flags(val, llptr, dest.align, flags);
323                 }
324             }
325         }
326     }
327 }
328
329 impl OperandValue<&'ll Value> {
330     pub fn store_unsized(
331         self,
332         bx: &Builder<'a, 'll, 'tcx, &'ll Value>,
333         indirect_dest: PlaceRef<'tcx, &'ll Value>
334     ) {
335         debug!("OperandRef::store_unsized: operand={:?}, indirect_dest={:?}", self, indirect_dest);
336         let flags = MemFlags::empty();
337
338         // `indirect_dest` must have `*mut T` type. We extract `T` out of it.
339         let unsized_ty = indirect_dest.layout.ty.builtin_deref(true)
340             .unwrap_or_else(|| bug!("indirect_dest has non-pointer type: {:?}", indirect_dest)).ty;
341
342         let (llptr, llextra) =
343             if let OperandValue::Ref(llptr, Some(llextra), _) = self {
344                 (llptr, llextra)
345             } else {
346                 bug!("store_unsized called with a sized value")
347             };
348
349         // FIXME: choose an appropriate alignment, or use dynamic align somehow
350         let max_align = Align::from_bits(128, 128).unwrap();
351         let min_align = Align::from_bits(8, 8).unwrap();
352
353         // Allocate an appropriate region on the stack, and copy the value into it
354         let (llsize, _) = glue::size_and_align_of_dst(bx, unsized_ty, Some(llextra));
355         let lldst = bx.array_alloca(Type::i8(bx.cx), llsize, "unsized_tmp", max_align);
356         base::call_memcpy(bx, lldst, max_align, llptr, min_align, llsize, flags);
357
358         // Store the allocated region and the extra to the indirect place.
359         let indirect_operand = OperandValue::Pair(lldst, llextra);
360         indirect_operand.store(bx, indirect_dest);
361     }
362 }
363
364 impl FunctionCx<'a, 'll, 'tcx, &'ll Value> {
365     fn maybe_codegen_consume_direct(&mut self,
366                                   bx: &Builder<'a, 'll, 'tcx>,
367                                   place: &mir::Place<'tcx>)
368                                    -> Option<OperandRef<'tcx, &'ll Value>>
369     {
370         debug!("maybe_codegen_consume_direct(place={:?})", place);
371
372         // watch out for locals that do not have an
373         // alloca; they are handled somewhat differently
374         if let mir::Place::Local(index) = *place {
375             match self.locals[index] {
376                 LocalRef::Operand(Some(o)) => {
377                     return Some(o);
378                 }
379                 LocalRef::Operand(None) => {
380                     bug!("use of {:?} before def", place);
381                 }
382                 LocalRef::Place(..) | LocalRef::UnsizedPlace(..) => {
383                     // use path below
384                 }
385             }
386         }
387
388         // Moves out of scalar and scalar pair fields are trivial.
389         if let &mir::Place::Projection(ref proj) = place {
390             if let Some(o) = self.maybe_codegen_consume_direct(bx, &proj.base) {
391                 match proj.elem {
392                     mir::ProjectionElem::Field(ref f, _) => {
393                         return Some(o.extract_field(bx, f.index()));
394                     }
395                     mir::ProjectionElem::Index(_) |
396                     mir::ProjectionElem::ConstantIndex { .. } => {
397                         // ZSTs don't require any actual memory access.
398                         // FIXME(eddyb) deduplicate this with the identical
399                         // checks in `codegen_consume` and `extract_field`.
400                         let elem = o.layout.field(bx.cx, 0);
401                         if elem.is_zst() {
402                             return Some(OperandRef::new_zst(bx.cx, elem));
403                         }
404                     }
405                     _ => {}
406                 }
407             }
408         }
409
410         None
411     }
412
413     pub fn codegen_consume(&mut self,
414                          bx: &Builder<'a, 'll, 'tcx>,
415                          place: &mir::Place<'tcx>)
416                          -> OperandRef<'tcx, &'ll Value>
417     {
418         debug!("codegen_consume(place={:?})", place);
419
420         let ty = self.monomorphized_place_ty(place);
421         let layout = bx.cx.layout_of(ty);
422
423         // ZSTs don't require any actual memory access.
424         if layout.is_zst() {
425             return OperandRef::new_zst(bx.cx, layout);
426         }
427
428         if let Some(o) = self.maybe_codegen_consume_direct(bx, place) {
429             return o;
430         }
431
432         // for most places, to consume them we just load them
433         // out from their home
434         self.codegen_place(bx, place).load(bx)
435     }
436
437     pub fn codegen_operand(&mut self,
438                          bx: &Builder<'a, 'll, 'tcx>,
439                          operand: &mir::Operand<'tcx>)
440                          -> OperandRef<'tcx, &'ll Value>
441     {
442         debug!("codegen_operand(operand={:?})", operand);
443
444         match *operand {
445             mir::Operand::Copy(ref place) |
446             mir::Operand::Move(ref place) => {
447                 self.codegen_consume(bx, place)
448             }
449
450             mir::Operand::Constant(ref constant) => {
451                 let ty = self.monomorphize(&constant.ty);
452                 self.eval_mir_constant(bx, constant)
453                     .and_then(|c| OperandRef::from_const(bx, c))
454                     .unwrap_or_else(|err| {
455                         match err {
456                             // errored or at least linted
457                             ErrorHandled::Reported => {},
458                             ErrorHandled::TooGeneric => {
459                                 bug!("codgen encountered polymorphic constant")
460                             },
461                         }
462                         // Allow RalfJ to sleep soundly knowing that even refactorings that remove
463                         // the above error (or silence it under some conditions) will not cause UB
464                         let fnname = bx.cx.get_intrinsic(&("llvm.trap"));
465                         bx.call(fnname, &[], None);
466                         // We've errored, so we don't have to produce working code.
467                         let layout = bx.cx.layout_of(ty);
468                         PlaceRef::new_sized(
469                             C_undef(layout.llvm_type(bx.cx).ptr_to()),
470                             layout,
471                             layout.align,
472                         ).load(bx)
473                     })
474             }
475         }
476     }
477 }