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};
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<'ll, 'tcx> {
31 /// Pointer to the contents of the place
32 pub llval: &'ll Value,
34 /// This place's extra data if it is unsized, or null
35 pub llextra: Option<&'ll Value>,
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<'ll, 'tcx> {
47 layout: TyLayout<'tcx>,
49 ) -> PlaceRef<'ll, 'tcx> {
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<'ll, 'tcx> {
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<'ll, 'tcx> {
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(bx: &Builder<'a, 'll, 'tcx>, layout: TyLayout<'tcx>, name: &str)
87 -> PlaceRef<'ll, 'tcx> {
88 debug!("alloca_unsized_indirect({:?}: {:?})", name, layout);
89 assert!(layout.is_unsized(), "tried to allocate indirect place for sized values");
90 let ptr_ty = bx.cx.tcx.mk_mut_ptr(layout.ty);
91 let ptr_layout = bx.cx.layout_of(ptr_ty);
92 Self::alloca(bx, ptr_layout, name)
95 pub fn len(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Value {
96 if let layout::FieldPlacement::Array { count, .. } = self.layout.fields {
97 if self.layout.is_unsized() {
104 bug!("unexpected layout `{:#?}` in PlaceRef::len", self.layout)
108 pub fn load(&self, bx: &Builder<'a, 'll, 'tcx>) -> OperandRef<'ll, 'tcx> {
109 debug!("PlaceRef::load: {:?}", self);
111 assert_eq!(self.llextra.is_some(), self.layout.is_unsized());
113 if self.layout.is_zst() {
114 return OperandRef::new_zst(bx.cx, self.layout);
117 let scalar_load_metadata = |load, scalar: &layout::Scalar| {
118 let vr = scalar.valid_range.clone();
121 let range = scalar.valid_range_exclusive(bx.cx);
122 if range.start != range.end {
123 bx.range_metadata(load, range);
126 layout::Pointer if vr.start() < vr.end() && !vr.contains(&0) => {
127 bx.nonnull_metadata(load);
133 let val = if let Some(llextra) = self.llextra {
134 OperandValue::Ref(self.llval, Some(llextra), self.align)
135 } else if self.layout.is_llvm_immediate() {
136 let mut const_llval = None;
138 if let Some(global) = llvm::LLVMIsAGlobalVariable(self.llval) {
139 if llvm::LLVMIsGlobalConstant(global) == llvm::True {
140 const_llval = llvm::LLVMGetInitializer(global);
144 let llval = const_llval.unwrap_or_else(|| {
145 let load = bx.load(self.llval, self.align);
146 if let layout::Abi::Scalar(ref scalar) = self.layout.abi {
147 scalar_load_metadata(load, scalar);
151 OperandValue::Immediate(base::to_immediate(bx, llval, self.layout))
152 } else if let layout::Abi::ScalarPair(ref a, ref b) = self.layout.abi {
153 let load = |i, scalar: &layout::Scalar| {
154 let llptr = bx.struct_gep(self.llval, i as u64);
155 let load = bx.load(llptr, self.align);
156 scalar_load_metadata(load, scalar);
157 if scalar.is_bool() {
158 bx.trunc(load, Type::i1(bx.cx))
163 OperandValue::Pair(load(0, a), load(1, b))
165 OperandValue::Ref(self.llval, None, self.align)
168 OperandRef { val, layout: self.layout }
171 /// Access a field, at a point when the value's case is known.
172 pub fn project_field(self, bx: &Builder<'a, 'll, 'tcx>, ix: usize) -> PlaceRef<'ll, 'tcx> {
174 let field = self.layout.field(cx, ix);
175 let offset = self.layout.fields.offset(ix);
176 let effective_field_align = self.align.restrict_for_offset(offset);
179 // Unions and newtypes only use an offset of 0.
180 let llval = if offset.bytes() == 0 {
182 } else if let layout::Abi::ScalarPair(ref a, ref b) = self.layout.abi {
183 // Offsets have to match either first or second field.
184 assert_eq!(offset, a.value.size(cx).abi_align(b.value.align(cx)));
185 bx.struct_gep(self.llval, 1)
187 bx.struct_gep(self.llval, self.layout.llvm_field_index(ix))
190 // HACK(eddyb) have to bitcast pointers until LLVM removes pointee types.
191 llval: bx.pointercast(llval, field.llvm_type(cx).ptr_to()),
192 llextra: if cx.type_has_metadata(field.ty) {
198 align: effective_field_align,
202 // Simple cases, which don't need DST adjustment:
203 // * no metadata available - just log the case
204 // * known alignment - sized types, [T], str or a foreign type
205 // * packed struct - there is no alignment padding
207 _ if self.llextra.is_none() => {
208 debug!("Unsized field `{}`, of `{:?}` has no metadata for adjustment",
212 _ if !field.is_unsized() => return simple(),
213 ty::Slice(..) | ty::Str | ty::Foreign(..) => return simple(),
215 if def.repr.packed() {
216 // FIXME(eddyb) generalize the adjustment when we
217 // start supporting packing to larger alignments.
218 assert_eq!(self.layout.align.abi(), 1);
225 // We need to get the pointer manually now.
226 // We do this by casting to a *i8, then offsetting it by the appropriate amount.
227 // We do this instead of, say, simply adjusting the pointer from the result of a GEP
228 // because the field may have an arbitrary alignment in the LLVM representation
232 // struct Foo<T: ?Sized> {
237 // The type Foo<Foo<Trait>> is represented in LLVM as { u16, { u16, u8 }}, meaning that
238 // the `y` field has 16-bit alignment.
240 let meta = self.llextra;
242 let unaligned_offset = C_usize(cx, offset.bytes());
244 // Get the alignment of the field
245 let (_, unsized_align) = glue::size_and_align_of_dst(bx, field.ty, meta);
247 // Bump the unaligned offset up to the appropriate alignment using the
248 // following expression:
250 // (unaligned offset + (align - 1)) & -align
253 let align_sub_1 = bx.sub(unsized_align, C_usize(cx, 1u64));
254 let offset = bx.and(bx.add(unaligned_offset, align_sub_1),
255 bx.neg(unsized_align));
257 debug!("struct_field_ptr: DST field offset: {:?}", offset);
259 // Cast and adjust pointer
260 let byte_ptr = bx.pointercast(self.llval, Type::i8p(cx));
261 let byte_ptr = bx.gep(byte_ptr, &[offset]);
263 // Finally, cast back to the type expected
264 let ll_fty = field.llvm_type(cx);
265 debug!("struct_field_ptr: Field type is {:?}", ll_fty);
268 llval: bx.pointercast(byte_ptr, ll_fty.ptr_to()),
269 llextra: self.llextra,
271 align: effective_field_align,
275 /// Obtain the actual discriminant of a value.
276 pub fn codegen_get_discr(self, bx: &Builder<'a, 'll, 'tcx>, cast_to: Ty<'tcx>) -> &'ll Value {
277 let cast_to = bx.cx.layout_of(cast_to).immediate_llvm_type(bx.cx);
278 if self.layout.abi.is_uninhabited() {
279 return C_undef(cast_to);
281 match self.layout.variants {
282 layout::Variants::Single { index } => {
283 let discr_val = self.layout.ty.ty_adt_def().map_or(
285 |def| def.discriminant_for_variant(bx.cx.tcx, index).val);
286 return C_uint_big(cast_to, discr_val);
288 layout::Variants::Tagged { .. } |
289 layout::Variants::NicheFilling { .. } => {},
292 let discr = self.project_field(bx, 0);
293 let lldiscr = discr.load(bx).immediate();
294 match self.layout.variants {
295 layout::Variants::Single { .. } => bug!(),
296 layout::Variants::Tagged { ref tag, .. } => {
297 let signed = match tag.value {
298 // We use `i1` for bytes that are always `0` or `1`,
299 // e.g. `#[repr(i8)] enum E { A, B }`, but we can't
300 // let LLVM interpret the `i1` as signed, because
301 // then `i1 1` (i.e. E::B) is effectively `i8 -1`.
302 layout::Int(_, signed) => !tag.is_bool() && signed,
305 bx.intcast(lldiscr, cast_to, signed)
307 layout::Variants::NicheFilling {
313 let niche_llty = discr.layout.immediate_llvm_type(bx.cx);
314 if niche_variants.start() == niche_variants.end() {
315 // FIXME(eddyb) Check the actual primitive type here.
316 let niche_llval = if niche_start == 0 {
317 // HACK(eddyb) Using `C_null` as it works on all types.
320 C_uint_big(niche_llty, niche_start)
322 bx.select(bx.icmp(llvm::IntEQ, lldiscr, niche_llval),
323 C_uint(cast_to, *niche_variants.start() as u64),
324 C_uint(cast_to, dataful_variant as u64))
326 // Rebase from niche values to discriminant values.
327 let delta = niche_start.wrapping_sub(*niche_variants.start() as u128);
328 let lldiscr = bx.sub(lldiscr, C_uint_big(niche_llty, delta));
329 let lldiscr_max = C_uint(niche_llty, *niche_variants.end() as u64);
330 bx.select(bx.icmp(llvm::IntULE, lldiscr, lldiscr_max),
331 bx.intcast(lldiscr, cast_to, false),
332 C_uint(cast_to, dataful_variant as u64))
338 /// Set the discriminant for a new value of the given case of the given
340 pub fn codegen_set_discr(&self, bx: &Builder<'a, 'll, 'tcx>, variant_index: usize) {
341 if self.layout.for_variant(bx.cx, variant_index).abi.is_uninhabited() {
344 match self.layout.variants {
345 layout::Variants::Single { index } => {
346 assert_eq!(index, variant_index);
348 layout::Variants::Tagged { .. } => {
349 let ptr = self.project_field(bx, 0);
350 let to = self.layout.ty.ty_adt_def().unwrap()
351 .discriminant_for_variant(bx.tcx(), variant_index)
354 C_uint_big(ptr.layout.llvm_type(bx.cx), to),
358 layout::Variants::NicheFilling {
364 if variant_index != dataful_variant {
365 if bx.sess().target.target.arch == "arm" ||
366 bx.sess().target.target.arch == "aarch64" {
367 // Issue #34427: As workaround for LLVM bug on ARM,
368 // use memset of 0 before assigning niche value.
369 let llptr = bx.pointercast(self.llval, Type::i8(bx.cx).ptr_to());
370 let fill_byte = C_u8(bx.cx, 0);
371 let (size, align) = self.layout.size_and_align();
372 let size = C_usize(bx.cx, size.bytes());
373 let align = C_u32(bx.cx, align.abi() as u32);
374 base::call_memset(bx, llptr, fill_byte, size, align, false);
377 let niche = self.project_field(bx, 0);
378 let niche_llty = niche.layout.immediate_llvm_type(bx.cx);
379 let niche_value = ((variant_index - *niche_variants.start()) as u128)
380 .wrapping_add(niche_start);
381 // FIXME(eddyb) Check the actual primitive type here.
382 let niche_llval = if niche_value == 0 {
383 // HACK(eddyb) Using `C_null` as it works on all types.
386 C_uint_big(niche_llty, niche_value)
388 OperandValue::Immediate(niche_llval).store(bx, niche);
394 pub fn project_index(&self, bx: &Builder<'a, 'll, 'tcx>, llindex: &'ll Value)
395 -> PlaceRef<'ll, 'tcx> {
397 llval: bx.inbounds_gep(self.llval, &[C_usize(bx.cx, 0), llindex]),
399 layout: self.layout.field(bx.cx, 0),
404 pub fn project_downcast(&self, bx: &Builder<'a, 'll, 'tcx>, variant_index: usize)
405 -> PlaceRef<'ll, 'tcx> {
406 let mut downcast = *self;
407 downcast.layout = self.layout.for_variant(bx.cx, variant_index);
409 // Cast to the appropriate variant struct type.
410 let variant_ty = downcast.layout.llvm_type(bx.cx);
411 downcast.llval = bx.pointercast(downcast.llval, variant_ty.ptr_to());
416 pub fn storage_live(&self, bx: &Builder<'a, 'll, 'tcx>) {
417 bx.lifetime_start(self.llval, self.layout.size);
420 pub fn storage_dead(&self, bx: &Builder<'a, 'll, 'tcx>) {
421 bx.lifetime_end(self.llval, self.layout.size);
425 impl FunctionCx<'a, 'll, 'tcx> {
426 pub fn codegen_place(&mut self,
427 bx: &Builder<'a, 'll, 'tcx>,
428 place: &mir::Place<'tcx>)
429 -> PlaceRef<'ll, 'tcx> {
430 debug!("codegen_place(place={:?})", place);
435 if let mir::Place::Local(index) = *place {
436 match self.locals[index] {
437 LocalRef::Place(place) => {
440 LocalRef::UnsizedPlace(place) => {
441 return place.load(bx).deref(&cx);
443 LocalRef::Operand(..) => {
444 bug!("using operand local {:?} as place", place);
449 let result = match *place {
450 mir::Place::Local(_) => bug!(), // handled above
451 mir::Place::Promoted(box (index, ty)) => {
452 let param_env = ty::ParamEnv::reveal_all();
453 let cid = mir::interpret::GlobalId {
454 instance: self.instance,
455 promoted: Some(index),
457 let layout = cx.layout_of(self.monomorphize(&ty));
458 match bx.tcx().const_eval(param_env.and(cid)) {
459 Ok(val) => match val.val {
460 mir::interpret::ConstValue::ByRef(_, alloc, offset) => {
461 PlaceRef::from_const_alloc(bx, layout, alloc, offset)
463 _ => bug!("promoteds should have an allocation: {:?}", val),
466 // this is unreachable as long as runtime
467 // and compile-time agree on values
468 // With floats that won't always be true
469 // so we generate an abort
470 let fnname = bx.cx.get_intrinsic(&("llvm.trap"));
471 bx.call(fnname, &[], None);
472 let llval = C_undef(layout.llvm_type(bx.cx).ptr_to());
473 PlaceRef::new_sized(llval, layout, layout.align)
477 mir::Place::Static(box mir::Static { def_id, ty }) => {
478 let layout = cx.layout_of(self.monomorphize(&ty));
479 PlaceRef::new_sized(consts::get_static(cx, def_id), layout, layout.align)
481 mir::Place::Projection(box mir::Projection {
483 elem: mir::ProjectionElem::Deref
485 // Load the pointer from its location.
486 self.codegen_consume(bx, base).deref(bx.cx)
488 mir::Place::Projection(ref projection) => {
489 let cg_base = self.codegen_place(bx, &projection.base);
491 match projection.elem {
492 mir::ProjectionElem::Deref => bug!(),
493 mir::ProjectionElem::Field(ref field, _) => {
494 cg_base.project_field(bx, field.index())
496 mir::ProjectionElem::Index(index) => {
497 let index = &mir::Operand::Copy(mir::Place::Local(index));
498 let index = self.codegen_operand(bx, index);
499 let llindex = index.immediate();
500 cg_base.project_index(bx, llindex)
502 mir::ProjectionElem::ConstantIndex { offset,
505 let lloffset = C_usize(bx.cx, offset as u64);
506 cg_base.project_index(bx, lloffset)
508 mir::ProjectionElem::ConstantIndex { offset,
511 let lloffset = C_usize(bx.cx, offset as u64);
512 let lllen = cg_base.len(bx.cx);
513 let llindex = bx.sub(lllen, lloffset);
514 cg_base.project_index(bx, llindex)
516 mir::ProjectionElem::Subslice { from, to } => {
517 let mut subslice = cg_base.project_index(bx,
518 C_usize(bx.cx, from as u64));
519 let projected_ty = PlaceTy::Ty { ty: cg_base.layout.ty }
520 .projection_ty(tcx, &projection.elem).to_ty(bx.tcx());
521 subslice.layout = bx.cx.layout_of(self.monomorphize(&projected_ty));
523 if subslice.layout.is_unsized() {
524 subslice.llextra = Some(bx.sub(cg_base.llextra.unwrap(),
525 C_usize(bx.cx, (from as u64) + (to as u64))));
528 // Cast the place pointer type to the new
529 // array or slice type (*[%_; new_len]).
530 subslice.llval = bx.pointercast(subslice.llval,
531 subslice.layout.llvm_type(bx.cx).ptr_to());
535 mir::ProjectionElem::Downcast(_, v) => {
536 cg_base.project_downcast(bx, v)
541 debug!("codegen_place(place={:?}) => {:?}", place, result);
545 pub fn monomorphized_place_ty(&self, place: &mir::Place<'tcx>) -> Ty<'tcx> {
546 let tcx = self.cx.tcx;
547 let place_ty = place.ty(self.mir, tcx);
548 self.monomorphize(&place_ty.to_ty(tcx))