3 use crate::type_::Type;
6 use rustc::ty::layout::{self, Align, FnAbiExt, LayoutOf, PointeeInfo, Size, TyLayout};
7 use rustc::ty::print::obsolete::DefPathBasedNames;
8 use rustc::ty::{self, Ty, TypeFoldable};
9 use rustc_codegen_ssa::traits::*;
10 use rustc_target::abi::TyLayoutMethods;
14 fn uncached_llvm_type<'a, 'tcx>(
15 cx: &CodegenCx<'a, 'tcx>,
16 layout: TyLayout<'tcx>,
17 defer: &mut Option<(&'a Type, TyLayout<'tcx>)>,
20 layout::Abi::Scalar(_) => bug!("handled elsewhere"),
21 layout::Abi::Vector { ref element, count } => {
22 // LLVM has a separate type for 64-bit SIMD vectors on X86 called
23 // `x86_mmx` which is needed for some SIMD operations. As a bit of a
24 // hack (all SIMD definitions are super unstable anyway) we
25 // recognize any one-element SIMD vector as "this should be an
26 // x86_mmx" type. In general there shouldn't be a need for other
27 // one-element SIMD vectors, so it's assumed this won't clash with
29 let use_x86_mmx = count == 1
30 && layout.size.bits() == 64
31 && (cx.sess().target.target.arch == "x86"
32 || cx.sess().target.target.arch == "x86_64");
34 return cx.type_x86_mmx();
36 let element = layout.scalar_llvm_type_at(cx, element, Size::ZERO);
37 return cx.type_vector(element, count);
40 layout::Abi::ScalarPair(..) => {
41 return cx.type_struct(
43 layout.scalar_pair_element_llvm_type(cx, 0, false),
44 layout.scalar_pair_element_llvm_type(cx, 1, false),
49 layout::Abi::Uninhabited | layout::Abi::Aggregate { .. } => {}
52 let name = match layout.ty.kind {
56 // FIXME(eddyb) producing readable type names for trait objects can result
57 // in problematically distinct types due to HRTB and subtyping (see #47638).
61 let mut name = String::with_capacity(32);
62 let printer = DefPathBasedNames::new(cx.tcx, true, true);
63 printer.push_type_name(layout.ty, &mut name, false);
64 if let (&ty::Adt(def, _), &layout::Variants::Single { index })
65 = (&layout.ty.kind, &layout.variants)
67 if def.is_enum() && !def.variants.is_empty() {
68 write!(&mut name, "::{}", def.variants[index].ident).unwrap();
71 if let (&ty::Generator(_, substs, _), &layout::Variants::Single { index })
72 = (&layout.ty.kind, &layout.variants)
74 write!(&mut name, "::{}", substs.as_generator().variant_name(index)).unwrap();
82 layout::FieldPlacement::Union(_) => {
83 let fill = cx.type_padding_filler(layout.size, layout.align.abi);
86 None => cx.type_struct(&[fill], packed),
88 let llty = cx.type_named_struct(name);
89 cx.set_struct_body(llty, &[fill], packed);
94 layout::FieldPlacement::Array { count, .. } => {
95 cx.type_array(layout.field(cx, 0).llvm_type(cx), count)
97 layout::FieldPlacement::Arbitrary { .. } => match name {
99 let (llfields, packed) = struct_llfields(cx, layout);
100 cx.type_struct(&llfields, packed)
103 let llty = cx.type_named_struct(name);
104 *defer = Some((llty, layout));
111 fn struct_llfields<'a, 'tcx>(
112 cx: &CodegenCx<'a, 'tcx>,
113 layout: TyLayout<'tcx>,
114 ) -> (Vec<&'a Type>, bool) {
115 debug!("struct_llfields: {:#?}", layout);
116 let field_count = layout.fields.count();
118 let mut packed = false;
119 let mut offset = Size::ZERO;
120 let mut prev_effective_align = layout.align.abi;
121 let mut result: Vec<_> = Vec::with_capacity(1 + field_count * 2);
122 for i in layout.fields.index_by_increasing_offset() {
123 let target_offset = layout.fields.offset(i as usize);
124 let field = layout.field(cx, i);
125 let effective_field_align =
126 layout.align.abi.min(field.align.abi).restrict_for_offset(target_offset);
127 packed |= effective_field_align < field.align.abi;
130 "struct_llfields: {}: {:?} offset: {:?} target_offset: {:?} \
131 effective_field_align: {}",
136 effective_field_align.bytes()
138 assert!(target_offset >= offset);
139 let padding = target_offset - offset;
140 let padding_align = prev_effective_align.min(effective_field_align);
141 assert_eq!(offset.align_to(padding_align) + padding, target_offset);
142 result.push(cx.type_padding_filler(padding, padding_align));
143 debug!(" padding before: {:?}", padding);
145 result.push(field.llvm_type(cx));
146 offset = target_offset + field.size;
147 prev_effective_align = effective_field_align;
149 if !layout.is_unsized() && field_count > 0 {
150 if offset > layout.size {
151 bug!("layout: {:#?} stride: {:?} offset: {:?}", layout, layout.size, offset);
153 let padding = layout.size - offset;
154 let padding_align = prev_effective_align;
155 assert_eq!(offset.align_to(padding_align) + padding, layout.size);
157 "struct_llfields: pad_bytes: {:?} offset: {:?} stride: {:?}",
158 padding, offset, layout.size
160 result.push(cx.type_padding_filler(padding, padding_align));
161 assert_eq!(result.len(), 1 + field_count * 2);
163 debug!("struct_llfields: offset: {:?} stride: {:?}", offset, layout.size);
169 impl<'a, 'tcx> CodegenCx<'a, 'tcx> {
170 pub fn align_of(&self, ty: Ty<'tcx>) -> Align {
171 self.layout_of(ty).align.abi
174 pub fn size_of(&self, ty: Ty<'tcx>) -> Size {
175 self.layout_of(ty).size
178 pub fn size_and_align_of(&self, ty: Ty<'tcx>) -> (Size, Align) {
179 let layout = self.layout_of(ty);
180 (layout.size, layout.align.abi)
184 pub trait LayoutLlvmExt<'tcx> {
185 fn is_llvm_immediate(&self) -> bool;
186 fn is_llvm_scalar_pair(&self) -> bool;
187 fn llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type;
188 fn immediate_llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type;
189 fn scalar_llvm_type_at<'a>(
191 cx: &CodegenCx<'a, 'tcx>,
192 scalar: &layout::Scalar,
195 fn scalar_pair_element_llvm_type<'a>(
197 cx: &CodegenCx<'a, 'tcx>,
201 fn llvm_field_index(&self, index: usize) -> u64;
202 fn pointee_info_at<'a>(&self, cx: &CodegenCx<'a, 'tcx>, offset: Size) -> Option<PointeeInfo>;
205 impl<'tcx> LayoutLlvmExt<'tcx> for TyLayout<'tcx> {
206 fn is_llvm_immediate(&self) -> bool {
208 layout::Abi::Scalar(_) | layout::Abi::Vector { .. } => true,
209 layout::Abi::ScalarPair(..) => false,
210 layout::Abi::Uninhabited | layout::Abi::Aggregate { .. } => self.is_zst(),
214 fn is_llvm_scalar_pair(&self) -> bool {
216 layout::Abi::ScalarPair(..) => true,
217 layout::Abi::Uninhabited
218 | layout::Abi::Scalar(_)
219 | layout::Abi::Vector { .. }
220 | layout::Abi::Aggregate { .. } => false,
224 /// Gets the LLVM type corresponding to a Rust type, i.e., `rustc::ty::Ty`.
225 /// The pointee type of the pointer in `PlaceRef` is always this type.
226 /// For sized types, it is also the right LLVM type for an `alloca`
227 /// containing a value of that type, and most immediates (except `bool`).
228 /// Unsized types, however, are represented by a "minimal unit", e.g.
229 /// `[T]` becomes `T`, while `str` and `Trait` turn into `i8` - this
230 /// is useful for indexing slices, as `&[T]`'s data pointer is `T*`.
231 /// If the type is an unsized struct, the regular layout is generated,
232 /// with the inner-most trailing unsized field using the "minimal unit"
233 /// of that field's type - this is useful for taking the address of
234 /// that field and ensuring the struct has the right alignment.
235 fn llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type {
236 if let layout::Abi::Scalar(ref scalar) = self.abi {
237 // Use a different cache for scalars because pointers to DSTs
238 // can be either fat or thin (data pointers of fat pointers).
239 if let Some(&llty) = cx.scalar_lltypes.borrow().get(&self.ty) {
242 let llty = match self.ty.kind {
243 ty::Ref(_, ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) => {
244 cx.type_ptr_to(cx.layout_of(ty).llvm_type(cx))
246 ty::Adt(def, _) if def.is_box() => {
247 cx.type_ptr_to(cx.layout_of(self.ty.boxed_ty()).llvm_type(cx))
249 ty::FnPtr(sig) => cx.fn_ptr_backend_type(&FnAbi::of_fn_ptr(cx, sig, &[])),
250 _ => self.scalar_llvm_type_at(cx, scalar, Size::ZERO),
252 cx.scalar_lltypes.borrow_mut().insert(self.ty, llty);
257 let variant_index = match self.variants {
258 layout::Variants::Single { index } => Some(index),
261 if let Some(&llty) = cx.lltypes.borrow().get(&(self.ty, variant_index)) {
265 debug!("llvm_type({:#?})", self);
267 assert!(!self.ty.has_escaping_bound_vars(), "{:?} has escaping bound vars", self.ty);
269 // Make sure lifetimes are erased, to avoid generating distinct LLVM
270 // types for Rust types that only differ in the choice of lifetimes.
271 let normal_ty = cx.tcx.erase_regions(&self.ty);
273 let mut defer = None;
274 let llty = if self.ty != normal_ty {
275 let mut layout = cx.layout_of(normal_ty);
276 if let Some(v) = variant_index {
277 layout = layout.for_variant(cx, v);
281 uncached_llvm_type(cx, *self, &mut defer)
283 debug!("--> mapped {:#?} to llty={:?}", self, llty);
285 cx.lltypes.borrow_mut().insert((self.ty, variant_index), llty);
287 if let Some((llty, layout)) = defer {
288 let (llfields, packed) = struct_llfields(cx, layout);
289 cx.set_struct_body(llty, &llfields, packed)
295 fn immediate_llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type {
296 if let layout::Abi::Scalar(ref scalar) = self.abi {
297 if scalar.is_bool() {
304 fn scalar_llvm_type_at<'a>(
306 cx: &CodegenCx<'a, 'tcx>,
307 scalar: &layout::Scalar,
311 layout::Int(i, _) => cx.type_from_integer(i),
312 layout::F32 => cx.type_f32(),
313 layout::F64 => cx.type_f64(),
315 // If we know the alignment, pick something better than i8.
316 let pointee = if let Some(pointee) = self.pointee_info_at(cx, offset) {
317 cx.type_pointee_for_align(pointee.align)
321 cx.type_ptr_to(pointee)
326 fn scalar_pair_element_llvm_type<'a>(
328 cx: &CodegenCx<'a, 'tcx>,
332 // HACK(eddyb) special-case fat pointers until LLVM removes
333 // pointee types, to avoid bitcasting every `OperandRef::deref`.
335 ty::Ref(..) | ty::RawPtr(_) => {
336 return self.field(cx, index).llvm_type(cx);
338 ty::Adt(def, _) if def.is_box() => {
339 let ptr_ty = cx.tcx.mk_mut_ptr(self.ty.boxed_ty());
340 return cx.layout_of(ptr_ty).scalar_pair_element_llvm_type(cx, index, immediate);
345 let (a, b) = match self.abi {
346 layout::Abi::ScalarPair(ref a, ref b) => (a, b),
347 _ => bug!("TyLayout::scalar_pair_element_llty({:?}): not applicable", self),
349 let scalar = [a, b][index];
351 // Make sure to return the same type `immediate_llvm_type` would when
352 // dealing with an immediate pair. This means that `(bool, bool)` is
353 // effectively represented as `{i8, i8}` in memory and two `i1`s as an
354 // immediate, just like `bool` is typically `i8` in memory and only `i1`
355 // when immediate. We need to load/store `bool` as `i8` to avoid
356 // crippling LLVM optimizations or triggering other LLVM bugs with `i1`.
357 if immediate && scalar.is_bool() {
362 if index == 0 { Size::ZERO } else { a.value.size(cx).align_to(b.value.align(cx).abi) };
363 self.scalar_llvm_type_at(cx, scalar, offset)
366 fn llvm_field_index(&self, index: usize) -> u64 {
368 layout::Abi::Scalar(_) | layout::Abi::ScalarPair(..) => {
369 bug!("TyLayout::llvm_field_index({:?}): not applicable", self)
374 layout::FieldPlacement::Union(_) => {
375 bug!("TyLayout::llvm_field_index({:?}): not applicable", self)
378 layout::FieldPlacement::Array { .. } => index as u64,
380 layout::FieldPlacement::Arbitrary { .. } => {
381 1 + (self.fields.memory_index(index) as u64) * 2
386 fn pointee_info_at<'a>(&self, cx: &CodegenCx<'a, 'tcx>, offset: Size) -> Option<PointeeInfo> {
387 if let Some(&pointee) = cx.pointee_infos.borrow().get(&(self.ty, offset)) {
391 let result = Ty::pointee_info_at(*self, cx, offset);
393 cx.pointee_infos.borrow_mut().insert((self.ty, offset), result);