3 use crate::type_::Type;
4 use rustc_codegen_ssa::traits::*;
6 use rustc_middle::ty::layout::{FnAbiExt, TyAndLayout};
7 use rustc_middle::ty::print::with_no_trimmed_paths;
8 use rustc_middle::ty::{self, Ty, TypeFoldable};
9 use rustc_target::abi::{Abi, AddressSpace, Align, FieldsShape};
10 use rustc_target::abi::{Int, Pointer, F32, F64};
11 use rustc_target::abi::{LayoutOf, PointeeInfo, Scalar, Size, TyAndLayoutMethods, Variants};
16 fn uncached_llvm_type<'a, 'tcx>(
17 cx: &CodegenCx<'a, 'tcx>,
18 layout: TyAndLayout<'tcx>,
19 defer: &mut Option<(&'a Type, TyAndLayout<'tcx>)>,
22 Abi::Scalar(_) => bug!("handled elsewhere"),
23 Abi::Vector { ref element, count } => {
24 let element = layout.scalar_llvm_type_at(cx, element, Size::ZERO);
25 return cx.type_vector(element, count);
27 Abi::ScalarPair(..) => {
28 return cx.type_struct(
30 layout.scalar_pair_element_llvm_type(cx, 0, false),
31 layout.scalar_pair_element_llvm_type(cx, 1, false),
36 Abi::Uninhabited | Abi::Aggregate { .. } => {}
39 let name = match layout.ty.kind() {
40 // FIXME(eddyb) producing readable type names for trait objects can result
41 // in problematically distinct types due to HRTB and subtyping (see #47638).
43 ty::Adt(..) | ty::Closure(..) | ty::Foreign(..) | ty::Generator(..) | ty::Str => {
44 let mut name = with_no_trimmed_paths(|| layout.ty.to_string());
45 if let (&ty::Adt(def, _), &Variants::Single { index }) =
46 (layout.ty.kind(), &layout.variants)
48 if def.is_enum() && !def.variants.is_empty() {
49 write!(&mut name, "::{}", def.variants[index].ident).unwrap();
52 if let (&ty::Generator(_, _, _), &Variants::Single { index }) =
53 (layout.ty.kind(), &layout.variants)
55 write!(&mut name, "::{}", ty::GeneratorSubsts::variant_name(index)).unwrap();
63 FieldsShape::Primitive | FieldsShape::Union(_) => {
64 let fill = cx.type_padding_filler(layout.size, layout.align.abi);
67 None => cx.type_struct(&[fill], packed),
69 let llty = cx.type_named_struct(name);
70 cx.set_struct_body(llty, &[fill], packed);
75 FieldsShape::Array { count, .. } => cx.type_array(layout.field(cx, 0).llvm_type(cx), count),
76 FieldsShape::Arbitrary { .. } => match name {
78 let (llfields, packed) = struct_llfields(cx, layout);
79 cx.type_struct(&llfields, packed)
82 let llty = cx.type_named_struct(name);
83 *defer = Some((llty, layout));
90 fn struct_llfields<'a, 'tcx>(
91 cx: &CodegenCx<'a, 'tcx>,
92 layout: TyAndLayout<'tcx>,
93 ) -> (Vec<&'a Type>, bool) {
94 debug!("struct_llfields: {:#?}", layout);
95 let field_count = layout.fields.count();
97 let mut packed = false;
98 let mut offset = Size::ZERO;
99 let mut prev_effective_align = layout.align.abi;
100 let mut result: Vec<_> = Vec::with_capacity(1 + field_count * 2);
101 for i in layout.fields.index_by_increasing_offset() {
102 let target_offset = layout.fields.offset(i as usize);
103 let field = layout.field(cx, i);
104 let effective_field_align =
105 layout.align.abi.min(field.align.abi).restrict_for_offset(target_offset);
106 packed |= effective_field_align < field.align.abi;
109 "struct_llfields: {}: {:?} offset: {:?} target_offset: {:?} \
110 effective_field_align: {}",
115 effective_field_align.bytes()
117 assert!(target_offset >= offset);
118 let padding = target_offset - offset;
119 let padding_align = prev_effective_align.min(effective_field_align);
120 assert_eq!(offset.align_to(padding_align) + padding, target_offset);
121 result.push(cx.type_padding_filler(padding, padding_align));
122 debug!(" padding before: {:?}", padding);
124 result.push(field.llvm_type(cx));
125 offset = target_offset + field.size;
126 prev_effective_align = effective_field_align;
128 if !layout.is_unsized() && field_count > 0 {
129 if offset > layout.size {
130 bug!("layout: {:#?} stride: {:?} offset: {:?}", layout, layout.size, offset);
132 let padding = layout.size - offset;
133 let padding_align = prev_effective_align;
134 assert_eq!(offset.align_to(padding_align) + padding, layout.size);
136 "struct_llfields: pad_bytes: {:?} offset: {:?} stride: {:?}",
137 padding, offset, layout.size
139 result.push(cx.type_padding_filler(padding, padding_align));
140 assert_eq!(result.len(), 1 + field_count * 2);
142 debug!("struct_llfields: offset: {:?} stride: {:?}", offset, layout.size);
148 impl<'a, 'tcx> CodegenCx<'a, 'tcx> {
149 pub fn align_of(&self, ty: Ty<'tcx>) -> Align {
150 self.layout_of(ty).align.abi
153 pub fn size_of(&self, ty: Ty<'tcx>) -> Size {
154 self.layout_of(ty).size
157 pub fn size_and_align_of(&self, ty: Ty<'tcx>) -> (Size, Align) {
158 let layout = self.layout_of(ty);
159 (layout.size, layout.align.abi)
163 pub trait LayoutLlvmExt<'tcx> {
164 fn is_llvm_immediate(&self) -> bool;
165 fn is_llvm_scalar_pair(&self) -> bool;
166 fn llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type;
167 fn immediate_llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type;
168 fn scalar_llvm_type_at<'a>(
170 cx: &CodegenCx<'a, 'tcx>,
174 fn scalar_pair_element_llvm_type<'a>(
176 cx: &CodegenCx<'a, 'tcx>,
180 fn llvm_field_index(&self, index: usize) -> u64;
181 fn pointee_info_at<'a>(&self, cx: &CodegenCx<'a, 'tcx>, offset: Size) -> Option<PointeeInfo>;
184 impl<'tcx> LayoutLlvmExt<'tcx> for TyAndLayout<'tcx> {
185 fn is_llvm_immediate(&self) -> bool {
187 Abi::Scalar(_) | Abi::Vector { .. } => true,
188 Abi::ScalarPair(..) => false,
189 Abi::Uninhabited | Abi::Aggregate { .. } => self.is_zst(),
193 fn is_llvm_scalar_pair(&self) -> bool {
195 Abi::ScalarPair(..) => true,
196 Abi::Uninhabited | Abi::Scalar(_) | Abi::Vector { .. } | Abi::Aggregate { .. } => false,
200 /// Gets the LLVM type corresponding to a Rust type, i.e., `rustc_middle::ty::Ty`.
201 /// The pointee type of the pointer in `PlaceRef` is always this type.
202 /// For sized types, it is also the right LLVM type for an `alloca`
203 /// containing a value of that type, and most immediates (except `bool`).
204 /// Unsized types, however, are represented by a "minimal unit", e.g.
205 /// `[T]` becomes `T`, while `str` and `Trait` turn into `i8` - this
206 /// is useful for indexing slices, as `&[T]`'s data pointer is `T*`.
207 /// If the type is an unsized struct, the regular layout is generated,
208 /// with the inner-most trailing unsized field using the "minimal unit"
209 /// of that field's type - this is useful for taking the address of
210 /// that field and ensuring the struct has the right alignment.
211 fn llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type {
212 if let Abi::Scalar(ref scalar) = self.abi {
213 // Use a different cache for scalars because pointers to DSTs
214 // can be either fat or thin (data pointers of fat pointers).
215 if let Some(&llty) = cx.scalar_lltypes.borrow().get(&self.ty) {
218 let llty = match *self.ty.kind() {
219 ty::Ref(_, ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) => {
220 cx.type_ptr_to(cx.layout_of(ty).llvm_type(cx))
222 ty::Adt(def, _) if def.is_box() => {
223 cx.type_ptr_to(cx.layout_of(self.ty.boxed_ty()).llvm_type(cx))
225 ty::FnPtr(sig) => cx.fn_ptr_backend_type(&FnAbi::of_fn_ptr(cx, sig, &[])),
226 _ => self.scalar_llvm_type_at(cx, scalar, Size::ZERO),
228 cx.scalar_lltypes.borrow_mut().insert(self.ty, llty);
233 let variant_index = match self.variants {
234 Variants::Single { index } => Some(index),
237 if let Some(&llty) = cx.lltypes.borrow().get(&(self.ty, variant_index)) {
241 debug!("llvm_type({:#?})", self);
243 assert!(!self.ty.has_escaping_bound_vars(), "{:?} has escaping bound vars", self.ty);
245 // Make sure lifetimes are erased, to avoid generating distinct LLVM
246 // types for Rust types that only differ in the choice of lifetimes.
247 let normal_ty = cx.tcx.erase_regions(self.ty);
249 let mut defer = None;
250 let llty = if self.ty != normal_ty {
251 let mut layout = cx.layout_of(normal_ty);
252 if let Some(v) = variant_index {
253 layout = layout.for_variant(cx, v);
257 uncached_llvm_type(cx, *self, &mut defer)
259 debug!("--> mapped {:#?} to llty={:?}", self, llty);
261 cx.lltypes.borrow_mut().insert((self.ty, variant_index), llty);
263 if let Some((llty, layout)) = defer {
264 let (llfields, packed) = struct_llfields(cx, layout);
265 cx.set_struct_body(llty, &llfields, packed)
271 fn immediate_llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type {
272 if let Abi::Scalar(ref scalar) = self.abi {
273 if scalar.is_bool() {
280 fn scalar_llvm_type_at<'a>(
282 cx: &CodegenCx<'a, 'tcx>,
287 Int(i, _) => cx.type_from_integer(i),
288 F32 => cx.type_f32(),
289 F64 => cx.type_f64(),
291 // If we know the alignment, pick something better than i8.
292 let (pointee, address_space) =
293 if let Some(pointee) = self.pointee_info_at(cx, offset) {
294 (cx.type_pointee_for_align(pointee.align), pointee.address_space)
296 (cx.type_i8(), AddressSpace::DATA)
298 cx.type_ptr_to_ext(pointee, address_space)
303 fn scalar_pair_element_llvm_type<'a>(
305 cx: &CodegenCx<'a, 'tcx>,
309 // HACK(eddyb) special-case fat pointers until LLVM removes
310 // pointee types, to avoid bitcasting every `OperandRef::deref`.
311 match self.ty.kind() {
312 ty::Ref(..) | ty::RawPtr(_) => {
313 return self.field(cx, index).llvm_type(cx);
315 ty::Adt(def, _) if def.is_box() => {
316 let ptr_ty = cx.tcx.mk_mut_ptr(self.ty.boxed_ty());
317 return cx.layout_of(ptr_ty).scalar_pair_element_llvm_type(cx, index, immediate);
322 let (a, b) = match self.abi {
323 Abi::ScalarPair(ref a, ref b) => (a, b),
324 _ => bug!("TyAndLayout::scalar_pair_element_llty({:?}): not applicable", self),
326 let scalar = [a, b][index];
328 // Make sure to return the same type `immediate_llvm_type` would when
329 // dealing with an immediate pair. This means that `(bool, bool)` is
330 // effectively represented as `{i8, i8}` in memory and two `i1`s as an
331 // immediate, just like `bool` is typically `i8` in memory and only `i1`
332 // when immediate. We need to load/store `bool` as `i8` to avoid
333 // crippling LLVM optimizations or triggering other LLVM bugs with `i1`.
334 if immediate && scalar.is_bool() {
339 if index == 0 { Size::ZERO } else { a.value.size(cx).align_to(b.value.align(cx).abi) };
340 self.scalar_llvm_type_at(cx, scalar, offset)
343 fn llvm_field_index(&self, index: usize) -> u64 {
345 Abi::Scalar(_) | Abi::ScalarPair(..) => {
346 bug!("TyAndLayout::llvm_field_index({:?}): not applicable", self)
351 FieldsShape::Primitive | FieldsShape::Union(_) => {
352 bug!("TyAndLayout::llvm_field_index({:?}): not applicable", self)
355 FieldsShape::Array { .. } => index as u64,
357 FieldsShape::Arbitrary { .. } => 1 + (self.fields.memory_index(index) as u64) * 2,
361 fn pointee_info_at<'a>(&self, cx: &CodegenCx<'a, 'tcx>, offset: Size) -> Option<PointeeInfo> {
362 if let Some(&pointee) = cx.pointee_infos.borrow().get(&(self.ty, offset)) {
366 let result = Ty::pointee_info_at(*self, cx, offset);
368 cx.pointee_infos.borrow_mut().insert((self.ty, offset), result);