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.
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.
11 use llvm::{self, LLVMConstInBoundsGEP};
12 use rustc::ty::{self, Ty};
13 use rustc::ty::layout::{self, Align, TyLayout, LayoutOf, Size, VariantIdx};
15 use rustc::mir::tcx::PlaceTy;
18 use common::{CodegenCx, IntPredicate};
20 use type_of::LayoutLlvmExt;
23 use mir::constant::const_alloc_to_llvm;
25 use interfaces::{BuilderMethods, ConstMethods, TypeMethods};
27 use super::{FunctionCx, LocalRef};
28 use super::operand::{OperandRef, OperandValue};
30 #[derive(Copy, Clone, Debug)]
31 pub struct PlaceRef<'tcx, V> {
32 /// Pointer to the contents of the place
35 /// This place's extra data if it is unsized, or null
36 pub llextra: Option<V>,
38 /// Monomorphized type of this place, including variant information
39 pub layout: TyLayout<'tcx>,
41 /// What alignment we know for this place
45 impl PlaceRef<'tcx, &'ll Value> {
48 layout: TyLayout<'tcx>,
50 ) -> PlaceRef<'tcx, &'ll Value> {
51 assert!(!layout.is_unsized());
60 pub fn from_const_alloc(
61 bx: &Builder<'a, 'll, 'tcx>,
62 layout: TyLayout<'tcx>,
63 alloc: &mir::interpret::Allocation,
65 ) -> PlaceRef<'tcx, &'ll Value> {
66 let init = const_alloc_to_llvm(bx.cx(), alloc);
67 let base_addr = consts::addr_of(bx.cx(), init, layout.align, None);
69 let llval = unsafe { LLVMConstInBoundsGEP(
70 consts::bitcast(base_addr, bx.cx().type_i8p()),
71 &bx.cx().const_usize(offset.bytes()),
74 let llval = consts::bitcast(llval, bx.cx().type_ptr_to(layout.llvm_type(bx.cx())));
75 PlaceRef::new_sized(llval, layout, alloc.align)
78 pub fn alloca(bx: &Builder<'a, 'll, 'tcx>, layout: TyLayout<'tcx>, name: &str)
79 -> PlaceRef<'tcx, &'ll Value> {
80 debug!("alloca({:?}: {:?})", name, layout);
81 assert!(!layout.is_unsized(), "tried to statically allocate unsized place");
82 let tmp = bx.alloca(layout.llvm_type(bx.cx()), name, layout.align);
83 Self::new_sized(tmp, layout, layout.align)
86 /// Returns a place for an indirect reference to an unsized place.
87 pub fn alloca_unsized_indirect(
88 bx: &Builder<'a, 'll, 'tcx>,
89 layout: TyLayout<'tcx>,
91 ) -> PlaceRef<'tcx, &'ll Value> {
92 debug!("alloca_unsized_indirect({:?}: {:?})", name, layout);
93 assert!(layout.is_unsized(), "tried to allocate indirect place for sized values");
94 let ptr_ty = bx.cx().tcx.mk_mut_ptr(layout.ty);
95 let ptr_layout = bx.cx().layout_of(ptr_ty);
96 Self::alloca(bx, ptr_layout, name)
99 pub fn len(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Value {
100 if let layout::FieldPlacement::Array { count, .. } = self.layout.fields {
101 if self.layout.is_unsized() {
102 assert_eq!(count, 0);
103 self.llextra.unwrap()
105 cx.const_usize(count)
108 bug!("unexpected layout `{:#?}` in PlaceRef::len", self.layout)
112 pub fn load(&self, bx: &Builder<'a, 'll, 'tcx>) -> OperandRef<'tcx, &'ll Value> {
113 debug!("PlaceRef::load: {:?}", self);
115 assert_eq!(self.llextra.is_some(), self.layout.is_unsized());
117 if self.layout.is_zst() {
118 return OperandRef::new_zst(bx.cx(), self.layout);
121 let scalar_load_metadata = |load, scalar: &layout::Scalar| {
122 let vr = scalar.valid_range.clone();
125 let range = scalar.valid_range_exclusive(bx.cx());
126 if range.start != range.end {
127 bx.range_metadata(load, range);
130 layout::Pointer if vr.start() < vr.end() && !vr.contains(&0) => {
131 bx.nonnull_metadata(load);
137 let val = if let Some(llextra) = self.llextra {
138 OperandValue::Ref(self.llval, Some(llextra), self.align)
139 } else if self.layout.is_llvm_immediate() {
140 let mut const_llval = None;
142 if let Some(global) = llvm::LLVMIsAGlobalVariable(self.llval) {
143 if llvm::LLVMIsGlobalConstant(global) == llvm::True {
144 const_llval = llvm::LLVMGetInitializer(global);
148 let llval = const_llval.unwrap_or_else(|| {
149 let load = bx.load(self.llval, self.align);
150 if let layout::Abi::Scalar(ref scalar) = self.layout.abi {
151 scalar_load_metadata(load, scalar);
155 OperandValue::Immediate(base::to_immediate(bx, llval, self.layout))
156 } else if let layout::Abi::ScalarPair(ref a, ref b) = self.layout.abi {
157 let load = |i, scalar: &layout::Scalar| {
158 let llptr = bx.struct_gep(self.llval, i as u64);
159 let load = bx.load(llptr, self.align);
160 scalar_load_metadata(load, scalar);
161 if scalar.is_bool() {
162 bx.trunc(load, bx.cx().type_i1())
167 OperandValue::Pair(load(0, a), load(1, b))
169 OperandValue::Ref(self.llval, None, self.align)
172 OperandRef { val, layout: self.layout }
175 /// Access a field, at a point when the value's case is known.
176 pub fn project_field(
178 bx: &Builder<'a, 'll, 'tcx>,
180 ) -> PlaceRef<'tcx, &'ll Value> {
182 let field = self.layout.field(cx, ix);
183 let offset = self.layout.fields.offset(ix);
184 let effective_field_align = self.align.restrict_for_offset(offset);
187 // Unions and newtypes only use an offset of 0.
188 let llval = if offset.bytes() == 0 {
190 } else if let layout::Abi::ScalarPair(ref a, ref b) = self.layout.abi {
191 // Offsets have to match either first or second field.
192 assert_eq!(offset, a.value.size(cx).abi_align(b.value.align(cx)));
193 bx.struct_gep(self.llval, 1)
195 bx.struct_gep(self.llval, self.layout.llvm_field_index(ix))
198 // HACK(eddyb) have to bitcast pointers until LLVM removes pointee types.
199 llval: bx.pointercast(llval, cx.type_ptr_to(field.llvm_type(cx))),
200 llextra: if cx.type_has_metadata(field.ty) {
206 align: effective_field_align,
210 // Simple cases, which don't need DST adjustment:
211 // * no metadata available - just log the case
212 // * known alignment - sized types, [T], str or a foreign type
213 // * packed struct - there is no alignment padding
215 _ if self.llextra.is_none() => {
216 debug!("Unsized field `{}`, of `{:?}` has no metadata for adjustment",
220 _ if !field.is_unsized() => return simple(),
221 ty::Slice(..) | ty::Str | ty::Foreign(..) => return simple(),
223 if def.repr.packed() {
224 // FIXME(eddyb) generalize the adjustment when we
225 // start supporting packing to larger alignments.
226 assert_eq!(self.layout.align.abi(), 1);
233 // We need to get the pointer manually now.
234 // We do this by casting to a *i8, then offsetting it by the appropriate amount.
235 // We do this instead of, say, simply adjusting the pointer from the result of a GEP
236 // because the field may have an arbitrary alignment in the LLVM representation
240 // struct Foo<T: ?Sized> {
245 // The type Foo<Foo<Trait>> is represented in LLVM as { u16, { u16, u8 }}, meaning that
246 // the `y` field has 16-bit alignment.
248 let meta = self.llextra;
250 let unaligned_offset = cx.const_usize(offset.bytes());
252 // Get the alignment of the field
253 let (_, unsized_align) = glue::size_and_align_of_dst(bx, field.ty, meta);
255 // Bump the unaligned offset up to the appropriate alignment using the
256 // following expression:
258 // (unaligned offset + (align - 1)) & -align
261 let align_sub_1 = bx.sub(unsized_align, cx.const_usize(1u64));
262 let offset = bx.and(bx.add(unaligned_offset, align_sub_1),
263 bx.neg(unsized_align));
265 debug!("struct_field_ptr: DST field offset: {:?}", offset);
267 // Cast and adjust pointer
268 let byte_ptr = bx.pointercast(self.llval, cx.type_i8p());
269 let byte_ptr = bx.gep(byte_ptr, &[offset]);
271 // Finally, cast back to the type expected
272 let ll_fty = field.llvm_type(cx);
273 debug!("struct_field_ptr: Field type is {:?}", ll_fty);
276 llval: bx.pointercast(byte_ptr, bx.cx().type_ptr_to(ll_fty)),
277 llextra: self.llextra,
279 align: effective_field_align,
283 /// Obtain the actual discriminant of a value.
284 pub fn codegen_get_discr(
286 bx: &Builder<'a, 'll, 'tcx>,
289 let cast_to = bx.cx().layout_of(cast_to).immediate_llvm_type(bx.cx());
290 if self.layout.abi.is_uninhabited() {
291 return bx.cx().const_undef(cast_to);
293 match self.layout.variants {
294 layout::Variants::Single { index } => {
295 let discr_val = self.layout.ty.ty_adt_def().map_or(
296 index.as_u32() as u128,
297 |def| def.discriminant_for_variant(bx.cx().tcx, index).val);
298 return bx.cx().const_uint_big(cast_to, discr_val);
300 layout::Variants::Tagged { .. } |
301 layout::Variants::NicheFilling { .. } => {},
304 let discr = self.project_field(bx, 0);
305 let lldiscr = discr.load(bx).immediate();
306 match self.layout.variants {
307 layout::Variants::Single { .. } => bug!(),
308 layout::Variants::Tagged { ref tag, .. } => {
309 let signed = match tag.value {
310 // We use `i1` for bytes that are always `0` or `1`,
311 // e.g. `#[repr(i8)] enum E { A, B }`, but we can't
312 // let LLVM interpret the `i1` as signed, because
313 // then `i1 1` (i.e. E::B) is effectively `i8 -1`.
314 layout::Int(_, signed) => !tag.is_bool() && signed,
317 bx.intcast(lldiscr, cast_to, signed)
319 layout::Variants::NicheFilling {
325 let niche_llty = discr.layout.immediate_llvm_type(bx.cx());
326 if niche_variants.start() == niche_variants.end() {
327 // FIXME(eddyb) Check the actual primitive type here.
328 let niche_llval = if niche_start == 0 {
329 // HACK(eddyb) Using `c_null` as it works on all types.
330 bx.cx().const_null(niche_llty)
332 bx.cx().const_uint_big(niche_llty, niche_start)
334 bx.select(bx.icmp(IntPredicate::IntEQ, lldiscr, niche_llval),
335 bx.cx().const_uint(cast_to, niche_variants.start().as_u32() as u64),
336 bx.cx().const_uint(cast_to, dataful_variant.as_u32() as u64))
338 // Rebase from niche values to discriminant values.
339 let delta = niche_start.wrapping_sub(niche_variants.start().as_u32() as u128);
340 let lldiscr = bx.sub(lldiscr, bx.cx().const_uint_big(niche_llty, delta));
342 bx.cx().const_uint(niche_llty, niche_variants.end().as_u32() as u64);
343 bx.select(bx.icmp(IntPredicate::IntULE, lldiscr, lldiscr_max),
344 bx.intcast(lldiscr, cast_to, false),
345 bx.cx().const_uint(cast_to, dataful_variant.as_u32() as u64))
351 /// Set the discriminant for a new value of the given case of the given
353 pub fn codegen_set_discr(&self, bx: &Builder<'a, 'll, 'tcx>, variant_index: VariantIdx) {
354 if self.layout.for_variant(bx.cx(), variant_index).abi.is_uninhabited() {
357 match self.layout.variants {
358 layout::Variants::Single { index } => {
359 assert_eq!(index, variant_index);
361 layout::Variants::Tagged { .. } => {
362 let ptr = self.project_field(bx, 0);
363 let to = self.layout.ty.ty_adt_def().unwrap()
364 .discriminant_for_variant(bx.tcx(), variant_index)
367 bx.cx().const_uint_big(ptr.layout.llvm_type(bx.cx()), to),
371 layout::Variants::NicheFilling {
377 if variant_index != dataful_variant {
378 if bx.sess().target.target.arch == "arm" ||
379 bx.sess().target.target.arch == "aarch64" {
380 // Issue #34427: As workaround for LLVM bug on ARM,
381 // use memset of 0 before assigning niche value.
382 let llptr = bx.pointercast(
384 bx.cx().type_ptr_to(bx.cx().type_i8())
386 let fill_byte = bx.cx().const_u8(0);
387 let (size, align) = self.layout.size_and_align();
388 let size = bx.cx().const_usize(size.bytes());
389 let align = bx.cx().const_u32(align.abi() as u32);
390 base::call_memset(bx, llptr, fill_byte, size, align, false);
393 let niche = self.project_field(bx, 0);
394 let niche_llty = niche.layout.immediate_llvm_type(bx.cx());
395 let niche_value = variant_index.as_u32() - niche_variants.start().as_u32();
396 let niche_value = (niche_value as u128)
397 .wrapping_add(niche_start);
398 // FIXME(eddyb) Check the actual primitive type here.
399 let niche_llval = if niche_value == 0 {
400 // HACK(eddyb) Using `c_null` as it works on all types.
401 bx.cx().const_null(niche_llty)
403 bx.cx().const_uint_big(niche_llty, niche_value)
405 OperandValue::Immediate(niche_llval).store(bx, niche);
411 pub fn project_index(&self, bx: &Builder<'a, 'll, 'tcx>, llindex: &'ll Value)
412 -> PlaceRef<'tcx, &'ll Value> {
414 llval: bx.inbounds_gep(self.llval, &[bx.cx().const_usize(0), llindex]),
416 layout: self.layout.field(bx.cx(), 0),
421 pub fn project_downcast(&self, bx: &Builder<'a, 'll, 'tcx>, variant_index: VariantIdx)
422 -> PlaceRef<'tcx, &'ll Value> {
423 let mut downcast = *self;
424 downcast.layout = self.layout.for_variant(bx.cx(), variant_index);
426 // Cast to the appropriate variant struct type.
427 let variant_ty = downcast.layout.llvm_type(bx.cx());
428 downcast.llval = bx.pointercast(downcast.llval, bx.cx().type_ptr_to(variant_ty));
433 pub fn storage_live(&self, bx: &Builder<'a, 'll, 'tcx>) {
434 bx.lifetime_start(self.llval, self.layout.size);
437 pub fn storage_dead(&self, bx: &Builder<'a, 'll, 'tcx>) {
438 bx.lifetime_end(self.llval, self.layout.size);
442 impl FunctionCx<'a, 'll, 'tcx, &'ll Value> {
443 pub fn codegen_place(&mut self,
444 bx: &Builder<'a, 'll, 'tcx>,
445 place: &mir::Place<'tcx>)
446 -> PlaceRef<'tcx, &'ll Value> {
447 debug!("codegen_place(place={:?})", place);
452 if let mir::Place::Local(index) = *place {
453 match self.locals[index] {
454 LocalRef::Place(place) => {
457 LocalRef::UnsizedPlace(place) => {
458 return place.load(bx).deref(&cx);
460 LocalRef::Operand(..) => {
461 bug!("using operand local {:?} as place", place);
466 let result = match *place {
467 mir::Place::Local(_) => bug!(), // handled above
468 mir::Place::Promoted(box (index, ty)) => {
469 let param_env = ty::ParamEnv::reveal_all();
470 let cid = mir::interpret::GlobalId {
471 instance: self.instance,
472 promoted: Some(index),
474 let layout = cx.layout_of(self.monomorphize(&ty));
475 match bx.tcx().const_eval(param_env.and(cid)) {
476 Ok(val) => match val.val {
477 mir::interpret::ConstValue::ByRef(_, alloc, offset) => {
478 PlaceRef::from_const_alloc(bx, layout, alloc, offset)
480 _ => bug!("promoteds should have an allocation: {:?}", val),
483 // this is unreachable as long as runtime
484 // and compile-time agree on values
485 // With floats that won't always be true
486 // so we generate an abort
487 let fnname = bx.cx().get_intrinsic(&("llvm.trap"));
488 bx.call(fnname, &[], None);
489 let llval = bx.cx().const_undef(
490 bx.cx().type_ptr_to(layout.llvm_type(bx.cx()))
492 PlaceRef::new_sized(llval, layout, layout.align)
496 mir::Place::Static(box mir::Static { def_id, ty }) => {
497 let layout = cx.layout_of(self.monomorphize(&ty));
498 PlaceRef::new_sized(consts::get_static(cx, def_id), layout, layout.align)
500 mir::Place::Projection(box mir::Projection {
502 elem: mir::ProjectionElem::Deref
504 // Load the pointer from its location.
505 self.codegen_consume(bx, base).deref(bx.cx())
507 mir::Place::Projection(ref projection) => {
508 let cg_base = self.codegen_place(bx, &projection.base);
510 match projection.elem {
511 mir::ProjectionElem::Deref => bug!(),
512 mir::ProjectionElem::Field(ref field, _) => {
513 cg_base.project_field(bx, field.index())
515 mir::ProjectionElem::Index(index) => {
516 let index = &mir::Operand::Copy(mir::Place::Local(index));
517 let index = self.codegen_operand(bx, index);
518 let llindex = index.immediate();
519 cg_base.project_index(bx, llindex)
521 mir::ProjectionElem::ConstantIndex { offset,
524 let lloffset = bx.cx().const_usize(offset as u64);
525 cg_base.project_index(bx, lloffset)
527 mir::ProjectionElem::ConstantIndex { offset,
530 let lloffset = bx.cx().const_usize(offset as u64);
531 let lllen = cg_base.len(bx.cx());
532 let llindex = bx.sub(lllen, lloffset);
533 cg_base.project_index(bx, llindex)
535 mir::ProjectionElem::Subslice { from, to } => {
536 let mut subslice = cg_base.project_index(bx,
537 bx.cx().const_usize(from as u64));
538 let projected_ty = PlaceTy::Ty { ty: cg_base.layout.ty }
539 .projection_ty(tcx, &projection.elem)
541 subslice.layout = bx.cx().layout_of(self.monomorphize(&projected_ty));
543 if subslice.layout.is_unsized() {
544 subslice.llextra = Some(bx.sub(cg_base.llextra.unwrap(),
545 bx.cx().const_usize((from as u64) + (to as u64))));
548 // Cast the place pointer type to the new
549 // array or slice type (*[%_; new_len]).
550 subslice.llval = bx.pointercast(subslice.llval,
551 bx.cx().type_ptr_to(subslice.layout.llvm_type(bx.cx())));
555 mir::ProjectionElem::Downcast(_, v) => {
556 cg_base.project_downcast(bx, v)
561 debug!("codegen_place(place={:?}) => {:?}", place, result);
565 pub fn monomorphized_place_ty(&self, place: &mir::Place<'tcx>) -> Ty<'tcx> {
566 let tcx = self.cx.tcx;
567 let place_ty = place.ty(self.mir, tcx);
568 self.monomorphize(&place_ty.to_ty(tcx))