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