1 // Copyright 2012-2013 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 abi::{FnType, FnTypeExt};
14 use rustc::ty::{self, Ty, TypeFoldable};
15 use rustc::ty::layout::{self, Align, LayoutOf, Size, TyLayout};
16 use rustc_target::abi::FloatTy;
17 use rustc_mir::monomorphize::item::DefPathBasedNames;
22 fn uncached_llvm_type<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
23 layout: TyLayout<'tcx>,
24 defer: &mut Option<(&'a Type, TyLayout<'tcx>)>)
27 layout::Abi::Scalar(_) => bug!("handled elsewhere"),
28 layout::Abi::Vector { ref element, count } => {
29 // LLVM has a separate type for 64-bit SIMD vectors on X86 called
30 // `x86_mmx` which is needed for some SIMD operations. As a bit of a
31 // hack (all SIMD definitions are super unstable anyway) we
32 // recognize any one-element SIMD vector as "this should be an
33 // x86_mmx" type. In general there shouldn't be a need for other
34 // one-element SIMD vectors, so it's assumed this won't clash with
36 let use_x86_mmx = count == 1 && layout.size.bits() == 64 &&
37 (cx.sess().target.target.arch == "x86" ||
38 cx.sess().target.target.arch == "x86_64");
40 return Type::x86_mmx(cx)
42 let element = layout.scalar_llvm_type_at(cx, element, Size::ZERO);
43 return Type::vector(element, count);
46 layout::Abi::ScalarPair(..) => {
47 return Type::struct_(cx, &[
48 layout.scalar_pair_element_llvm_type(cx, 0, false),
49 layout.scalar_pair_element_llvm_type(cx, 1, false),
52 layout::Abi::Uninhabited |
53 layout::Abi::Aggregate { .. } => {}
56 let name = match layout.ty.sty {
60 // FIXME(eddyb) producing readable type names for trait objects can result
61 // in problematically distinct types due to HRTB and subtyping (see #47638).
65 let mut name = String::with_capacity(32);
66 let printer = DefPathBasedNames::new(cx.tcx, true, true);
67 printer.push_type_name(layout.ty, &mut name);
68 if let (&ty::Adt(def, _), &layout::Variants::Single { index })
69 = (&layout.ty.sty, &layout.variants)
71 if def.is_enum() && !def.variants.is_empty() {
72 write!(&mut name, "::{}", def.variants[index].name).unwrap();
81 layout::FieldPlacement::Union(_) => {
82 let fill = Type::padding_filler(cx, layout.size, layout.align);
86 Type::struct_(cx, &[fill], packed)
89 let llty = Type::named_struct(cx, name);
90 llty.set_struct_body(&[fill], packed);
95 layout::FieldPlacement::Array { count, .. } => {
96 Type::array(layout.field(cx, 0).llvm_type(cx), count)
98 layout::FieldPlacement::Arbitrary { .. } => {
101 let (llfields, packed) = struct_llfields(cx, layout);
102 Type::struct_(cx, &llfields, packed)
105 let llty = Type::named_struct(cx, name);
106 *defer = Some((llty, layout));
114 fn struct_llfields<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
115 layout: TyLayout<'tcx>)
116 -> (Vec<&'a Type>, bool) {
117 debug!("struct_llfields: {:#?}", layout);
118 let field_count = layout.fields.count();
120 let mut packed = false;
121 let mut offset = Size::ZERO;
122 let mut prev_effective_align = layout.align;
123 let mut result: Vec<_> = Vec::with_capacity(1 + field_count * 2);
124 for i in layout.fields.index_by_increasing_offset() {
125 let target_offset = layout.fields.offset(i as usize);
126 let field = layout.field(cx, i);
127 let effective_field_align = layout.align
129 .restrict_for_offset(target_offset);
130 packed |= effective_field_align.abi() < field.align.abi();
132 debug!("struct_llfields: {}: {:?} offset: {:?} target_offset: {:?} \
133 effective_field_align: {}",
134 i, field, offset, target_offset, effective_field_align.abi());
135 assert!(target_offset >= offset);
136 let padding = target_offset - offset;
137 let padding_align = prev_effective_align.min(effective_field_align);
138 assert_eq!(offset.abi_align(padding_align) + padding, target_offset);
139 result.push(Type::padding_filler(cx, padding, padding_align));
140 debug!(" padding before: {:?}", padding);
142 result.push(field.llvm_type(cx));
143 offset = target_offset + field.size;
144 prev_effective_align = effective_field_align;
146 if !layout.is_unsized() && field_count > 0 {
147 if offset > layout.size {
148 bug!("layout: {:#?} stride: {:?} offset: {:?}",
149 layout, layout.size, offset);
151 let padding = layout.size - offset;
152 let padding_align = prev_effective_align;
153 assert_eq!(offset.abi_align(padding_align) + padding, layout.size);
154 debug!("struct_llfields: pad_bytes: {:?} offset: {:?} stride: {:?}",
155 padding, offset, layout.size);
156 result.push(Type::padding_filler(cx, padding, padding_align));
157 assert_eq!(result.len(), 1 + field_count * 2);
159 debug!("struct_llfields: offset: {:?} stride: {:?}",
160 offset, layout.size);
166 impl<'a, 'tcx> CodegenCx<'a, 'tcx> {
167 pub fn align_of(&self, ty: Ty<'tcx>) -> Align {
168 self.layout_of(ty).align
171 pub fn size_of(&self, ty: Ty<'tcx>) -> Size {
172 self.layout_of(ty).size
175 pub fn size_and_align_of(&self, ty: Ty<'tcx>) -> (Size, Align) {
176 self.layout_of(ty).size_and_align()
180 #[derive(Copy, Clone, PartialEq, Eq)]
181 pub enum PointerKind {
182 /// Most general case, we know no restrictions to tell LLVM.
185 /// `&T` where `T` contains no `UnsafeCell`, is `noalias` and `readonly`.
188 /// `&mut T`, when we know `noalias` is safe for LLVM.
191 /// `Box<T>`, unlike `UniqueBorrowed`, it also has `noalias` on returns.
195 #[derive(Copy, Clone)]
196 pub struct PointeeInfo {
199 pub safe: Option<PointerKind>,
202 pub trait LayoutLlvmExt<'tcx> {
203 fn is_llvm_immediate(&self) -> bool;
204 fn is_llvm_scalar_pair<'a>(&self) -> bool;
205 fn llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type;
206 fn immediate_llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type;
207 fn scalar_llvm_type_at<'a>(&self, cx: &CodegenCx<'a, 'tcx>,
208 scalar: &layout::Scalar, offset: Size) -> &'a Type;
209 fn scalar_pair_element_llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>,
210 index: usize, immediate: bool) -> &'a Type;
211 fn llvm_field_index(&self, index: usize) -> u64;
212 fn pointee_info_at<'a>(&self, cx: &CodegenCx<'a, 'tcx>, offset: Size)
213 -> Option<PointeeInfo>;
216 impl<'tcx> LayoutLlvmExt<'tcx> for TyLayout<'tcx> {
217 fn is_llvm_immediate(&self) -> bool {
219 layout::Abi::Scalar(_) |
220 layout::Abi::Vector { .. } => true,
221 layout::Abi::ScalarPair(..) => false,
222 layout::Abi::Uninhabited |
223 layout::Abi::Aggregate { .. } => self.is_zst()
227 fn is_llvm_scalar_pair<'a>(&self) -> bool {
229 layout::Abi::ScalarPair(..) => true,
230 layout::Abi::Uninhabited |
231 layout::Abi::Scalar(_) |
232 layout::Abi::Vector { .. } |
233 layout::Abi::Aggregate { .. } => false
237 /// Get the LLVM type corresponding to a Rust type, i.e. `rustc::ty::Ty`.
238 /// The pointee type of the pointer in `PlaceRef` is always this type.
239 /// For sized types, it is also the right LLVM type for an `alloca`
240 /// containing a value of that type, and most immediates (except `bool`).
241 /// Unsized types, however, are represented by a "minimal unit", e.g.
242 /// `[T]` becomes `T`, while `str` and `Trait` turn into `i8` - this
243 /// is useful for indexing slices, as `&[T]`'s data pointer is `T*`.
244 /// If the type is an unsized struct, the regular layout is generated,
245 /// with the inner-most trailing unsized field using the "minimal unit"
246 /// of that field's type - this is useful for taking the address of
247 /// that field and ensuring the struct has the right alignment.
248 fn llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type {
249 if let layout::Abi::Scalar(ref scalar) = self.abi {
250 // Use a different cache for scalars because pointers to DSTs
251 // can be either fat or thin (data pointers of fat pointers).
252 if let Some(&llty) = cx.scalar_lltypes.borrow().get(&self.ty) {
255 let llty = match self.ty.sty {
257 ty::RawPtr(ty::TypeAndMut { ty, .. }) => {
258 cx.layout_of(ty).llvm_type(cx).ptr_to()
260 ty::Adt(def, _) if def.is_box() => {
261 cx.layout_of(self.ty.boxed_ty()).llvm_type(cx).ptr_to()
264 let sig = cx.tcx.normalize_erasing_late_bound_regions(
265 ty::ParamEnv::reveal_all(),
268 FnType::new(cx, sig, &[]).llvm_type(cx).ptr_to()
270 _ => self.scalar_llvm_type_at(cx, scalar, Size::ZERO)
272 cx.scalar_lltypes.borrow_mut().insert(self.ty, llty);
278 let variant_index = match self.variants {
279 layout::Variants::Single { index } => Some(index),
282 if let Some(&llty) = cx.lltypes.borrow().get(&(self.ty, variant_index)) {
286 debug!("llvm_type({:#?})", self);
288 assert!(!self.ty.has_escaping_bound_vars(), "{:?} has escaping bound vars", self.ty);
290 // Make sure lifetimes are erased, to avoid generating distinct LLVM
291 // types for Rust types that only differ in the choice of lifetimes.
292 let normal_ty = cx.tcx.erase_regions(&self.ty);
294 let mut defer = None;
295 let llty = if self.ty != normal_ty {
296 let mut layout = cx.layout_of(normal_ty);
297 if let Some(v) = variant_index {
298 layout = layout.for_variant(cx, v);
302 uncached_llvm_type(cx, *self, &mut defer)
304 debug!("--> mapped {:#?} to llty={:?}", self, llty);
306 cx.lltypes.borrow_mut().insert((self.ty, variant_index), llty);
308 if let Some((llty, layout)) = defer {
309 let (llfields, packed) = struct_llfields(cx, layout);
310 llty.set_struct_body(&llfields, packed)
316 fn immediate_llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type {
317 if let layout::Abi::Scalar(ref scalar) = self.abi {
318 if scalar.is_bool() {
325 fn scalar_llvm_type_at<'a>(&self, cx: &CodegenCx<'a, 'tcx>,
326 scalar: &layout::Scalar, offset: Size) -> &'a Type {
328 layout::Int(i, _) => Type::from_integer(cx, i),
329 layout::Float(FloatTy::F32) => Type::f32(cx),
330 layout::Float(FloatTy::F64) => Type::f64(cx),
332 // If we know the alignment, pick something better than i8.
333 let pointee = if let Some(pointee) = self.pointee_info_at(cx, offset) {
334 Type::pointee_for_abi_align(cx, pointee.align)
343 fn scalar_pair_element_llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>,
344 index: usize, immediate: bool) -> &'a Type {
345 // HACK(eddyb) special-case fat pointers until LLVM removes
346 // pointee types, to avoid bitcasting every `OperandRef::deref`.
350 return self.field(cx, index).llvm_type(cx);
352 ty::Adt(def, _) if def.is_box() => {
353 let ptr_ty = cx.tcx.mk_mut_ptr(self.ty.boxed_ty());
354 return cx.layout_of(ptr_ty).scalar_pair_element_llvm_type(cx, index, immediate);
359 let (a, b) = match self.abi {
360 layout::Abi::ScalarPair(ref a, ref b) => (a, b),
361 _ => bug!("TyLayout::scalar_pair_element_llty({:?}): not applicable", self)
363 let scalar = [a, b][index];
365 // Make sure to return the same type `immediate_llvm_type` would when
366 // dealing with an immediate pair. This means that `(bool, bool)` is
367 // effectively represented as `{i8, i8}` in memory and two `i1`s as an
368 // immediate, just like `bool` is typically `i8` in memory and only `i1`
369 // when immediate. We need to load/store `bool` as `i8` to avoid
370 // crippling LLVM optimizations or triggering other LLVM bugs with `i1`.
371 if immediate && scalar.is_bool() {
375 let offset = if index == 0 {
378 a.value.size(cx).abi_align(b.value.align(cx))
380 self.scalar_llvm_type_at(cx, scalar, offset)
383 fn llvm_field_index(&self, index: usize) -> u64 {
385 layout::Abi::Scalar(_) |
386 layout::Abi::ScalarPair(..) => {
387 bug!("TyLayout::llvm_field_index({:?}): not applicable", self)
392 layout::FieldPlacement::Union(_) => {
393 bug!("TyLayout::llvm_field_index({:?}): not applicable", self)
396 layout::FieldPlacement::Array { .. } => {
400 layout::FieldPlacement::Arbitrary { .. } => {
401 1 + (self.fields.memory_index(index) as u64) * 2
406 fn pointee_info_at<'a>(&self, cx: &CodegenCx<'a, 'tcx>, offset: Size)
407 -> Option<PointeeInfo> {
408 if let Some(&pointee) = cx.pointee_infos.borrow().get(&(self.ty, offset)) {
412 let mut result = None;
414 ty::RawPtr(mt) if offset.bytes() == 0 => {
415 let (size, align) = cx.size_and_align_of(mt.ty);
416 result = Some(PointeeInfo {
423 ty::Ref(_, ty, mt) if offset.bytes() == 0 => {
424 let (size, align) = cx.size_and_align_of(ty);
426 let kind = match mt {
427 hir::MutImmutable => if cx.type_is_freeze(ty) {
433 // Previously we would only emit noalias annotations for LLVM >= 6 or in
434 // panic=abort mode. That was deemed right, as prior versions had many bugs
435 // in conjunction with unwinding, but later versions didn’t seem to have
436 // said issues. See issue #31681.
438 // Alas, later on we encountered a case where noalias would generate wrong
439 // code altogether even with recent versions of LLVM in *safe* code with no
440 // unwinding involved. See #54462.
442 // For now, do not enable mutable_noalias by default at all, while the
443 // issue is being figured out.
444 let mutable_noalias = cx.tcx.sess.opts.debugging_opts.mutable_noalias
447 PointerKind::UniqueBorrowed
454 result = Some(PointeeInfo {
462 let mut data_variant = match self.variants {
463 layout::Variants::NicheFilling { dataful_variant, .. } => {
464 // Only the niche itself is always initialized,
465 // so only check for a pointer at its offset.
467 // If the niche is a pointer, it's either valid
468 // (according to its type), or null (which the
469 // niche field's scalar validity range encodes).
470 // This allows using `dereferenceable_or_null`
471 // for e.g. `Option<&T>`, and this will continue
472 // to work as long as we don't start using more
473 // niches than just null (e.g. the first page
474 // of the address space, or unaligned pointers).
475 if self.fields.offset(0) == offset {
476 Some(self.for_variant(cx, dataful_variant))
484 if let Some(variant) = data_variant {
485 // We're not interested in any unions.
486 if let layout::FieldPlacement::Union(_) = variant.fields {
491 if let Some(variant) = data_variant {
492 let ptr_end = offset + layout::Pointer.size(cx);
493 for i in 0..variant.fields.count() {
494 let field_start = variant.fields.offset(i);
495 if field_start <= offset {
496 let field = variant.field(cx, i);
497 if ptr_end <= field_start + field.size {
498 // We found the right field, look inside it.
499 result = field.pointee_info_at(cx, offset - field_start);
506 // FIXME(eddyb) This should be for `ptr::Unique<T>`, not `Box<T>`.
507 if let Some(ref mut pointee) = result {
508 if let ty::Adt(def, _) = self.ty.sty {
509 if def.is_box() && offset.bytes() == 0 {
510 pointee.safe = Some(PointerKind::UniqueOwned);
517 cx.pointee_infos.borrow_mut().insert((self.ty, offset), result);