]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/mir/lvalue.rs
88e46b5c99a44186a4a033e4ff630544049555c1
[rust.git] / src / librustc_trans / mir / lvalue.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, TypeFoldable};
13 use rustc::ty::layout::{self, LayoutTyper};
14 use rustc::mir;
15 use rustc::mir::tcx::LvalueTy;
16 use rustc_data_structures::indexed_vec::Idx;
17 use adt;
18 use builder::Builder;
19 use common::{self, CrateContext, C_uint};
20 use consts;
21 use machine;
22 use type_of;
23 use type_::Type;
24 use value::Value;
25 use glue;
26
27 use std::ptr;
28 use std::ops;
29
30 use super::{MirContext, LocalRef};
31
32 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
33 pub enum Alignment {
34     Packed,
35     AbiAligned,
36 }
37
38 impl ops::BitOr for Alignment {
39     type Output = Self;
40
41     fn bitor(self, rhs: Self) -> Self {
42         match (self, rhs) {
43             (Alignment::Packed, _) => Alignment::Packed,
44             (Alignment::AbiAligned, a) => a,
45         }
46     }
47 }
48
49 impl Alignment {
50     pub fn from_packed(packed: bool) -> Self {
51         if packed {
52             Alignment::Packed
53         } else {
54             Alignment::AbiAligned
55         }
56     }
57
58     pub fn to_align(self) -> Option<u32> {
59         match self {
60             Alignment::Packed => Some(1),
61             Alignment::AbiAligned => None,
62         }
63     }
64
65     pub fn min_with(self, align: u32) -> Option<u32> {
66         match self {
67             Alignment::Packed => Some(1),
68             Alignment::AbiAligned => Some(align),
69         }
70     }
71 }
72
73 #[derive(Copy, Clone, Debug)]
74 pub struct LvalueRef<'tcx> {
75     /// Pointer to the contents of the lvalue
76     pub llval: ValueRef,
77
78     /// This lvalue's extra data if it is unsized, or null
79     pub llextra: ValueRef,
80
81     /// Monomorphized type of this lvalue, including variant information
82     pub ty: LvalueTy<'tcx>,
83
84     /// Whether this lvalue is known to be aligned according to its layout
85     pub alignment: Alignment,
86 }
87
88 impl<'a, 'tcx> LvalueRef<'tcx> {
89     pub fn new_sized(llval: ValueRef, lvalue_ty: LvalueTy<'tcx>,
90                      alignment: Alignment) -> LvalueRef<'tcx> {
91         LvalueRef { llval: llval, llextra: ptr::null_mut(), ty: lvalue_ty, alignment: alignment }
92     }
93
94     pub fn new_sized_ty(llval: ValueRef, ty: Ty<'tcx>, alignment: Alignment) -> LvalueRef<'tcx> {
95         LvalueRef::new_sized(llval, LvalueTy::from_ty(ty), alignment)
96     }
97
98     pub fn alloca(bcx: &Builder<'a, 'tcx>, ty: Ty<'tcx>, name: &str) -> LvalueRef<'tcx> {
99         debug!("alloca({:?}: {:?})", name, ty);
100         let tmp = bcx.alloca(
101             type_of::type_of(bcx.ccx, ty), name, bcx.ccx.over_align_of(ty));
102         assert!(!ty.has_param_types());
103         Self::new_sized_ty(tmp, ty, Alignment::AbiAligned)
104     }
105
106     pub fn len(&self, ccx: &CrateContext<'a, 'tcx>) -> ValueRef {
107         let ty = self.ty.to_ty(ccx.tcx());
108         match ty.sty {
109             ty::TyArray(_, n) => common::C_uint(ccx, n),
110             ty::TySlice(_) | ty::TyStr => {
111                 assert!(self.llextra != ptr::null_mut());
112                 self.llextra
113             }
114             _ => bug!("unexpected type `{}` in LvalueRef::len", ty)
115         }
116     }
117
118     pub fn has_extra(&self) -> bool {
119         !self.llextra.is_null()
120     }
121
122     fn struct_field_ptr(
123         self,
124         bcx: &Builder<'a, 'tcx>,
125         st: &layout::Struct,
126         fields: &Vec<Ty<'tcx>>,
127         ix: usize,
128         needs_cast: bool
129     ) -> (ValueRef, Alignment) {
130         let fty = fields[ix];
131         let ccx = bcx.ccx;
132
133         let alignment = self.alignment | Alignment::from_packed(st.packed);
134
135         let llfields = adt::struct_llfields(ccx, fields, st);
136         let ptr_val = if needs_cast {
137             let real_ty = Type::struct_(ccx, &llfields[..], st.packed);
138             bcx.pointercast(self.llval, real_ty.ptr_to())
139         } else {
140             self.llval
141         };
142
143         // Simple case - we can just GEP the field
144         //   * First field - Always aligned properly
145         //   * Packed struct - There is no alignment padding
146         //   * Field is sized - pointer is properly aligned already
147         if st.offsets[ix] == layout::Size::from_bytes(0) || st.packed ||
148             bcx.ccx.shared().type_is_sized(fty) {
149                 return (bcx.struct_gep(
150                         ptr_val, adt::struct_llfields_index(st, ix)), alignment);
151             }
152
153         // If the type of the last field is [T] or str, then we don't need to do
154         // any adjusments
155         match fty.sty {
156             ty::TySlice(..) | ty::TyStr => {
157                 return (bcx.struct_gep(
158                         ptr_val, adt::struct_llfields_index(st, ix)), alignment);
159             }
160             _ => ()
161         }
162
163         // There's no metadata available, log the case and just do the GEP.
164         if !self.has_extra() {
165             debug!("Unsized field `{}`, of `{:?}` has no metadata for adjustment",
166                 ix, Value(ptr_val));
167             return (bcx.struct_gep(ptr_val, adt::struct_llfields_index(st, ix)), alignment);
168         }
169
170         // We need to get the pointer manually now.
171         // We do this by casting to a *i8, then offsetting it by the appropriate amount.
172         // We do this instead of, say, simply adjusting the pointer from the result of a GEP
173         // because the field may have an arbitrary alignment in the LLVM representation
174         // anyway.
175         //
176         // To demonstrate:
177         //   struct Foo<T: ?Sized> {
178         //      x: u16,
179         //      y: T
180         //   }
181         //
182         // The type Foo<Foo<Trait>> is represented in LLVM as { u16, { u16, u8 }}, meaning that
183         // the `y` field has 16-bit alignment.
184
185         let meta = self.llextra;
186
187
188         let offset = st.offsets[ix].bytes();
189         let unaligned_offset = C_uint(bcx.ccx, offset);
190
191         // Get the alignment of the field
192         let (_, align) = glue::size_and_align_of_dst(bcx, fty, meta);
193
194         // Bump the unaligned offset up to the appropriate alignment using the
195         // following expression:
196         //
197         //   (unaligned offset + (align - 1)) & -align
198
199         // Calculate offset
200         let align_sub_1 = bcx.sub(align, C_uint(bcx.ccx, 1u64));
201         let offset = bcx.and(bcx.add(unaligned_offset, align_sub_1),
202         bcx.neg(align));
203
204         debug!("struct_field_ptr: DST field offset: {:?}", Value(offset));
205
206         // Cast and adjust pointer
207         let byte_ptr = bcx.pointercast(ptr_val, Type::i8p(bcx.ccx));
208         let byte_ptr = bcx.gep(byte_ptr, &[offset]);
209
210         // Finally, cast back to the type expected
211         let ll_fty = type_of::in_memory_type_of(bcx.ccx, fty);
212         debug!("struct_field_ptr: Field type is {:?}", ll_fty);
213         (bcx.pointercast(byte_ptr, ll_fty.ptr_to()), alignment)
214     }
215
216     /// Access a field, at a point when the value's case is known.
217     pub fn trans_field_ptr(self, bcx: &Builder<'a, 'tcx>, ix: usize) -> (ValueRef, Alignment) {
218         let discr = match self.ty {
219             LvalueTy::Ty { .. } => 0,
220             LvalueTy::Downcast { variant_index, .. } => variant_index,
221         };
222         let t = self.ty.to_ty(bcx.tcx());
223         let l = bcx.ccx.layout_of(t);
224         // Note: if this ever needs to generate conditionals (e.g., if we
225         // decide to do some kind of cdr-coding-like non-unique repr
226         // someday), it will need to return a possibly-new bcx as well.
227         match *l {
228             layout::Univariant { ref variant, .. } => {
229                 assert_eq!(discr, 0);
230                 self.struct_field_ptr(bcx, &variant,
231                     &adt::compute_fields(bcx.ccx, t, 0, false), ix, false)
232             }
233             layout::Vector { count, .. } => {
234                 assert_eq!(discr, 0);
235                 assert!((ix as u64) < count);
236                 (bcx.struct_gep(self.llval, ix), self.alignment)
237             }
238             layout::General { discr: d, ref variants, .. } => {
239                 let mut fields = adt::compute_fields(bcx.ccx, t, discr, false);
240                 fields.insert(0, d.to_ty(&bcx.tcx(), false));
241                 self.struct_field_ptr(bcx, &variants[discr], &fields, ix + 1, true)
242             }
243             layout::UntaggedUnion { ref variants } => {
244                 let fields = adt::compute_fields(bcx.ccx, t, 0, false);
245                 let ty = type_of::in_memory_type_of(bcx.ccx, fields[ix]);
246                 (bcx.pointercast(self.llval, ty.ptr_to()),
247                  self.alignment | Alignment::from_packed(variants.packed))
248             }
249             layout::RawNullablePointer { nndiscr, .. } |
250             layout::StructWrappedNullablePointer { nndiscr,  .. } if discr as u64 != nndiscr => {
251                 let nullfields = adt::compute_fields(bcx.ccx, t, (1-nndiscr) as usize, false);
252                 // The unit-like case might have a nonzero number of unit-like fields.
253                 // (e.d., Result of Either with (), as one side.)
254                 let ty = type_of::type_of(bcx.ccx, nullfields[ix]);
255                 assert_eq!(machine::llsize_of_alloc(bcx.ccx, ty), 0);
256                 (bcx.pointercast(self.llval, ty.ptr_to()), Alignment::Packed)
257             }
258             layout::RawNullablePointer { nndiscr, .. } => {
259                 let nnty = adt::compute_fields(bcx.ccx, t, nndiscr as usize, false)[0];
260                 assert_eq!(ix, 0);
261                 assert_eq!(discr as u64, nndiscr);
262                 let ty = type_of::type_of(bcx.ccx, nnty);
263                 (bcx.pointercast(self.llval, ty.ptr_to()), self.alignment)
264             }
265             layout::StructWrappedNullablePointer { ref nonnull, nndiscr, .. } => {
266                 assert_eq!(discr as u64, nndiscr);
267                 self.struct_field_ptr(bcx, &nonnull,
268                      &adt::compute_fields(bcx.ccx, t, discr, false), ix, false)
269             }
270             _ => bug!("element access in type without elements: {} represented as {:#?}", t, l)
271         }
272     }
273
274     pub fn project_index(&self, bcx: &Builder<'a, 'tcx>, llindex: ValueRef) -> ValueRef {
275         if let ty::TySlice(_) = self.ty.to_ty(bcx.tcx()).sty {
276             // Slices already point to the array element type.
277             bcx.inbounds_gep(self.llval, &[llindex])
278         } else {
279             let zero = common::C_uint(bcx.ccx, 0u64);
280             bcx.inbounds_gep(self.llval, &[zero, llindex])
281         }
282     }
283 }
284
285 impl<'a, 'tcx> MirContext<'a, 'tcx> {
286     pub fn trans_lvalue(&mut self,
287                         bcx: &Builder<'a, 'tcx>,
288                         lvalue: &mir::Lvalue<'tcx>)
289                         -> LvalueRef<'tcx> {
290         debug!("trans_lvalue(lvalue={:?})", lvalue);
291
292         let ccx = bcx.ccx;
293         let tcx = ccx.tcx();
294
295         if let mir::Lvalue::Local(index) = *lvalue {
296             match self.locals[index] {
297                 LocalRef::Lvalue(lvalue) => {
298                     return lvalue;
299                 }
300                 LocalRef::Operand(..) => {
301                     bug!("using operand local {:?} as lvalue", lvalue);
302                 }
303             }
304         }
305
306         let result = match *lvalue {
307             mir::Lvalue::Local(_) => bug!(), // handled above
308             mir::Lvalue::Static(box mir::Static { def_id, ty }) => {
309                 LvalueRef::new_sized(consts::get_static(ccx, def_id),
310                                      LvalueTy::from_ty(self.monomorphize(&ty)),
311                                      Alignment::AbiAligned)
312             },
313             mir::Lvalue::Projection(box mir::Projection {
314                 ref base,
315                 elem: mir::ProjectionElem::Deref
316             }) => {
317                 // Load the pointer from its location.
318                 self.trans_consume(bcx, base).deref()
319             }
320             mir::Lvalue::Projection(ref projection) => {
321                 let tr_base = self.trans_lvalue(bcx, &projection.base);
322                 let projected_ty = tr_base.ty.projection_ty(tcx, &projection.elem);
323                 let projected_ty = self.monomorphize(&projected_ty);
324                 let align = tr_base.alignment;
325
326                 let ((llprojected, align), llextra) = match projection.elem {
327                     mir::ProjectionElem::Deref => bug!(),
328                     mir::ProjectionElem::Field(ref field, _) => {
329                         let llextra = if self.ccx.shared().type_is_sized(projected_ty.to_ty(tcx)) {
330                             ptr::null_mut()
331                         } else {
332                             tr_base.llextra
333                         };
334                         (tr_base.trans_field_ptr(bcx, field.index()), llextra)
335                     }
336                     mir::ProjectionElem::Index(ref index) => {
337                         let index = self.trans_operand(bcx, index);
338                         let llindex = self.prepare_index(bcx, index.immediate());
339                         ((tr_base.project_index(bcx, llindex), align), ptr::null_mut())
340                     }
341                     mir::ProjectionElem::ConstantIndex { offset,
342                                                          from_end: false,
343                                                          min_length: _ } => {
344                         let lloffset = C_uint(bcx.ccx, offset);
345                         ((tr_base.project_index(bcx, lloffset), align), ptr::null_mut())
346                     }
347                     mir::ProjectionElem::ConstantIndex { offset,
348                                                          from_end: true,
349                                                          min_length: _ } => {
350                         let lloffset = C_uint(bcx.ccx, offset);
351                         let lllen = tr_base.len(bcx.ccx);
352                         let llindex = bcx.sub(lllen, lloffset);
353                         ((tr_base.project_index(bcx, llindex), align), ptr::null_mut())
354                     }
355                     mir::ProjectionElem::Subslice { from, to } => {
356                         let llbase = tr_base.project_index(bcx, C_uint(bcx.ccx, from));
357
358                         let base_ty = tr_base.ty.to_ty(bcx.tcx());
359                         match base_ty.sty {
360                             ty::TyArray(..) => {
361                                 // must cast the lvalue pointer type to the new
362                                 // array type (*[%_; new_len]).
363                                 let base_ty = self.monomorphized_lvalue_ty(lvalue);
364                                 let llbasety = type_of::type_of(bcx.ccx, base_ty).ptr_to();
365                                 let llbase = bcx.pointercast(llbase, llbasety);
366                                 ((llbase, align), ptr::null_mut())
367                             }
368                             ty::TySlice(..) => {
369                                 assert!(tr_base.llextra != ptr::null_mut());
370                                 let lllen = bcx.sub(tr_base.llextra,
371                                                     C_uint(bcx.ccx, from+to));
372                                 ((llbase, align), lllen)
373                             }
374                             _ => bug!("unexpected type {:?} in Subslice", base_ty)
375                         }
376                     }
377                     mir::ProjectionElem::Downcast(..) => {
378                         ((tr_base.llval, align), tr_base.llextra)
379                     }
380                 };
381                 LvalueRef {
382                     llval: llprojected,
383                     llextra: llextra,
384                     ty: projected_ty,
385                     alignment: align,
386                 }
387             }
388         };
389         debug!("trans_lvalue(lvalue={:?}) => {:?}", lvalue, result);
390         result
391     }
392
393     /// Adjust the bitwidth of an index since LLVM is less forgiving
394     /// than we are.
395     ///
396     /// nmatsakis: is this still necessary? Not sure.
397     fn prepare_index(&mut self, bcx: &Builder<'a, 'tcx>, llindex: ValueRef) -> ValueRef {
398         let index_size = machine::llbitsize_of_real(bcx.ccx, common::val_ty(llindex));
399         let int_size = machine::llbitsize_of_real(bcx.ccx, bcx.ccx.int_type());
400         if index_size < int_size {
401             bcx.zext(llindex, bcx.ccx.int_type())
402         } else if index_size > int_size {
403             bcx.trunc(llindex, bcx.ccx.int_type())
404         } else {
405             llindex
406         }
407     }
408
409     pub fn monomorphized_lvalue_ty(&self, lvalue: &mir::Lvalue<'tcx>) -> Ty<'tcx> {
410         let tcx = self.ccx.tcx();
411         let lvalue_ty = lvalue.ty(&self.mir, tcx);
412         self.monomorphize(&lvalue_ty.to_ty(tcx))
413     }
414 }