]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/type_of.rs
Add 'library/portable-simd/' from commit '1ce1c645cf27c4acdefe6ec8a11d1f0491954a99'
[rust.git] / compiler / rustc_codegen_llvm / src / type_of.rs
1 use crate::common::*;
2 use crate::context::TypeLowering;
3 use crate::type_::Type;
4 use rustc_codegen_ssa::traits::*;
5 use rustc_middle::bug;
6 use rustc_middle::ty::layout::{FnAbiOf, LayoutOf, TyAndLayout};
7 use rustc_middle::ty::print::{with_no_trimmed_paths, with_no_visible_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::{PointeeInfo, Scalar, Size, TyAbiInterface, Variants};
12 use smallvec::{smallvec, SmallVec};
13 use tracing::debug;
14
15 use std::fmt::Write;
16
17 fn uncached_llvm_type<'a, 'tcx>(
18     cx: &CodegenCx<'a, 'tcx>,
19     layout: TyAndLayout<'tcx>,
20     defer: &mut Option<(&'a Type, TyAndLayout<'tcx>)>,
21     field_remapping: &mut Option<SmallVec<[u32; 4]>>,
22 ) -> &'a Type {
23     match layout.abi {
24         Abi::Scalar(_) => bug!("handled elsewhere"),
25         Abi::Vector { element, count } => {
26             let element = layout.scalar_llvm_type_at(cx, element, Size::ZERO);
27             return cx.type_vector(element, count);
28         }
29         Abi::ScalarPair(..) => {
30             return cx.type_struct(
31                 &[
32                     layout.scalar_pair_element_llvm_type(cx, 0, false),
33                     layout.scalar_pair_element_llvm_type(cx, 1, false),
34                 ],
35                 false,
36             );
37         }
38         Abi::Uninhabited | Abi::Aggregate { .. } => {}
39     }
40
41     let name = match layout.ty.kind() {
42         // FIXME(eddyb) producing readable type names for trait objects can result
43         // in problematically distinct types due to HRTB and subtyping (see #47638).
44         // ty::Dynamic(..) |
45         ty::Adt(..) | ty::Closure(..) | ty::Foreign(..) | ty::Generator(..) | ty::Str => {
46             let mut name =
47                 with_no_visible_paths(|| with_no_trimmed_paths(|| layout.ty.to_string()));
48             if let (&ty::Adt(def, _), &Variants::Single { index }) =
49                 (layout.ty.kind(), &layout.variants)
50             {
51                 if def.is_enum() && !def.variants.is_empty() {
52                     write!(&mut name, "::{}", def.variants[index].ident).unwrap();
53                 }
54             }
55             if let (&ty::Generator(_, _, _), &Variants::Single { index }) =
56                 (layout.ty.kind(), &layout.variants)
57             {
58                 write!(&mut name, "::{}", ty::GeneratorSubsts::variant_name(index)).unwrap();
59             }
60             Some(name)
61         }
62         _ => None,
63     };
64
65     match layout.fields {
66         FieldsShape::Primitive | FieldsShape::Union(_) => {
67             let fill = cx.type_padding_filler(layout.size, layout.align.abi);
68             let packed = false;
69             match name {
70                 None => cx.type_struct(&[fill], packed),
71                 Some(ref name) => {
72                     let llty = cx.type_named_struct(name);
73                     cx.set_struct_body(llty, &[fill], packed);
74                     llty
75                 }
76             }
77         }
78         FieldsShape::Array { count, .. } => cx.type_array(layout.field(cx, 0).llvm_type(cx), count),
79         FieldsShape::Arbitrary { .. } => match name {
80             None => {
81                 let (llfields, packed, new_field_remapping) = struct_llfields(cx, layout);
82                 *field_remapping = new_field_remapping;
83                 cx.type_struct(&llfields, packed)
84             }
85             Some(ref name) => {
86                 let llty = cx.type_named_struct(name);
87                 *defer = Some((llty, layout));
88                 llty
89             }
90         },
91     }
92 }
93
94 fn struct_llfields<'a, 'tcx>(
95     cx: &CodegenCx<'a, 'tcx>,
96     layout: TyAndLayout<'tcx>,
97 ) -> (Vec<&'a Type>, bool, Option<SmallVec<[u32; 4]>>) {
98     debug!("struct_llfields: {:#?}", layout);
99     let field_count = layout.fields.count();
100
101     let mut packed = false;
102     let mut offset = Size::ZERO;
103     let mut prev_effective_align = layout.align.abi;
104     let mut result: Vec<_> = Vec::with_capacity(1 + field_count * 2);
105     let mut field_remapping = smallvec![0; field_count];
106     for i in layout.fields.index_by_increasing_offset() {
107         let target_offset = layout.fields.offset(i as usize);
108         let field = layout.field(cx, i);
109         let effective_field_align =
110             layout.align.abi.min(field.align.abi).restrict_for_offset(target_offset);
111         packed |= effective_field_align < field.align.abi;
112
113         debug!(
114             "struct_llfields: {}: {:?} offset: {:?} target_offset: {:?} \
115                 effective_field_align: {}",
116             i,
117             field,
118             offset,
119             target_offset,
120             effective_field_align.bytes()
121         );
122         assert!(target_offset >= offset);
123         let padding = target_offset - offset;
124         if padding != Size::ZERO {
125             let padding_align = prev_effective_align.min(effective_field_align);
126             assert_eq!(offset.align_to(padding_align) + padding, target_offset);
127             result.push(cx.type_padding_filler(padding, padding_align));
128             debug!("    padding before: {:?}", padding);
129         }
130         field_remapping[i] = result.len() as u32;
131         result.push(field.llvm_type(cx));
132         offset = target_offset + field.size;
133         prev_effective_align = effective_field_align;
134     }
135     let padding_used = result.len() > field_count;
136     if !layout.is_unsized() && field_count > 0 {
137         if offset > layout.size {
138             bug!("layout: {:#?} stride: {:?} offset: {:?}", layout, layout.size, offset);
139         }
140         let padding = layout.size - offset;
141         if padding != Size::ZERO {
142             let padding_align = prev_effective_align;
143             assert_eq!(offset.align_to(padding_align) + padding, layout.size);
144             debug!(
145                 "struct_llfields: pad_bytes: {:?} offset: {:?} stride: {:?}",
146                 padding, offset, layout.size
147             );
148             result.push(cx.type_padding_filler(padding, padding_align));
149         }
150     } else {
151         debug!("struct_llfields: offset: {:?} stride: {:?}", offset, layout.size);
152     }
153     let field_remapping = if padding_used { Some(field_remapping) } else { None };
154     (result, packed, field_remapping)
155 }
156
157 impl<'a, 'tcx> CodegenCx<'a, 'tcx> {
158     pub fn align_of(&self, ty: Ty<'tcx>) -> Align {
159         self.layout_of(ty).align.abi
160     }
161
162     pub fn size_of(&self, ty: Ty<'tcx>) -> Size {
163         self.layout_of(ty).size
164     }
165
166     pub fn size_and_align_of(&self, ty: Ty<'tcx>) -> (Size, Align) {
167         let layout = self.layout_of(ty);
168         (layout.size, layout.align.abi)
169     }
170 }
171
172 pub trait LayoutLlvmExt<'tcx> {
173     fn is_llvm_immediate(&self) -> bool;
174     fn is_llvm_scalar_pair(&self) -> bool;
175     fn llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type;
176     fn immediate_llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type;
177     fn scalar_llvm_type_at<'a>(
178         &self,
179         cx: &CodegenCx<'a, 'tcx>,
180         scalar: Scalar,
181         offset: Size,
182     ) -> &'a Type;
183     fn scalar_pair_element_llvm_type<'a>(
184         &self,
185         cx: &CodegenCx<'a, 'tcx>,
186         index: usize,
187         immediate: bool,
188     ) -> &'a Type;
189     fn llvm_field_index<'a>(&self, cx: &CodegenCx<'a, 'tcx>, index: usize) -> u64;
190     fn pointee_info_at<'a>(&self, cx: &CodegenCx<'a, 'tcx>, offset: Size) -> Option<PointeeInfo>;
191 }
192
193 impl<'tcx> LayoutLlvmExt<'tcx> for TyAndLayout<'tcx> {
194     fn is_llvm_immediate(&self) -> bool {
195         match self.abi {
196             Abi::Scalar(_) | Abi::Vector { .. } => true,
197             Abi::ScalarPair(..) => false,
198             Abi::Uninhabited | Abi::Aggregate { .. } => self.is_zst(),
199         }
200     }
201
202     fn is_llvm_scalar_pair(&self) -> bool {
203         match self.abi {
204             Abi::ScalarPair(..) => true,
205             Abi::Uninhabited | Abi::Scalar(_) | Abi::Vector { .. } | Abi::Aggregate { .. } => false,
206         }
207     }
208
209     /// Gets the LLVM type corresponding to a Rust type, i.e., `rustc_middle::ty::Ty`.
210     /// The pointee type of the pointer in `PlaceRef` is always this type.
211     /// For sized types, it is also the right LLVM type for an `alloca`
212     /// containing a value of that type, and most immediates (except `bool`).
213     /// Unsized types, however, are represented by a "minimal unit", e.g.
214     /// `[T]` becomes `T`, while `str` and `Trait` turn into `i8` - this
215     /// is useful for indexing slices, as `&[T]`'s data pointer is `T*`.
216     /// If the type is an unsized struct, the regular layout is generated,
217     /// with the inner-most trailing unsized field using the "minimal unit"
218     /// of that field's type - this is useful for taking the address of
219     /// that field and ensuring the struct has the right alignment.
220     fn llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type {
221         if let Abi::Scalar(scalar) = self.abi {
222             // Use a different cache for scalars because pointers to DSTs
223             // can be either fat or thin (data pointers of fat pointers).
224             if let Some(&llty) = cx.scalar_lltypes.borrow().get(&self.ty) {
225                 return llty;
226             }
227             let llty = match *self.ty.kind() {
228                 ty::Ref(_, ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) => {
229                     cx.type_ptr_to(cx.layout_of(ty).llvm_type(cx))
230                 }
231                 ty::Adt(def, _) if def.is_box() => {
232                     cx.type_ptr_to(cx.layout_of(self.ty.boxed_ty()).llvm_type(cx))
233                 }
234                 ty::FnPtr(sig) => {
235                     cx.fn_ptr_backend_type(cx.fn_abi_of_fn_ptr(sig, ty::List::empty()))
236                 }
237                 _ => self.scalar_llvm_type_at(cx, scalar, Size::ZERO),
238             };
239             cx.scalar_lltypes.borrow_mut().insert(self.ty, llty);
240             return llty;
241         }
242
243         // Check the cache.
244         let variant_index = match self.variants {
245             Variants::Single { index } => Some(index),
246             _ => None,
247         };
248         if let Some(llty) = cx.type_lowering.borrow().get(&(self.ty, variant_index)) {
249             return llty.lltype;
250         }
251
252         debug!("llvm_type({:#?})", self);
253
254         assert!(!self.ty.has_escaping_bound_vars(), "{:?} has escaping bound vars", self.ty);
255
256         // Make sure lifetimes are erased, to avoid generating distinct LLVM
257         // types for Rust types that only differ in the choice of lifetimes.
258         let normal_ty = cx.tcx.erase_regions(self.ty);
259
260         let mut defer = None;
261         let mut field_remapping = None;
262         let llty = if self.ty != normal_ty {
263             let mut layout = cx.layout_of(normal_ty);
264             if let Some(v) = variant_index {
265                 layout = layout.for_variant(cx, v);
266             }
267             layout.llvm_type(cx)
268         } else {
269             uncached_llvm_type(cx, *self, &mut defer, &mut field_remapping)
270         };
271         debug!("--> mapped {:#?} to llty={:?}", self, llty);
272
273         cx.type_lowering
274             .borrow_mut()
275             .insert((self.ty, variant_index), TypeLowering { lltype: llty, field_remapping });
276
277         if let Some((llty, layout)) = defer {
278             let (llfields, packed, new_field_remapping) = struct_llfields(cx, layout);
279             cx.set_struct_body(llty, &llfields, packed);
280             cx.type_lowering
281                 .borrow_mut()
282                 .get_mut(&(self.ty, variant_index))
283                 .unwrap()
284                 .field_remapping = new_field_remapping;
285         }
286         llty
287     }
288
289     fn immediate_llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type {
290         if let Abi::Scalar(scalar) = self.abi {
291             if scalar.is_bool() {
292                 return cx.type_i1();
293             }
294         }
295         self.llvm_type(cx)
296     }
297
298     fn scalar_llvm_type_at<'a>(
299         &self,
300         cx: &CodegenCx<'a, 'tcx>,
301         scalar: Scalar,
302         offset: Size,
303     ) -> &'a Type {
304         match scalar.value {
305             Int(i, _) => cx.type_from_integer(i),
306             F32 => cx.type_f32(),
307             F64 => cx.type_f64(),
308             Pointer => {
309                 // If we know the alignment, pick something better than i8.
310                 let (pointee, address_space) =
311                     if let Some(pointee) = self.pointee_info_at(cx, offset) {
312                         (cx.type_pointee_for_align(pointee.align), pointee.address_space)
313                     } else {
314                         (cx.type_i8(), AddressSpace::DATA)
315                     };
316                 cx.type_ptr_to_ext(pointee, address_space)
317             }
318         }
319     }
320
321     fn scalar_pair_element_llvm_type<'a>(
322         &self,
323         cx: &CodegenCx<'a, 'tcx>,
324         index: usize,
325         immediate: bool,
326     ) -> &'a Type {
327         // HACK(eddyb) special-case fat pointers until LLVM removes
328         // pointee types, to avoid bitcasting every `OperandRef::deref`.
329         match self.ty.kind() {
330             ty::Ref(..) | ty::RawPtr(_) => {
331                 return self.field(cx, index).llvm_type(cx);
332             }
333             ty::Adt(def, _) if def.is_box() => {
334                 let ptr_ty = cx.tcx.mk_mut_ptr(self.ty.boxed_ty());
335                 return cx.layout_of(ptr_ty).scalar_pair_element_llvm_type(cx, index, immediate);
336             }
337             _ => {}
338         }
339
340         let (a, b) = match self.abi {
341             Abi::ScalarPair(a, b) => (a, b),
342             _ => bug!("TyAndLayout::scalar_pair_element_llty({:?}): not applicable", self),
343         };
344         let scalar = [a, b][index];
345
346         // Make sure to return the same type `immediate_llvm_type` would when
347         // dealing with an immediate pair.  This means that `(bool, bool)` is
348         // effectively represented as `{i8, i8}` in memory and two `i1`s as an
349         // immediate, just like `bool` is typically `i8` in memory and only `i1`
350         // when immediate.  We need to load/store `bool` as `i8` to avoid
351         // crippling LLVM optimizations or triggering other LLVM bugs with `i1`.
352         if immediate && scalar.is_bool() {
353             return cx.type_i1();
354         }
355
356         let offset =
357             if index == 0 { Size::ZERO } else { a.value.size(cx).align_to(b.value.align(cx).abi) };
358         self.scalar_llvm_type_at(cx, scalar, offset)
359     }
360
361     fn llvm_field_index<'a>(&self, cx: &CodegenCx<'a, 'tcx>, index: usize) -> u64 {
362         match self.abi {
363             Abi::Scalar(_) | Abi::ScalarPair(..) => {
364                 bug!("TyAndLayout::llvm_field_index({:?}): not applicable", self)
365             }
366             _ => {}
367         }
368         match self.fields {
369             FieldsShape::Primitive | FieldsShape::Union(_) => {
370                 bug!("TyAndLayout::llvm_field_index({:?}): not applicable", self)
371             }
372
373             FieldsShape::Array { .. } => index as u64,
374
375             FieldsShape::Arbitrary { .. } => {
376                 let variant_index = match self.variants {
377                     Variants::Single { index } => Some(index),
378                     _ => None,
379                 };
380
381                 // Look up llvm field if indexes do not match memory order due to padding. If
382                 // `field_remapping` is `None` no padding was used and the llvm field index
383                 // matches the memory index.
384                 match cx.type_lowering.borrow().get(&(self.ty, variant_index)) {
385                     Some(TypeLowering { field_remapping: Some(ref remap), .. }) => {
386                         remap[index] as u64
387                     }
388                     Some(_) => self.fields.memory_index(index) as u64,
389                     None => {
390                         bug!("TyAndLayout::llvm_field_index({:?}): type info not found", self)
391                     }
392                 }
393             }
394         }
395     }
396
397     // FIXME(eddyb) this having the same name as `TyAndLayout::pointee_info_at`
398     // (the inherent method, which is lacking this caching logic) can result in
399     // the uncached version being called - not wrong, but potentially inefficient.
400     fn pointee_info_at<'a>(&self, cx: &CodegenCx<'a, 'tcx>, offset: Size) -> Option<PointeeInfo> {
401         if let Some(&pointee) = cx.pointee_infos.borrow().get(&(self.ty, offset)) {
402             return pointee;
403         }
404
405         let result = Ty::ty_and_layout_pointee_info_at(*self, cx, offset);
406
407         cx.pointee_infos.borrow_mut().insert((self.ty, offset), result);
408         result
409     }
410 }