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;
16 use rustc_data_structures::indexed_vec::Idx;
19 use common::{CodegenCx, C_undef, C_usize, C_u8, C_u32, C_uint, C_null, C_uint_big};
21 use type_of::LayoutLlvmExt;
25 use mir::constant::const_alloc_to_llvm;
27 use super::{FunctionCx, LocalRef};
28 use super::operand::{OperandRef, OperandValue};
30 #[derive(Copy, Clone, Debug)]
31 pub struct PlaceRef<'ll, 'tcx> {
32 /// Pointer to the contents of the place
33 pub llval: &'ll Value,
35 /// This place's extra data if it is unsized, or null
36 pub llextra: Option<&'ll Value>,
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<'ll, 'tcx> {
48 layout: TyLayout<'tcx>,
50 ) -> PlaceRef<'ll, 'tcx> {
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, "byte_str");
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 let tmp = bx.alloca(layout.llvm_type(bx.cx), name, layout.align);
81 Self::new_sized(tmp, layout, layout.align)
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() {
93 bug!("unexpected layout `{:#?}` in PlaceRef::len", self.layout)
97 pub fn load(&self, bx: &Builder<'a, 'll, 'tcx>) -> OperandRef<'ll, 'tcx> {
98 debug!("PlaceRef::load: {:?}", self);
100 assert_eq!(self.llextra, None);
102 if self.layout.is_zst() {
103 return OperandRef::new_zst(bx.cx, self.layout);
106 let scalar_load_metadata = |load, scalar: &layout::Scalar| {
107 let vr = scalar.valid_range.clone();
110 let range = scalar.valid_range_exclusive(bx.cx);
111 if range.start != range.end {
112 bx.range_metadata(load, range);
115 layout::Pointer if vr.start() < vr.end() && !vr.contains(&0) => {
116 bx.nonnull_metadata(load);
122 let val = if self.layout.is_llvm_immediate() {
123 let mut const_llval = None;
125 if let Some(global) = llvm::LLVMIsAGlobalVariable(self.llval) {
126 if llvm::LLVMIsGlobalConstant(global) == llvm::True {
127 const_llval = llvm::LLVMGetInitializer(global);
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);
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))
150 OperandValue::Pair(load(0, a), load(1, b))
152 OperandValue::Ref(self.llval, self.align)
155 OperandRef { val, layout: self.layout }
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> {
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);
166 // Unions and newtypes only use an offset of 0.
167 let llval = if offset.bytes() == 0 {
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)
174 bx.struct_gep(self.llval, self.layout.llvm_field_index(ix))
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) {
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
194 _ if self.llextra.is_none() => {
195 debug!("Unsized field `{}`, of `{:?}` has no metadata for adjustment",
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);
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
219 // struct Foo<T: ?Sized> {
224 // The type Foo<Foo<Trait>> is represented in LLVM as { u16, { u16, u8 }}, meaning that
225 // the `y` field has 16-bit alignment.
227 let meta = self.llextra;
229 let unaligned_offset = C_usize(cx, offset.bytes());
231 // Get the alignment of the field
232 let (_, unsized_align) = glue::size_and_align_of_dst(bx, field.ty, meta);
234 // Bump the unaligned offset up to the appropriate alignment using the
235 // following expression:
237 // (unaligned offset + (align - 1)) & -align
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));
244 debug!("struct_field_ptr: DST field offset: {:?}", offset);
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]);
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);
255 llval: bx.pointercast(byte_ptr, ll_fty.ptr_to()),
256 llextra: self.llextra,
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);
268 match self.layout.variants {
269 layout::Variants::Single { index } => {
270 let discr_val = self.layout.ty.ty_adt_def().map_or(
272 |def| def.discriminant_for_variant(bx.cx.tcx, index).val);
273 return C_uint_big(cast_to, discr_val);
275 layout::Variants::Tagged { .. } |
276 layout::Variants::NicheFilling { .. } => {},
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,
292 bx.intcast(lldiscr, cast_to, signed)
294 layout::Variants::NicheFilling {
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.
307 C_uint_big(niche_llty, niche_start)
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))
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))
325 /// Set the discriminant for a new value of the given case of the given
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 {
331 match self.layout.variants {
332 layout::Variants::Single { index } => {
333 assert_eq!(index, variant_index);
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)
341 C_uint_big(ptr.layout.llvm_type(bx.cx), to),
345 layout::Variants::NicheFilling {
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);
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.
373 C_uint_big(niche_llty, niche_value)
375 OperandValue::Immediate(niche_llval).store(bx, niche);
381 pub fn project_index(&self, bx: &Builder<'a, 'll, 'tcx>, llindex: &'ll Value)
382 -> PlaceRef<'ll, 'tcx> {
384 llval: bx.inbounds_gep(self.llval, &[C_usize(bx.cx, 0), llindex]),
386 layout: self.layout.field(bx.cx, 0),
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);
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());
403 pub fn storage_live(&self, bx: &Builder<'a, 'll, 'tcx>) {
404 bx.lifetime_start(self.llval, self.layout.size);
407 pub fn storage_dead(&self, bx: &Builder<'a, 'll, 'tcx>) {
408 bx.lifetime_end(self.llval, self.layout.size);
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);
422 if let mir::Place::Local(index) = *place {
423 match self.locals[index] {
424 LocalRef::Place(place) => {
427 LocalRef::Operand(..) => {
428 bug!("using operand local {:?} as place", place);
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),
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)
447 _ => bug!("promoteds should have an allocation: {:?}", val),
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)
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)
465 mir::Place::Projection(box mir::Projection {
467 elem: mir::ProjectionElem::Deref
469 // Load the pointer from its location.
470 self.codegen_consume(bx, base).deref(bx.cx)
472 mir::Place::Projection(ref projection) => {
473 let cg_base = self.codegen_place(bx, &projection.base);
475 match projection.elem {
476 mir::ProjectionElem::Deref => bug!(),
477 mir::ProjectionElem::Field(ref field, _) => {
478 cg_base.project_field(bx, field.index())
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)
486 mir::ProjectionElem::ConstantIndex { offset,
489 let lloffset = C_usize(bx.cx, offset as u64);
490 cg_base.project_index(bx, lloffset)
492 mir::ProjectionElem::ConstantIndex { offset,
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)
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));
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))));
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());
519 mir::ProjectionElem::Downcast(_, v) => {
520 cg_base.project_downcast(bx, v)
525 debug!("codegen_place(place={:?}) => {:?}", place, result);
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))