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