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