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;
17 use builder::{Builder, MemFlags};
18 use common::{CodegenCx, IntPredicate};
19 use type_of::LayoutLlvmExt;
22 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 = bx.cx().static_addr_of(init, layout.align, None);
68 let llval = unsafe { LLVMConstInBoundsGEP(
69 bx.cx().static_bitcast(base_addr, bx.cx().type_i8p()),
70 &bx.cx().const_usize(offset.bytes()),
73 let llval = bx.cx().static_bitcast(llval, bx.cx().type_ptr_to(layout.llvm_type(bx.cx())));
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()
104 cx.const_usize(count)
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, bx.cx().type_i1())
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, cx.type_ptr_to(field.llvm_type(cx))),
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 = cx.const_usize(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, cx.const_usize(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, cx.type_i8p());
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, bx.cx().type_ptr_to(ll_fty)),
276 llextra: self.llextra,
278 align: effective_field_align,
282 /// Obtain the actual discriminant of a value.
283 pub fn codegen_get_discr(
285 bx: &Builder<'a, 'll, 'tcx>,
288 let cast_to = bx.cx().layout_of(cast_to).immediate_llvm_type(bx.cx());
289 if self.layout.abi.is_uninhabited() {
290 return bx.cx().const_undef(cast_to);
292 match self.layout.variants {
293 layout::Variants::Single { index } => {
294 let discr_val = self.layout.ty.ty_adt_def().map_or(
295 index.as_u32() as u128,
296 |def| def.discriminant_for_variant(bx.cx().tcx, index).val);
297 return bx.cx().const_uint_big(cast_to, discr_val);
299 layout::Variants::Tagged { .. } |
300 layout::Variants::NicheFilling { .. } => {},
303 let discr = self.project_field(bx, 0);
304 let lldiscr = discr.load(bx).immediate();
305 match self.layout.variants {
306 layout::Variants::Single { .. } => bug!(),
307 layout::Variants::Tagged { ref tag, .. } => {
308 let signed = match tag.value {
309 // We use `i1` for bytes that are always `0` or `1`,
310 // e.g. `#[repr(i8)] enum E { A, B }`, but we can't
311 // let LLVM interpret the `i1` as signed, because
312 // then `i1 1` (i.e. E::B) is effectively `i8 -1`.
313 layout::Int(_, signed) => !tag.is_bool() && signed,
316 bx.intcast(lldiscr, cast_to, signed)
318 layout::Variants::NicheFilling {
324 let niche_llty = discr.layout.immediate_llvm_type(bx.cx());
325 if niche_variants.start() == niche_variants.end() {
326 // FIXME(eddyb) Check the actual primitive type here.
327 let niche_llval = if niche_start == 0 {
328 // HACK(eddyb) Using `c_null` as it works on all types.
329 bx.cx().const_null(niche_llty)
331 bx.cx().const_uint_big(niche_llty, niche_start)
333 bx.select(bx.icmp(IntPredicate::IntEQ, lldiscr, niche_llval),
334 bx.cx().const_uint(cast_to, niche_variants.start().as_u32() as u64),
335 bx.cx().const_uint(cast_to, dataful_variant.as_u32() as u64))
337 // Rebase from niche values to discriminant values.
338 let delta = niche_start.wrapping_sub(niche_variants.start().as_u32() as u128);
339 let lldiscr = bx.sub(lldiscr, bx.cx().const_uint_big(niche_llty, delta));
341 bx.cx().const_uint(niche_llty, niche_variants.end().as_u32() as u64);
342 bx.select(bx.icmp(IntPredicate::IntULE, lldiscr, lldiscr_max),
343 bx.intcast(lldiscr, cast_to, false),
344 bx.cx().const_uint(cast_to, dataful_variant.as_u32() as u64))
350 /// Set the discriminant for a new value of the given case of the given
352 pub fn codegen_set_discr(&self, bx: &Builder<'a, 'll, 'tcx>, variant_index: VariantIdx) {
353 if self.layout.for_variant(bx.cx(), variant_index).abi.is_uninhabited() {
356 match self.layout.variants {
357 layout::Variants::Single { index } => {
358 assert_eq!(index, variant_index);
360 layout::Variants::Tagged { .. } => {
361 let ptr = self.project_field(bx, 0);
362 let to = self.layout.ty.ty_adt_def().unwrap()
363 .discriminant_for_variant(bx.tcx(), variant_index)
366 bx.cx().const_uint_big(ptr.layout.llvm_type(bx.cx()), to),
370 layout::Variants::NicheFilling {
376 if variant_index != dataful_variant {
377 if bx.sess().target.target.arch == "arm" ||
378 bx.sess().target.target.arch == "aarch64" {
379 // Issue #34427: As workaround for LLVM bug on ARM,
380 // use memset of 0 before assigning niche value.
381 let fill_byte = bx.cx().const_u8(0);
382 let (size, align) = self.layout.size_and_align();
383 let size = bx.cx().const_usize(size.bytes());
384 bx.memset(self.llval, fill_byte, size, align, MemFlags::empty());
387 let niche = self.project_field(bx, 0);
388 let niche_llty = niche.layout.immediate_llvm_type(bx.cx());
389 let niche_value = variant_index.as_u32() - niche_variants.start().as_u32();
390 let niche_value = (niche_value as u128)
391 .wrapping_add(niche_start);
392 // FIXME(eddyb) Check the actual primitive type here.
393 let niche_llval = if niche_value == 0 {
394 // HACK(eddyb) Using `c_null` as it works on all types.
395 bx.cx().const_null(niche_llty)
397 bx.cx().const_uint_big(niche_llty, niche_value)
399 OperandValue::Immediate(niche_llval).store(bx, niche);
405 pub fn project_index(&self, bx: &Builder<'a, 'll, 'tcx>, llindex: &'ll Value)
406 -> PlaceRef<'tcx, &'ll Value> {
408 llval: bx.inbounds_gep(self.llval, &[bx.cx().const_usize(0), llindex]),
410 layout: self.layout.field(bx.cx(), 0),
415 pub fn project_downcast(&self, bx: &Builder<'a, 'll, 'tcx>, variant_index: VariantIdx)
416 -> PlaceRef<'tcx, &'ll Value> {
417 let mut downcast = *self;
418 downcast.layout = self.layout.for_variant(bx.cx(), variant_index);
420 // Cast to the appropriate variant struct type.
421 let variant_ty = downcast.layout.llvm_type(bx.cx());
422 downcast.llval = bx.pointercast(downcast.llval, bx.cx().type_ptr_to(variant_ty));
427 pub fn storage_live(&self, bx: &Builder<'a, 'll, 'tcx>) {
428 bx.lifetime_start(self.llval, self.layout.size);
431 pub fn storage_dead(&self, bx: &Builder<'a, 'll, 'tcx>) {
432 bx.lifetime_end(self.llval, self.layout.size);
436 impl FunctionCx<'a, 'll, 'tcx, &'ll Value> {
437 pub fn codegen_place(&mut self,
438 bx: &Builder<'a, 'll, 'tcx>,
439 place: &mir::Place<'tcx>)
440 -> PlaceRef<'tcx, &'ll Value> {
441 debug!("codegen_place(place={:?})", place);
446 if let mir::Place::Local(index) = *place {
447 match self.locals[index] {
448 LocalRef::Place(place) => {
451 LocalRef::UnsizedPlace(place) => {
452 return place.load(bx).deref(&cx);
454 LocalRef::Operand(..) => {
455 bug!("using operand local {:?} as place", place);
460 let result = match *place {
461 mir::Place::Local(_) => bug!(), // handled above
462 mir::Place::Promoted(box (index, ty)) => {
463 let param_env = ty::ParamEnv::reveal_all();
464 let cid = mir::interpret::GlobalId {
465 instance: self.instance,
466 promoted: Some(index),
468 let layout = cx.layout_of(self.monomorphize(&ty));
469 match bx.tcx().const_eval(param_env.and(cid)) {
470 Ok(val) => match val.val {
471 mir::interpret::ConstValue::ByRef(_, alloc, offset) => {
472 PlaceRef::from_const_alloc(bx, layout, alloc, offset)
474 _ => bug!("promoteds should have an allocation: {:?}", val),
477 // this is unreachable as long as runtime
478 // and compile-time agree on values
479 // With floats that won't always be true
480 // so we generate an abort
481 let fnname = bx.cx().get_intrinsic(&("llvm.trap"));
482 bx.call(fnname, &[], None);
483 let llval = bx.cx().const_undef(
484 bx.cx().type_ptr_to(layout.llvm_type(bx.cx()))
486 PlaceRef::new_sized(llval, layout, layout.align)
490 mir::Place::Static(box mir::Static { def_id, ty }) => {
491 let layout = cx.layout_of(self.monomorphize(&ty));
492 PlaceRef::new_sized(cx.get_static(def_id), layout, layout.align)
494 mir::Place::Projection(box mir::Projection {
496 elem: mir::ProjectionElem::Deref
498 // Load the pointer from its location.
499 self.codegen_consume(bx, base).deref(bx.cx())
501 mir::Place::Projection(ref projection) => {
502 let cg_base = self.codegen_place(bx, &projection.base);
504 match projection.elem {
505 mir::ProjectionElem::Deref => bug!(),
506 mir::ProjectionElem::Field(ref field, _) => {
507 cg_base.project_field(bx, field.index())
509 mir::ProjectionElem::Index(index) => {
510 let index = &mir::Operand::Copy(mir::Place::Local(index));
511 let index = self.codegen_operand(bx, index);
512 let llindex = index.immediate();
513 cg_base.project_index(bx, llindex)
515 mir::ProjectionElem::ConstantIndex { offset,
518 let lloffset = bx.cx().const_usize(offset as u64);
519 cg_base.project_index(bx, lloffset)
521 mir::ProjectionElem::ConstantIndex { offset,
524 let lloffset = bx.cx().const_usize(offset as u64);
525 let lllen = cg_base.len(bx.cx());
526 let llindex = bx.sub(lllen, lloffset);
527 cg_base.project_index(bx, llindex)
529 mir::ProjectionElem::Subslice { from, to } => {
530 let mut subslice = cg_base.project_index(bx,
531 bx.cx().const_usize(from as u64));
532 let projected_ty = PlaceTy::Ty { ty: cg_base.layout.ty }
533 .projection_ty(tcx, &projection.elem)
535 subslice.layout = bx.cx().layout_of(self.monomorphize(&projected_ty));
537 if subslice.layout.is_unsized() {
538 subslice.llextra = Some(bx.sub(cg_base.llextra.unwrap(),
539 bx.cx().const_usize((from as u64) + (to as u64))));
542 // Cast the place pointer type to the new
543 // array or slice type (*[%_; new_len]).
544 subslice.llval = bx.pointercast(subslice.llval,
545 bx.cx().type_ptr_to(subslice.layout.llvm_type(bx.cx())));
549 mir::ProjectionElem::Downcast(_, v) => {
550 cg_base.project_downcast(bx, v)
555 debug!("codegen_place(place={:?}) => {:?}", place, result);
559 pub fn monomorphized_place_ty(&self, place: &mir::Place<'tcx>) -> Ty<'tcx> {
560 let tcx = self.cx.tcx;
561 let place_ty = place.ty(self.mir, tcx);
562 self.monomorphize(&place_ty.to_ty(tcx))