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