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, C_undef, C_usize, C_u8, C_u32, C_uint, C_null, C_uint_big};
20 use type_of::LayoutLlvmExt;
24 use mir::constant::const_alloc_to_llvm;
26 use super::{FunctionCx, LocalRef};
27 use super::operand::{OperandRef, OperandValue};
29 #[derive(Copy, Clone, Debug)]
30 pub struct PlaceRef<'tcx, V> {
31 /// Pointer to the contents of the place
34 /// This place's extra data if it is unsized, or null
35 pub llextra: Option<V>,
37 /// Monomorphized type of this place, including variant information
38 pub layout: TyLayout<'tcx>,
40 /// What alignment we know for this place
44 impl PlaceRef<'tcx, &'ll Value> {
47 layout: TyLayout<'tcx>,
49 ) -> PlaceRef<'tcx, &'ll Value> {
50 assert!(!layout.is_unsized());
59 pub fn from_const_alloc(
60 bx: &Builder<'a, 'll, 'tcx>,
61 layout: TyLayout<'tcx>,
62 alloc: &mir::interpret::Allocation,
64 ) -> PlaceRef<'tcx, &'ll Value> {
65 let init = const_alloc_to_llvm(bx.cx, alloc);
66 let base_addr = consts::addr_of(bx.cx, init, layout.align, None);
68 let llval = unsafe { LLVMConstInBoundsGEP(
69 consts::bitcast(base_addr, Type::i8p(bx.cx)),
70 &C_usize(bx.cx, offset.bytes()),
73 let llval = consts::bitcast(llval, layout.llvm_type(bx.cx).ptr_to());
74 PlaceRef::new_sized(llval, layout, alloc.align)
77 pub fn alloca(bx: &Builder<'a, 'll, 'tcx>, layout: TyLayout<'tcx>, name: &str)
78 -> PlaceRef<'tcx, &'ll Value> {
79 debug!("alloca({:?}: {:?})", name, layout);
80 assert!(!layout.is_unsized(), "tried to statically allocate unsized place");
81 let tmp = bx.alloca(layout.llvm_type(bx.cx), name, layout.align);
82 Self::new_sized(tmp, layout, layout.align)
85 /// Returns a place for an indirect reference to an unsized place.
86 pub fn alloca_unsized_indirect(
87 bx: &Builder<'a, 'll, 'tcx>,
88 layout: TyLayout<'tcx>,
90 ) -> PlaceRef<'tcx, &'ll Value> {
91 debug!("alloca_unsized_indirect({:?}: {:?})", name, layout);
92 assert!(layout.is_unsized(), "tried to allocate indirect place for sized values");
93 let ptr_ty = bx.cx.tcx.mk_mut_ptr(layout.ty);
94 let ptr_layout = bx.cx.layout_of(ptr_ty);
95 Self::alloca(bx, ptr_layout, name)
98 pub fn len(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Value {
99 if let layout::FieldPlacement::Array { count, .. } = self.layout.fields {
100 if self.layout.is_unsized() {
101 assert_eq!(count, 0);
102 self.llextra.unwrap()
107 bug!("unexpected layout `{:#?}` in PlaceRef::len", self.layout)
111 pub fn load(&self, bx: &Builder<'a, 'll, 'tcx>) -> OperandRef<'tcx, &'ll Value> {
112 debug!("PlaceRef::load: {:?}", self);
114 assert_eq!(self.llextra.is_some(), self.layout.is_unsized());
116 if self.layout.is_zst() {
117 return OperandRef::new_zst(bx.cx, self.layout);
120 let scalar_load_metadata = |load, scalar: &layout::Scalar| {
121 let vr = scalar.valid_range.clone();
124 let range = scalar.valid_range_exclusive(bx.cx);
125 if range.start != range.end {
126 bx.range_metadata(load, range);
129 layout::Pointer if vr.start() < vr.end() && !vr.contains(&0) => {
130 bx.nonnull_metadata(load);
136 let val = if let Some(llextra) = self.llextra {
137 OperandValue::Ref(self.llval, Some(llextra), self.align)
138 } else if self.layout.is_llvm_immediate() {
139 let mut const_llval = None;
141 if let Some(global) = llvm::LLVMIsAGlobalVariable(self.llval) {
142 if llvm::LLVMIsGlobalConstant(global) == llvm::True {
143 const_llval = llvm::LLVMGetInitializer(global);
147 let llval = const_llval.unwrap_or_else(|| {
148 let load = bx.load(self.llval, self.align);
149 if let layout::Abi::Scalar(ref scalar) = self.layout.abi {
150 scalar_load_metadata(load, scalar);
154 OperandValue::Immediate(base::to_immediate(bx, llval, self.layout))
155 } else if let layout::Abi::ScalarPair(ref a, ref b) = self.layout.abi {
156 let load = |i, scalar: &layout::Scalar| {
157 let llptr = bx.struct_gep(self.llval, i as u64);
158 let load = bx.load(llptr, self.align);
159 scalar_load_metadata(load, scalar);
160 if scalar.is_bool() {
161 bx.trunc(load, Type::i1(bx.cx))
166 OperandValue::Pair(load(0, a), load(1, b))
168 OperandValue::Ref(self.llval, None, self.align)
171 OperandRef { val, layout: self.layout }
174 /// Access a field, at a point when the value's case is known.
175 pub fn project_field(
177 bx: &Builder<'a, 'll, 'tcx>,
179 ) -> PlaceRef<'tcx, &'ll Value> {
181 let field = self.layout.field(cx, ix);
182 let offset = self.layout.fields.offset(ix);
183 let effective_field_align = self.align.restrict_for_offset(offset);
186 // Unions and newtypes only use an offset of 0.
187 let llval = if offset.bytes() == 0 {
189 } else if let layout::Abi::ScalarPair(ref a, ref b) = self.layout.abi {
190 // Offsets have to match either first or second field.
191 assert_eq!(offset, a.value.size(cx).abi_align(b.value.align(cx)));
192 bx.struct_gep(self.llval, 1)
194 bx.struct_gep(self.llval, self.layout.llvm_field_index(ix))
197 // HACK(eddyb) have to bitcast pointers until LLVM removes pointee types.
198 llval: bx.pointercast(llval, field.llvm_type(cx).ptr_to()),
199 llextra: if cx.type_has_metadata(field.ty) {
205 align: effective_field_align,
209 // Simple cases, which don't need DST adjustment:
210 // * no metadata available - just log the case
211 // * known alignment - sized types, [T], str or a foreign type
212 // * packed struct - there is no alignment padding
214 _ if self.llextra.is_none() => {
215 debug!("Unsized field `{}`, of `{:?}` has no metadata for adjustment",
219 _ if !field.is_unsized() => return simple(),
220 ty::Slice(..) | ty::Str | ty::Foreign(..) => return simple(),
222 if def.repr.packed() {
223 // FIXME(eddyb) generalize the adjustment when we
224 // start supporting packing to larger alignments.
225 assert_eq!(self.layout.align.abi(), 1);
232 // We need to get the pointer manually now.
233 // We do this by casting to a *i8, then offsetting it by the appropriate amount.
234 // We do this instead of, say, simply adjusting the pointer from the result of a GEP
235 // because the field may have an arbitrary alignment in the LLVM representation
239 // struct Foo<T: ?Sized> {
244 // The type Foo<Foo<Trait>> is represented in LLVM as { u16, { u16, u8 }}, meaning that
245 // the `y` field has 16-bit alignment.
247 let meta = self.llextra;
249 let unaligned_offset = C_usize(cx, offset.bytes());
251 // Get the alignment of the field
252 let (_, unsized_align) = glue::size_and_align_of_dst(bx, field.ty, meta);
254 // Bump the unaligned offset up to the appropriate alignment using the
255 // following expression:
257 // (unaligned offset + (align - 1)) & -align
260 let align_sub_1 = bx.sub(unsized_align, C_usize(cx, 1u64));
261 let offset = bx.and(bx.add(unaligned_offset, align_sub_1),
262 bx.neg(unsized_align));
264 debug!("struct_field_ptr: DST field offset: {:?}", offset);
266 // Cast and adjust pointer
267 let byte_ptr = bx.pointercast(self.llval, Type::i8p(cx));
268 let byte_ptr = bx.gep(byte_ptr, &[offset]);
270 // Finally, cast back to the type expected
271 let ll_fty = field.llvm_type(cx);
272 debug!("struct_field_ptr: Field type is {:?}", ll_fty);
275 llval: bx.pointercast(byte_ptr, ll_fty.ptr_to()),
276 llextra: self.llextra,
278 align: effective_field_align,
282 /// Obtain the actual discriminant of a value.
283 pub fn codegen_get_discr(self, bx: &Builder<'a, 'll, 'tcx>, cast_to: Ty<'tcx>) -> &'ll Value {
284 let cast_to = bx.cx.layout_of(cast_to).immediate_llvm_type(bx.cx);
285 if self.layout.abi.is_uninhabited() {
286 return C_undef(cast_to);
288 match self.layout.variants {
289 layout::Variants::Single { index } => {
290 let discr_val = self.layout.ty.ty_adt_def().map_or(
291 index.as_u32() as u128,
292 |def| def.discriminant_for_variant(bx.cx.tcx, index).val);
293 return C_uint_big(cast_to, discr_val);
295 layout::Variants::Tagged { .. } |
296 layout::Variants::NicheFilling { .. } => {},
299 let discr = self.project_field(bx, 0);
300 let lldiscr = discr.load(bx).immediate();
301 match self.layout.variants {
302 layout::Variants::Single { .. } => bug!(),
303 layout::Variants::Tagged { ref tag, .. } => {
304 let signed = match tag.value {
305 // We use `i1` for bytes that are always `0` or `1`,
306 // e.g. `#[repr(i8)] enum E { A, B }`, but we can't
307 // let LLVM interpret the `i1` as signed, because
308 // then `i1 1` (i.e. E::B) is effectively `i8 -1`.
309 layout::Int(_, signed) => !tag.is_bool() && signed,
312 bx.intcast(lldiscr, cast_to, signed)
314 layout::Variants::NicheFilling {
320 let niche_llty = discr.layout.immediate_llvm_type(bx.cx);
321 if niche_variants.start() == niche_variants.end() {
322 // FIXME(eddyb) Check the actual primitive type here.
323 let niche_llval = if niche_start == 0 {
324 // HACK(eddyb) Using `C_null` as it works on all types.
327 C_uint_big(niche_llty, niche_start)
329 bx.select(bx.icmp(llvm::IntEQ, lldiscr, niche_llval),
330 C_uint(cast_to, niche_variants.start().as_u32() as u64),
331 C_uint(cast_to, dataful_variant.as_u32() as u64))
333 // Rebase from niche values to discriminant values.
334 let delta = niche_start.wrapping_sub(niche_variants.start().as_u32() as u128);
335 let lldiscr = bx.sub(lldiscr, C_uint_big(niche_llty, delta));
336 let lldiscr_max = C_uint(niche_llty, niche_variants.end().as_u32() as u64);
337 bx.select(bx.icmp(llvm::IntULE, lldiscr, lldiscr_max),
338 bx.intcast(lldiscr, cast_to, false),
339 C_uint(cast_to, dataful_variant.as_u32() as u64))
345 /// Set the discriminant for a new value of the given case of the given
347 pub fn codegen_set_discr(&self, bx: &Builder<'a, 'll, 'tcx>, variant_index: VariantIdx) {
348 if self.layout.for_variant(bx.cx, variant_index).abi.is_uninhabited() {
351 match self.layout.variants {
352 layout::Variants::Single { index } => {
353 assert_eq!(index, variant_index);
355 layout::Variants::Tagged { .. } => {
356 let ptr = self.project_field(bx, 0);
357 let to = self.layout.ty.ty_adt_def().unwrap()
358 .discriminant_for_variant(bx.tcx(), variant_index)
361 C_uint_big(ptr.layout.llvm_type(bx.cx), to),
365 layout::Variants::NicheFilling {
371 if variant_index != dataful_variant {
372 if bx.sess().target.target.arch == "arm" ||
373 bx.sess().target.target.arch == "aarch64" {
374 // Issue #34427: As workaround for LLVM bug on ARM,
375 // use memset of 0 before assigning niche value.
376 let llptr = bx.pointercast(self.llval, Type::i8(bx.cx).ptr_to());
377 let fill_byte = C_u8(bx.cx, 0);
378 let (size, align) = self.layout.size_and_align();
379 let size = C_usize(bx.cx, size.bytes());
380 let align = C_u32(bx.cx, align.abi() as u32);
381 base::call_memset(bx, llptr, fill_byte, size, align, false);
384 let niche = self.project_field(bx, 0);
385 let niche_llty = niche.layout.immediate_llvm_type(bx.cx);
386 let niche_value = variant_index.as_u32() - niche_variants.start().as_u32();
387 let niche_value = (niche_value as u128)
388 .wrapping_add(niche_start);
389 // FIXME(eddyb) Check the actual primitive type here.
390 let niche_llval = if niche_value == 0 {
391 // HACK(eddyb) Using `C_null` as it works on all types.
394 C_uint_big(niche_llty, niche_value)
396 OperandValue::Immediate(niche_llval).store(bx, niche);
402 pub fn project_index(&self, bx: &Builder<'a, 'll, 'tcx>, llindex: &'ll Value)
403 -> PlaceRef<'tcx, &'ll Value> {
405 llval: bx.inbounds_gep(self.llval, &[C_usize(bx.cx, 0), llindex]),
407 layout: self.layout.field(bx.cx, 0),
412 pub fn project_downcast(&self, bx: &Builder<'a, 'll, 'tcx>, variant_index: VariantIdx)
413 -> PlaceRef<'tcx, &'ll Value> {
414 let mut downcast = *self;
415 downcast.layout = self.layout.for_variant(bx.cx, variant_index);
417 // Cast to the appropriate variant struct type.
418 let variant_ty = downcast.layout.llvm_type(bx.cx);
419 downcast.llval = bx.pointercast(downcast.llval, variant_ty.ptr_to());
424 pub fn storage_live(&self, bx: &Builder<'a, 'll, 'tcx>) {
425 bx.lifetime_start(self.llval, self.layout.size);
428 pub fn storage_dead(&self, bx: &Builder<'a, 'll, 'tcx>) {
429 bx.lifetime_end(self.llval, self.layout.size);
433 impl FunctionCx<'a, 'll, 'tcx, &'ll Value> {
434 pub fn codegen_place(&mut self,
435 bx: &Builder<'a, 'll, 'tcx>,
436 place: &mir::Place<'tcx>)
437 -> PlaceRef<'tcx, &'ll Value> {
438 debug!("codegen_place(place={:?})", place);
443 if let mir::Place::Local(index) = *place {
444 match self.locals[index] {
445 LocalRef::Place(place) => {
448 LocalRef::UnsizedPlace(place) => {
449 return place.load(bx).deref(&cx);
451 LocalRef::Operand(..) => {
452 bug!("using operand local {:?} as place", place);
457 let result = match *place {
458 mir::Place::Local(_) => bug!(), // handled above
459 mir::Place::Promoted(box (index, ty)) => {
460 let param_env = ty::ParamEnv::reveal_all();
461 let cid = mir::interpret::GlobalId {
462 instance: self.instance,
463 promoted: Some(index),
465 let layout = cx.layout_of(self.monomorphize(&ty));
466 match bx.tcx().const_eval(param_env.and(cid)) {
467 Ok(val) => match val.val {
468 mir::interpret::ConstValue::ByRef(_, alloc, offset) => {
469 PlaceRef::from_const_alloc(bx, layout, alloc, offset)
471 _ => bug!("promoteds should have an allocation: {:?}", val),
474 // this is unreachable as long as runtime
475 // and compile-time agree on values
476 // With floats that won't always be true
477 // so we generate an abort
478 let fnname = bx.cx.get_intrinsic(&("llvm.trap"));
479 bx.call(fnname, &[], None);
480 let llval = C_undef(layout.llvm_type(bx.cx).ptr_to());
481 PlaceRef::new_sized(llval, layout, layout.align)
485 mir::Place::Static(box mir::Static { def_id, ty }) => {
486 let layout = cx.layout_of(self.monomorphize(&ty));
487 PlaceRef::new_sized(consts::get_static(cx, def_id), layout, layout.align)
489 mir::Place::Projection(box mir::Projection {
491 elem: mir::ProjectionElem::Deref
493 // Load the pointer from its location.
494 self.codegen_consume(bx, base).deref(bx.cx)
496 mir::Place::Projection(ref projection) => {
497 let cg_base = self.codegen_place(bx, &projection.base);
499 match projection.elem {
500 mir::ProjectionElem::Deref => bug!(),
501 mir::ProjectionElem::Field(ref field, _) => {
502 cg_base.project_field(bx, field.index())
504 mir::ProjectionElem::Index(index) => {
505 let index = &mir::Operand::Copy(mir::Place::Local(index));
506 let index = self.codegen_operand(bx, index);
507 let llindex = index.immediate();
508 cg_base.project_index(bx, llindex)
510 mir::ProjectionElem::ConstantIndex { offset,
513 let lloffset = C_usize(bx.cx, offset as u64);
514 cg_base.project_index(bx, lloffset)
516 mir::ProjectionElem::ConstantIndex { offset,
519 let lloffset = C_usize(bx.cx, offset as u64);
520 let lllen = cg_base.len(bx.cx);
521 let llindex = bx.sub(lllen, lloffset);
522 cg_base.project_index(bx, llindex)
524 mir::ProjectionElem::Subslice { from, to } => {
525 let mut subslice = cg_base.project_index(bx,
526 C_usize(bx.cx, from as u64));
527 let projected_ty = PlaceTy::Ty { ty: cg_base.layout.ty }
528 .projection_ty(tcx, &projection.elem)
530 subslice.layout = bx.cx.layout_of(self.monomorphize(&projected_ty));
532 if subslice.layout.is_unsized() {
533 subslice.llextra = Some(bx.sub(cg_base.llextra.unwrap(),
534 C_usize(bx.cx, (from as u64) + (to as u64))));
537 // Cast the place pointer type to the new
538 // array or slice type (*[%_; new_len]).
539 subslice.llval = bx.pointercast(subslice.llval,
540 subslice.layout.llvm_type(bx.cx).ptr_to());
544 mir::ProjectionElem::Downcast(_, v) => {
545 cg_base.project_downcast(bx, v)
550 debug!("codegen_place(place={:?}) => {:?}", place, result);
554 pub fn monomorphized_place_ty(&self, place: &mir::Place<'tcx>) -> Ty<'tcx> {
555 let tcx = self.cx.tcx;
556 let place_ty = place.ty(self.mir, tcx);
557 self.monomorphize(&place_ty.to_ty(tcx))