]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/mir/place.rs
Auto merge of #53134 - alexcrichton:tweak-travis, r=Mark-Simulacrum
[rust.git] / src / librustc_codegen_llvm / mir / place.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::{self, LLVMConstInBoundsGEP};
12 use rustc::ty::{self, Ty};
13 use rustc::ty::layout::{self, Align, TyLayout, LayoutOf, Size};
14 use rustc::mir;
15 use rustc::mir::tcx::PlaceTy;
16 use rustc_data_structures::indexed_vec::Idx;
17 use base;
18 use builder::Builder;
19 use common::{CodegenCx, C_undef, C_usize, C_u8, C_u32, C_uint, C_null, C_uint_big};
20 use consts;
21 use type_of::LayoutLlvmExt;
22 use type_::Type;
23 use value::Value;
24 use glue;
25 use mir::constant::const_alloc_to_llvm;
26
27 use super::{FunctionCx, LocalRef};
28 use super::operand::{OperandRef, OperandValue};
29
30 #[derive(Copy, Clone, Debug)]
31 pub struct PlaceRef<'ll, 'tcx> {
32     /// Pointer to the contents of the place
33     pub llval: &'ll Value,
34
35     /// This place's extra data if it is unsized, or null
36     pub llextra: Option<&'ll Value>,
37
38     /// Monomorphized type of this place, including variant information
39     pub layout: TyLayout<'tcx>,
40
41     /// What alignment we know for this place
42     pub align: Align,
43 }
44
45 impl PlaceRef<'ll, 'tcx> {
46     pub fn new_sized(
47         llval: &'ll Value,
48         layout: TyLayout<'tcx>,
49         align: Align,
50     ) -> PlaceRef<'ll, 'tcx> {
51         PlaceRef {
52             llval,
53             llextra: None,
54             layout,
55             align
56         }
57     }
58
59     pub fn from_const_alloc(
60         bx: &Builder<'a, 'll, 'tcx>,
61         layout: TyLayout<'tcx>,
62         alloc: &mir::interpret::Allocation,
63         offset: Size,
64     ) -> PlaceRef<'ll, 'tcx> {
65         let init = const_alloc_to_llvm(bx.cx, alloc);
66         let base_addr = consts::addr_of(bx.cx, init, layout.align, "byte_str");
67
68         let llval = unsafe { LLVMConstInBoundsGEP(
69             consts::bitcast(base_addr, Type::i8p(bx.cx)),
70             &C_usize(bx.cx, offset.bytes()),
71             1,
72         )};
73         let llval = consts::bitcast(llval, layout.llvm_type(bx.cx).ptr_to());
74         PlaceRef::new_sized(llval, layout, alloc.align)
75     }
76
77     pub fn alloca(bx: &Builder<'a, 'll, 'tcx>, layout: TyLayout<'tcx>, name: &str)
78                   -> PlaceRef<'ll, 'tcx> {
79         debug!("alloca({:?}: {:?})", name, layout);
80         let tmp = bx.alloca(layout.llvm_type(bx.cx), name, layout.align);
81         Self::new_sized(tmp, layout, layout.align)
82     }
83
84     pub fn len(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Value {
85         if let layout::FieldPlacement::Array { count, .. } = self.layout.fields {
86             if self.layout.is_unsized() {
87                 assert_eq!(count, 0);
88                 self.llextra.unwrap()
89             } else {
90                 C_usize(cx, count)
91             }
92         } else {
93             bug!("unexpected layout `{:#?}` in PlaceRef::len", self.layout)
94         }
95     }
96
97     pub fn load(&self, bx: &Builder<'a, 'll, 'tcx>) -> OperandRef<'ll, 'tcx> {
98         debug!("PlaceRef::load: {:?}", self);
99
100         assert_eq!(self.llextra, None);
101
102         if self.layout.is_zst() {
103             return OperandRef::new_zst(bx.cx, self.layout);
104         }
105
106         let scalar_load_metadata = |load, scalar: &layout::Scalar| {
107             let vr = scalar.valid_range.clone();
108             match scalar.value {
109                 layout::Int(..) => {
110                     let range = scalar.valid_range_exclusive(bx.cx);
111                     if range.start != range.end {
112                         bx.range_metadata(load, range);
113                     }
114                 }
115                 layout::Pointer if vr.start() < vr.end() && !vr.contains(&0) => {
116                     bx.nonnull_metadata(load);
117                 }
118                 _ => {}
119             }
120         };
121
122         let val = if self.layout.is_llvm_immediate() {
123             let mut const_llval = None;
124             unsafe {
125                 if let Some(global) = llvm::LLVMIsAGlobalVariable(self.llval) {
126                     if llvm::LLVMIsGlobalConstant(global) == llvm::True {
127                         const_llval = llvm::LLVMGetInitializer(global);
128                     }
129                 }
130             }
131             let llval = const_llval.unwrap_or_else(|| {
132                 let load = bx.load(self.llval, self.align);
133                 if let layout::Abi::Scalar(ref scalar) = self.layout.abi {
134                     scalar_load_metadata(load, scalar);
135                 }
136                 load
137             });
138             OperandValue::Immediate(base::to_immediate(bx, llval, self.layout))
139         } else if let layout::Abi::ScalarPair(ref a, ref b) = self.layout.abi {
140             let load = |i, scalar: &layout::Scalar| {
141                 let llptr = bx.struct_gep(self.llval, i as u64);
142                 let load = bx.load(llptr, self.align);
143                 scalar_load_metadata(load, scalar);
144                 if scalar.is_bool() {
145                     bx.trunc(load, Type::i1(bx.cx))
146                 } else {
147                     load
148                 }
149             };
150             OperandValue::Pair(load(0, a), load(1, b))
151         } else {
152             OperandValue::Ref(self.llval, self.align)
153         };
154
155         OperandRef { val, layout: self.layout }
156     }
157
158     /// Access a field, at a point when the value's case is known.
159     pub fn project_field(self, bx: &Builder<'a, 'll, 'tcx>, ix: usize) -> PlaceRef<'ll, 'tcx> {
160         let cx = bx.cx;
161         let field = self.layout.field(cx, ix);
162         let offset = self.layout.fields.offset(ix);
163         let align = self.align.min(self.layout.align).min(field.align);
164
165         let simple = || {
166             // Unions and newtypes only use an offset of 0.
167             let llval = if offset.bytes() == 0 {
168                 self.llval
169             } else if let layout::Abi::ScalarPair(ref a, ref b) = self.layout.abi {
170                 // Offsets have to match either first or second field.
171                 assert_eq!(offset, a.value.size(cx).abi_align(b.value.align(cx)));
172                 bx.struct_gep(self.llval, 1)
173             } else {
174                 bx.struct_gep(self.llval, self.layout.llvm_field_index(ix))
175             };
176             PlaceRef {
177                 // HACK(eddyb) have to bitcast pointers until LLVM removes pointee types.
178                 llval: bx.pointercast(llval, field.llvm_type(cx).ptr_to()),
179                 llextra: if cx.type_has_metadata(field.ty) {
180                     self.llextra
181                 } else {
182                     None
183                 },
184                 layout: field,
185                 align,
186             }
187         };
188
189         // Simple cases, which don't need DST adjustment:
190         //   * no metadata available - just log the case
191         //   * known alignment - sized types, [T], str or a foreign type
192         //   * packed struct - there is no alignment padding
193         match field.ty.sty {
194             _ if self.llextra.is_none() => {
195                 debug!("Unsized field `{}`, of `{:?}` has no metadata for adjustment",
196                     ix, self.llval);
197                 return simple();
198             }
199             _ if !field.is_unsized() => return simple(),
200             ty::TySlice(..) | ty::TyStr | ty::TyForeign(..) => return simple(),
201             ty::TyAdt(def, _) => {
202                 if def.repr.packed() {
203                     // FIXME(eddyb) generalize the adjustment when we
204                     // start supporting packing to larger alignments.
205                     assert_eq!(self.layout.align.abi(), 1);
206                     return simple();
207                 }
208             }
209             _ => {}
210         }
211
212         // We need to get the pointer manually now.
213         // We do this by casting to a *i8, then offsetting it by the appropriate amount.
214         // We do this instead of, say, simply adjusting the pointer from the result of a GEP
215         // because the field may have an arbitrary alignment in the LLVM representation
216         // anyway.
217         //
218         // To demonstrate:
219         //   struct Foo<T: ?Sized> {
220         //      x: u16,
221         //      y: T
222         //   }
223         //
224         // The type Foo<Foo<Trait>> is represented in LLVM as { u16, { u16, u8 }}, meaning that
225         // the `y` field has 16-bit alignment.
226
227         let meta = self.llextra;
228
229         let unaligned_offset = C_usize(cx, offset.bytes());
230
231         // Get the alignment of the field
232         let (_, unsized_align) = glue::size_and_align_of_dst(bx, field.ty, meta);
233
234         // Bump the unaligned offset up to the appropriate alignment using the
235         // following expression:
236         //
237         //   (unaligned offset + (align - 1)) & -align
238
239         // Calculate offset
240         let align_sub_1 = bx.sub(unsized_align, C_usize(cx, 1u64));
241         let offset = bx.and(bx.add(unaligned_offset, align_sub_1),
242         bx.neg(unsized_align));
243
244         debug!("struct_field_ptr: DST field offset: {:?}", offset);
245
246         // Cast and adjust pointer
247         let byte_ptr = bx.pointercast(self.llval, Type::i8p(cx));
248         let byte_ptr = bx.gep(byte_ptr, &[offset]);
249
250         // Finally, cast back to the type expected
251         let ll_fty = field.llvm_type(cx);
252         debug!("struct_field_ptr: Field type is {:?}", ll_fty);
253
254         PlaceRef {
255             llval: bx.pointercast(byte_ptr, ll_fty.ptr_to()),
256             llextra: self.llextra,
257             layout: field,
258             align,
259         }
260     }
261
262     /// Obtain the actual discriminant of a value.
263     pub fn codegen_get_discr(self, bx: &Builder<'a, 'll, 'tcx>, cast_to: Ty<'tcx>) -> &'ll Value {
264         let cast_to = bx.cx.layout_of(cast_to).immediate_llvm_type(bx.cx);
265         if self.layout.abi == layout::Abi::Uninhabited {
266             return C_undef(cast_to);
267         }
268         match self.layout.variants {
269             layout::Variants::Single { index } => {
270                 let discr_val = self.layout.ty.ty_adt_def().map_or(
271                     index as u128,
272                     |def| def.discriminant_for_variant(bx.cx.tcx, index).val);
273                 return C_uint_big(cast_to, discr_val);
274             }
275             layout::Variants::Tagged { .. } |
276             layout::Variants::NicheFilling { .. } => {},
277         }
278
279         let discr = self.project_field(bx, 0);
280         let lldiscr = discr.load(bx).immediate();
281         match self.layout.variants {
282             layout::Variants::Single { .. } => bug!(),
283             layout::Variants::Tagged { ref tag, .. } => {
284                 let signed = match tag.value {
285                     // We use `i1` for bytes that are always `0` or `1`,
286                     // e.g. `#[repr(i8)] enum E { A, B }`, but we can't
287                     // let LLVM interpret the `i1` as signed, because
288                     // then `i1 1` (i.e. E::B) is effectively `i8 -1`.
289                     layout::Int(_, signed) => !tag.is_bool() && signed,
290                     _ => false
291                 };
292                 bx.intcast(lldiscr, cast_to, signed)
293             }
294             layout::Variants::NicheFilling {
295                 dataful_variant,
296                 ref niche_variants,
297                 niche_start,
298                 ..
299             } => {
300                 let niche_llty = discr.layout.immediate_llvm_type(bx.cx);
301                 if niche_variants.start() == niche_variants.end() {
302                     // FIXME(eddyb) Check the actual primitive type here.
303                     let niche_llval = if niche_start == 0 {
304                         // HACK(eddyb) Using `C_null` as it works on all types.
305                         C_null(niche_llty)
306                     } else {
307                         C_uint_big(niche_llty, niche_start)
308                     };
309                     bx.select(bx.icmp(llvm::IntEQ, lldiscr, niche_llval),
310                         C_uint(cast_to, *niche_variants.start() as u64),
311                         C_uint(cast_to, dataful_variant as u64))
312                 } else {
313                     // Rebase from niche values to discriminant values.
314                     let delta = niche_start.wrapping_sub(*niche_variants.start() as u128);
315                     let lldiscr = bx.sub(lldiscr, C_uint_big(niche_llty, delta));
316                     let lldiscr_max = C_uint(niche_llty, *niche_variants.end() as u64);
317                     bx.select(bx.icmp(llvm::IntULE, lldiscr, lldiscr_max),
318                         bx.intcast(lldiscr, cast_to, false),
319                         C_uint(cast_to, dataful_variant as u64))
320                 }
321             }
322         }
323     }
324
325     /// Set the discriminant for a new value of the given case of the given
326     /// representation.
327     pub fn codegen_set_discr(&self, bx: &Builder<'a, 'll, 'tcx>, variant_index: usize) {
328         if self.layout.for_variant(bx.cx, variant_index).abi == layout::Abi::Uninhabited {
329             return;
330         }
331         match self.layout.variants {
332             layout::Variants::Single { index } => {
333                 assert_eq!(index, variant_index);
334             }
335             layout::Variants::Tagged { .. } => {
336                 let ptr = self.project_field(bx, 0);
337                 let to = self.layout.ty.ty_adt_def().unwrap()
338                     .discriminant_for_variant(bx.tcx(), variant_index)
339                     .val;
340                 bx.store(
341                     C_uint_big(ptr.layout.llvm_type(bx.cx), to),
342                     ptr.llval,
343                     ptr.align);
344             }
345             layout::Variants::NicheFilling {
346                 dataful_variant,
347                 ref niche_variants,
348                 niche_start,
349                 ..
350             } => {
351                 if variant_index != dataful_variant {
352                     if bx.sess().target.target.arch == "arm" ||
353                        bx.sess().target.target.arch == "aarch64" {
354                         // Issue #34427: As workaround for LLVM bug on ARM,
355                         // use memset of 0 before assigning niche value.
356                         let llptr = bx.pointercast(self.llval, Type::i8(bx.cx).ptr_to());
357                         let fill_byte = C_u8(bx.cx, 0);
358                         let (size, align) = self.layout.size_and_align();
359                         let size = C_usize(bx.cx, size.bytes());
360                         let align = C_u32(bx.cx, align.abi() as u32);
361                         base::call_memset(bx, llptr, fill_byte, size, align, false);
362                     }
363
364                     let niche = self.project_field(bx, 0);
365                     let niche_llty = niche.layout.immediate_llvm_type(bx.cx);
366                     let niche_value = ((variant_index - *niche_variants.start()) as u128)
367                         .wrapping_add(niche_start);
368                     // FIXME(eddyb) Check the actual primitive type here.
369                     let niche_llval = if niche_value == 0 {
370                         // HACK(eddyb) Using `C_null` as it works on all types.
371                         C_null(niche_llty)
372                     } else {
373                         C_uint_big(niche_llty, niche_value)
374                     };
375                     OperandValue::Immediate(niche_llval).store(bx, niche);
376                 }
377             }
378         }
379     }
380
381     pub fn project_index(&self, bx: &Builder<'a, 'll, 'tcx>, llindex: &'ll Value)
382                          -> PlaceRef<'ll, 'tcx> {
383         PlaceRef {
384             llval: bx.inbounds_gep(self.llval, &[C_usize(bx.cx, 0), llindex]),
385             llextra: None,
386             layout: self.layout.field(bx.cx, 0),
387             align: self.align
388         }
389     }
390
391     pub fn project_downcast(&self, bx: &Builder<'a, 'll, 'tcx>, variant_index: usize)
392                             -> PlaceRef<'ll, 'tcx> {
393         let mut downcast = *self;
394         downcast.layout = self.layout.for_variant(bx.cx, variant_index);
395
396         // Cast to the appropriate variant struct type.
397         let variant_ty = downcast.layout.llvm_type(bx.cx);
398         downcast.llval = bx.pointercast(downcast.llval, variant_ty.ptr_to());
399
400         downcast
401     }
402
403     pub fn storage_live(&self, bx: &Builder<'a, 'll, 'tcx>) {
404         bx.lifetime_start(self.llval, self.layout.size);
405     }
406
407     pub fn storage_dead(&self, bx: &Builder<'a, 'll, 'tcx>) {
408         bx.lifetime_end(self.llval, self.layout.size);
409     }
410 }
411
412 impl FunctionCx<'a, 'll, 'tcx> {
413     pub fn codegen_place(&mut self,
414                         bx: &Builder<'a, 'll, 'tcx>,
415                         place: &mir::Place<'tcx>)
416                         -> PlaceRef<'ll, 'tcx> {
417         debug!("codegen_place(place={:?})", place);
418
419         let cx = bx.cx;
420         let tcx = cx.tcx;
421
422         if let mir::Place::Local(index) = *place {
423             match self.locals[index] {
424                 LocalRef::Place(place) => {
425                     return place;
426                 }
427                 LocalRef::Operand(..) => {
428                     bug!("using operand local {:?} as place", place);
429                 }
430             }
431         }
432
433         let result = match *place {
434             mir::Place::Local(_) => bug!(), // handled above
435             mir::Place::Promoted(box (index, ty)) => {
436                 let param_env = ty::ParamEnv::reveal_all();
437                 let cid = mir::interpret::GlobalId {
438                     instance: self.instance,
439                     promoted: Some(index),
440                 };
441                 let layout = cx.layout_of(self.monomorphize(&ty));
442                 match bx.tcx().const_eval(param_env.and(cid)) {
443                     Ok(val) => match val.val {
444                         mir::interpret::ConstValue::ByRef(alloc, offset) => {
445                             PlaceRef::from_const_alloc(bx, layout, alloc, offset)
446                         }
447                         _ => bug!("promoteds should have an allocation: {:?}", val),
448                     },
449                     Err(_) => {
450                         // this is unreachable as long as runtime
451                         // and compile-time agree on values
452                         // With floats that won't always be true
453                         // so we generate an abort
454                         let fnname = bx.cx.get_intrinsic(&("llvm.trap"));
455                         bx.call(fnname, &[], None);
456                         let llval = C_undef(layout.llvm_type(bx.cx).ptr_to());
457                         PlaceRef::new_sized(llval, layout, layout.align)
458                     }
459                 }
460             }
461             mir::Place::Static(box mir::Static { def_id, ty }) => {
462                 let layout = cx.layout_of(self.monomorphize(&ty));
463                 PlaceRef::new_sized(consts::get_static(cx, def_id), layout, layout.align)
464             },
465             mir::Place::Projection(box mir::Projection {
466                 ref base,
467                 elem: mir::ProjectionElem::Deref
468             }) => {
469                 // Load the pointer from its location.
470                 self.codegen_consume(bx, base).deref(bx.cx)
471             }
472             mir::Place::Projection(ref projection) => {
473                 let cg_base = self.codegen_place(bx, &projection.base);
474
475                 match projection.elem {
476                     mir::ProjectionElem::Deref => bug!(),
477                     mir::ProjectionElem::Field(ref field, _) => {
478                         cg_base.project_field(bx, field.index())
479                     }
480                     mir::ProjectionElem::Index(index) => {
481                         let index = &mir::Operand::Copy(mir::Place::Local(index));
482                         let index = self.codegen_operand(bx, index);
483                         let llindex = index.immediate();
484                         cg_base.project_index(bx, llindex)
485                     }
486                     mir::ProjectionElem::ConstantIndex { offset,
487                                                          from_end: false,
488                                                          min_length: _ } => {
489                         let lloffset = C_usize(bx.cx, offset as u64);
490                         cg_base.project_index(bx, lloffset)
491                     }
492                     mir::ProjectionElem::ConstantIndex { offset,
493                                                          from_end: true,
494                                                          min_length: _ } => {
495                         let lloffset = C_usize(bx.cx, offset as u64);
496                         let lllen = cg_base.len(bx.cx);
497                         let llindex = bx.sub(lllen, lloffset);
498                         cg_base.project_index(bx, llindex)
499                     }
500                     mir::ProjectionElem::Subslice { from, to } => {
501                         let mut subslice = cg_base.project_index(bx,
502                             C_usize(bx.cx, from as u64));
503                         let projected_ty = PlaceTy::Ty { ty: cg_base.layout.ty }
504                             .projection_ty(tcx, &projection.elem).to_ty(bx.tcx());
505                         subslice.layout = bx.cx.layout_of(self.monomorphize(&projected_ty));
506
507                         if subslice.layout.is_unsized() {
508                             subslice.llextra = Some(bx.sub(cg_base.llextra.unwrap(),
509                                 C_usize(bx.cx, (from as u64) + (to as u64))));
510                         }
511
512                         // Cast the place pointer type to the new
513                         // array or slice type (*[%_; new_len]).
514                         subslice.llval = bx.pointercast(subslice.llval,
515                             subslice.layout.llvm_type(bx.cx).ptr_to());
516
517                         subslice
518                     }
519                     mir::ProjectionElem::Downcast(_, v) => {
520                         cg_base.project_downcast(bx, v)
521                     }
522                 }
523             }
524         };
525         debug!("codegen_place(place={:?}) => {:?}", place, result);
526         result
527     }
528
529     pub fn monomorphized_place_ty(&self, place: &mir::Place<'tcx>) -> Ty<'tcx> {
530         let tcx = self.cx.tcx;
531         let place_ty = place.ty(self.mir, tcx);
532         self.monomorphize(&place_ty.to_ty(tcx))
533     }
534 }