]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/type_of.rs
Auto merge of #58561 - ljedrz:HirIdify_some_nodes, r=Zoxc
[rust.git] / src / librustc_codegen_llvm / type_of.rs
1 use crate::abi::{FnType, FnTypeExt};
2 use crate::common::*;
3 use crate::type_::Type;
4 use rustc::hir;
5 use rustc::ty::{self, Ty, TypeFoldable};
6 use rustc::ty::layout::{self, Align, LayoutOf, Size, TyLayout};
7 use rustc_target::abi::FloatTy;
8 use rustc_mir::monomorphize::item::DefPathBasedNames;
9 use rustc_codegen_ssa::traits::*;
10
11 use std::fmt::Write;
12
13 fn uncached_llvm_type<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
14                                 layout: TyLayout<'tcx>,
15                                 defer: &mut Option<(&'a Type, TyLayout<'tcx>)>)
16                                 -> &'a Type {
17     match layout.abi {
18         layout::Abi::Scalar(_) => bug!("handled elsewhere"),
19         layout::Abi::Vector { ref element, count } => {
20             // LLVM has a separate type for 64-bit SIMD vectors on X86 called
21             // `x86_mmx` which is needed for some SIMD operations. As a bit of a
22             // hack (all SIMD definitions are super unstable anyway) we
23             // recognize any one-element SIMD vector as "this should be an
24             // x86_mmx" type. In general there shouldn't be a need for other
25             // one-element SIMD vectors, so it's assumed this won't clash with
26             // much else.
27             let use_x86_mmx = count == 1 && layout.size.bits() == 64 &&
28                 (cx.sess().target.target.arch == "x86" ||
29                  cx.sess().target.target.arch == "x86_64");
30             if use_x86_mmx {
31                 return cx.type_x86_mmx()
32             } else {
33                 let element = layout.scalar_llvm_type_at(cx, element, Size::ZERO);
34                 return cx.type_vector(element, count);
35             }
36         }
37         layout::Abi::ScalarPair(..) => {
38             return cx.type_struct( &[
39                 layout.scalar_pair_element_llvm_type(cx, 0, false),
40                 layout.scalar_pair_element_llvm_type(cx, 1, false),
41             ], false);
42         }
43         layout::Abi::Uninhabited |
44         layout::Abi::Aggregate { .. } => {}
45     }
46
47     let name = match layout.ty.sty {
48         ty::Closure(..) |
49         ty::Generator(..) |
50         ty::Adt(..) |
51         // FIXME(eddyb) producing readable type names for trait objects can result
52         // in problematically distinct types due to HRTB and subtyping (see #47638).
53         // ty::Dynamic(..) |
54         ty::Foreign(..) |
55         ty::Str => {
56             let mut name = String::with_capacity(32);
57             let printer = DefPathBasedNames::new(cx.tcx, true, true);
58             printer.push_type_name(layout.ty, &mut name, false);
59             if let (&ty::Adt(def, _), &layout::Variants::Single { index })
60                  = (&layout.ty.sty, &layout.variants)
61             {
62                 if def.is_enum() && !def.variants.is_empty() {
63                     write!(&mut name, "::{}", def.variants[index].ident).unwrap();
64                 }
65             }
66             Some(name)
67         }
68         _ => None
69     };
70
71     match layout.fields {
72         layout::FieldPlacement::Union(_) => {
73             let fill = cx.type_padding_filler(layout.size, layout.align.abi);
74             let packed = false;
75             match name {
76                 None => {
77                     cx.type_struct(&[fill], packed)
78                 }
79                 Some(ref name) => {
80                     let llty = cx.type_named_struct(name);
81                     cx.set_struct_body(llty, &[fill], packed);
82                     llty
83                 }
84             }
85         }
86         layout::FieldPlacement::Array { count, .. } => {
87             cx.type_array(layout.field(cx, 0).llvm_type(cx), count)
88         }
89         layout::FieldPlacement::Arbitrary { .. } => {
90             match name {
91                 None => {
92                     let (llfields, packed) = struct_llfields(cx, layout);
93                     cx.type_struct( &llfields, packed)
94                 }
95                 Some(ref name) => {
96                     let llty = cx.type_named_struct( name);
97                     *defer = Some((llty, layout));
98                     llty
99                 }
100             }
101         }
102     }
103 }
104
105 fn struct_llfields<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
106                              layout: TyLayout<'tcx>)
107                              -> (Vec<&'a Type>, bool) {
108     debug!("struct_llfields: {:#?}", layout);
109     let field_count = layout.fields.count();
110
111     let mut packed = false;
112     let mut offset = Size::ZERO;
113     let mut prev_effective_align = layout.align.abi;
114     let mut result: Vec<_> = Vec::with_capacity(1 + field_count * 2);
115     for i in layout.fields.index_by_increasing_offset() {
116         let target_offset = layout.fields.offset(i as usize);
117         let field = layout.field(cx, i);
118         let effective_field_align = layout.align.abi
119             .min(field.align.abi)
120             .restrict_for_offset(target_offset);
121         packed |= effective_field_align < field.align.abi;
122
123         debug!("struct_llfields: {}: {:?} offset: {:?} target_offset: {:?} \
124                 effective_field_align: {}",
125                i, field, offset, target_offset, effective_field_align.bytes());
126         assert!(target_offset >= offset);
127         let padding = target_offset - offset;
128         let padding_align = prev_effective_align.min(effective_field_align);
129         assert_eq!(offset.align_to(padding_align) + padding, target_offset);
130         result.push(cx.type_padding_filler( padding, padding_align));
131         debug!("    padding before: {:?}", padding);
132
133         result.push(field.llvm_type(cx));
134         offset = target_offset + field.size;
135         prev_effective_align = effective_field_align;
136     }
137     if !layout.is_unsized() && field_count > 0 {
138         if offset > layout.size {
139             bug!("layout: {:#?} stride: {:?} offset: {:?}",
140                  layout, layout.size, offset);
141         }
142         let padding = layout.size - offset;
143         let padding_align = prev_effective_align;
144         assert_eq!(offset.align_to(padding_align) + padding, layout.size);
145         debug!("struct_llfields: pad_bytes: {:?} offset: {:?} stride: {:?}",
146                padding, offset, layout.size);
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: {:?}",
151                offset, layout.size);
152     }
153
154     (result, packed)
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 #[derive(Copy, Clone, PartialEq, Eq)]
173 pub enum PointerKind {
174     /// Most general case, we know no restrictions to tell LLVM.
175     Shared,
176
177     /// `&T` where `T` contains no `UnsafeCell`, is `noalias` and `readonly`.
178     Frozen,
179
180     /// `&mut T`, when we know `noalias` is safe for LLVM.
181     UniqueBorrowed,
182
183     /// `Box<T>`, unlike `UniqueBorrowed`, it also has `noalias` on returns.
184     UniqueOwned
185 }
186
187 #[derive(Copy, Clone)]
188 pub struct PointeeInfo {
189     pub size: Size,
190     pub align: Align,
191     pub safe: Option<PointerKind>,
192 }
193
194 pub trait LayoutLlvmExt<'tcx> {
195     fn is_llvm_immediate(&self) -> bool;
196     fn is_llvm_scalar_pair<'a>(&self) -> bool;
197     fn llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type;
198     fn immediate_llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type;
199     fn scalar_llvm_type_at<'a>(&self, cx: &CodegenCx<'a, 'tcx>,
200                                scalar: &layout::Scalar, offset: Size) -> &'a Type;
201     fn scalar_pair_element_llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>,
202                                          index: usize, immediate: bool) -> &'a Type;
203     fn llvm_field_index(&self, index: usize) -> u64;
204     fn pointee_info_at<'a>(&self, cx: &CodegenCx<'a, 'tcx>, offset: Size)
205                            -> Option<PointeeInfo>;
206 }
207
208 impl<'tcx> LayoutLlvmExt<'tcx> for TyLayout<'tcx> {
209     fn is_llvm_immediate(&self) -> bool {
210         match self.abi {
211             layout::Abi::Scalar(_) |
212             layout::Abi::Vector { .. } => true,
213             layout::Abi::ScalarPair(..) => false,
214             layout::Abi::Uninhabited |
215             layout::Abi::Aggregate { .. } => self.is_zst()
216         }
217     }
218
219     fn is_llvm_scalar_pair<'a>(&self) -> bool {
220         match self.abi {
221             layout::Abi::ScalarPair(..) => true,
222             layout::Abi::Uninhabited |
223             layout::Abi::Scalar(_) |
224             layout::Abi::Vector { .. } |
225             layout::Abi::Aggregate { .. } => false
226         }
227     }
228
229     /// Gets the LLVM type corresponding to a Rust type, i.e., `rustc::ty::Ty`.
230     /// The pointee type of the pointer in `PlaceRef` is always this type.
231     /// For sized types, it is also the right LLVM type for an `alloca`
232     /// containing a value of that type, and most immediates (except `bool`).
233     /// Unsized types, however, are represented by a "minimal unit", e.g.
234     /// `[T]` becomes `T`, while `str` and `Trait` turn into `i8` - this
235     /// is useful for indexing slices, as `&[T]`'s data pointer is `T*`.
236     /// If the type is an unsized struct, the regular layout is generated,
237     /// with the inner-most trailing unsized field using the "minimal unit"
238     /// of that field's type - this is useful for taking the address of
239     /// that field and ensuring the struct has the right alignment.
240     fn llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type {
241         if let layout::Abi::Scalar(ref scalar) = self.abi {
242             // Use a different cache for scalars because pointers to DSTs
243             // can be either fat or thin (data pointers of fat pointers).
244             if let Some(&llty) = cx.scalar_lltypes.borrow().get(&self.ty) {
245                 return llty;
246             }
247             let llty = match self.ty.sty {
248                 ty::Ref(_, ty, _) |
249                 ty::RawPtr(ty::TypeAndMut { ty, .. }) => {
250                     cx.type_ptr_to(cx.layout_of(ty).llvm_type(cx))
251                 }
252                 ty::Adt(def, _) if def.is_box() => {
253                     cx.type_ptr_to(cx.layout_of(self.ty.boxed_ty()).llvm_type(cx))
254                 }
255                 ty::FnPtr(sig) => {
256                     let sig = cx.tcx.normalize_erasing_late_bound_regions(
257                         ty::ParamEnv::reveal_all(),
258                         &sig,
259                     );
260                     cx.fn_ptr_backend_type(&FnType::new(cx, sig, &[]))
261                 }
262                 _ => self.scalar_llvm_type_at(cx, scalar, Size::ZERO)
263             };
264             cx.scalar_lltypes.borrow_mut().insert(self.ty, llty);
265             return llty;
266         }
267
268
269         // Check the cache.
270         let variant_index = match self.variants {
271             layout::Variants::Single { index } => Some(index),
272             _ => None
273         };
274         if let Some(&llty) = cx.lltypes.borrow().get(&(self.ty, variant_index)) {
275             return llty;
276         }
277
278         debug!("llvm_type({:#?})", self);
279
280         assert!(!self.ty.has_escaping_bound_vars(), "{:?} has escaping bound vars", self.ty);
281
282         // Make sure lifetimes are erased, to avoid generating distinct LLVM
283         // types for Rust types that only differ in the choice of lifetimes.
284         let normal_ty = cx.tcx.erase_regions(&self.ty);
285
286         let mut defer = None;
287         let llty = if self.ty != normal_ty {
288             let mut layout = cx.layout_of(normal_ty);
289             if let Some(v) = variant_index {
290                 layout = layout.for_variant(cx, v);
291             }
292             layout.llvm_type(cx)
293         } else {
294             uncached_llvm_type(cx, *self, &mut defer)
295         };
296         debug!("--> mapped {:#?} to llty={:?}", self, llty);
297
298         cx.lltypes.borrow_mut().insert((self.ty, variant_index), llty);
299
300         if let Some((llty, layout)) = defer {
301             let (llfields, packed) = struct_llfields(cx, layout);
302             cx.set_struct_body(llty, &llfields, packed)
303         }
304
305         llty
306     }
307
308     fn immediate_llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type {
309         if let layout::Abi::Scalar(ref scalar) = self.abi {
310             if scalar.is_bool() {
311                 return cx.type_i1();
312             }
313         }
314         self.llvm_type(cx)
315     }
316
317     fn scalar_llvm_type_at<'a>(&self, cx: &CodegenCx<'a, 'tcx>,
318                                scalar: &layout::Scalar, offset: Size) -> &'a Type {
319         match scalar.value {
320             layout::Int(i, _) => cx.type_from_integer( i),
321             layout::Float(FloatTy::F32) => cx.type_f32(),
322             layout::Float(FloatTy::F64) => cx.type_f64(),
323             layout::Pointer => {
324                 // If we know the alignment, pick something better than i8.
325                 let pointee = if let Some(pointee) = self.pointee_info_at(cx, offset) {
326                     cx.type_pointee_for_align(pointee.align)
327                 } else {
328                     cx.type_i8()
329                 };
330                 cx.type_ptr_to(pointee)
331             }
332         }
333     }
334
335     fn scalar_pair_element_llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>,
336                                          index: usize, immediate: bool) -> &'a Type {
337         // HACK(eddyb) special-case fat pointers until LLVM removes
338         // pointee types, to avoid bitcasting every `OperandRef::deref`.
339         match self.ty.sty {
340             ty::Ref(..) |
341             ty::RawPtr(_) => {
342                 return self.field(cx, index).llvm_type(cx);
343             }
344             ty::Adt(def, _) if def.is_box() => {
345                 let ptr_ty = cx.tcx.mk_mut_ptr(self.ty.boxed_ty());
346                 return cx.layout_of(ptr_ty).scalar_pair_element_llvm_type(cx, index, immediate);
347             }
348             _ => {}
349         }
350
351         let (a, b) = match self.abi {
352             layout::Abi::ScalarPair(ref a, ref b) => (a, b),
353             _ => bug!("TyLayout::scalar_pair_element_llty({:?}): not applicable", self)
354         };
355         let scalar = [a, b][index];
356
357         // Make sure to return the same type `immediate_llvm_type` would when
358         // dealing with an immediate pair.  This means that `(bool, bool)` is
359         // effectively represented as `{i8, i8}` in memory and two `i1`s as an
360         // immediate, just like `bool` is typically `i8` in memory and only `i1`
361         // when immediate.  We need to load/store `bool` as `i8` to avoid
362         // crippling LLVM optimizations or triggering other LLVM bugs with `i1`.
363         if immediate && scalar.is_bool() {
364             return cx.type_i1();
365         }
366
367         let offset = if index == 0 {
368             Size::ZERO
369         } else {
370             a.value.size(cx).align_to(b.value.align(cx).abi)
371         };
372         self.scalar_llvm_type_at(cx, scalar, offset)
373     }
374
375     fn llvm_field_index(&self, index: usize) -> u64 {
376         match self.abi {
377             layout::Abi::Scalar(_) |
378             layout::Abi::ScalarPair(..) => {
379                 bug!("TyLayout::llvm_field_index({:?}): not applicable", self)
380             }
381             _ => {}
382         }
383         match self.fields {
384             layout::FieldPlacement::Union(_) => {
385                 bug!("TyLayout::llvm_field_index({:?}): not applicable", self)
386             }
387
388             layout::FieldPlacement::Array { .. } => {
389                 index as u64
390             }
391
392             layout::FieldPlacement::Arbitrary { .. } => {
393                 1 + (self.fields.memory_index(index) as u64) * 2
394             }
395         }
396     }
397
398     fn pointee_info_at<'a>(&self, cx: &CodegenCx<'a, 'tcx>, offset: Size)
399                            -> Option<PointeeInfo> {
400         if let Some(&pointee) = cx.pointee_infos.borrow().get(&(self.ty, offset)) {
401             return pointee;
402         }
403
404         let mut result = None;
405         match self.ty.sty {
406             ty::RawPtr(mt) if offset.bytes() == 0 => {
407                 let (size, align) = cx.size_and_align_of(mt.ty);
408                 result = Some(PointeeInfo {
409                     size,
410                     align,
411                     safe: None
412                 });
413             }
414
415             ty::Ref(_, ty, mt) if offset.bytes() == 0 => {
416                 let (size, align) = cx.size_and_align_of(ty);
417
418                 let kind = match mt {
419                     hir::MutImmutable => if cx.type_is_freeze(ty) {
420                         PointerKind::Frozen
421                     } else {
422                         PointerKind::Shared
423                     },
424                     hir::MutMutable => {
425                         // Previously we would only emit noalias annotations for LLVM >= 6 or in
426                         // panic=abort mode. That was deemed right, as prior versions had many bugs
427                         // in conjunction with unwinding, but later versions didn’t seem to have
428                         // said issues. See issue #31681.
429                         //
430                         // Alas, later on we encountered a case where noalias would generate wrong
431                         // code altogether even with recent versions of LLVM in *safe* code with no
432                         // unwinding involved. See #54462.
433                         //
434                         // For now, do not enable mutable_noalias by default at all, while the
435                         // issue is being figured out.
436                         let mutable_noalias = cx.tcx.sess.opts.debugging_opts.mutable_noalias
437                             .unwrap_or(false);
438                         if mutable_noalias {
439                             PointerKind::UniqueBorrowed
440                         } else {
441                             PointerKind::Shared
442                         }
443                     }
444                 };
445
446                 result = Some(PointeeInfo {
447                     size,
448                     align,
449                     safe: Some(kind)
450                 });
451             }
452
453             _ => {
454                 let mut data_variant = match self.variants {
455                     layout::Variants::NicheFilling { dataful_variant, .. } => {
456                         // Only the niche itself is always initialized,
457                         // so only check for a pointer at its offset.
458                         //
459                         // If the niche is a pointer, it's either valid
460                         // (according to its type), or null (which the
461                         // niche field's scalar validity range encodes).
462                         // This allows using `dereferenceable_or_null`
463                         // for e.g., `Option<&T>`, and this will continue
464                         // to work as long as we don't start using more
465                         // niches than just null (e.g., the first page
466                         // of the address space, or unaligned pointers).
467                         if self.fields.offset(0) == offset {
468                             Some(self.for_variant(cx, dataful_variant))
469                         } else {
470                             None
471                         }
472                     }
473                     _ => Some(*self)
474                 };
475
476                 if let Some(variant) = data_variant {
477                     // We're not interested in any unions.
478                     if let layout::FieldPlacement::Union(_) = variant.fields {
479                         data_variant = None;
480                     }
481                 }
482
483                 if let Some(variant) = data_variant {
484                     let ptr_end = offset + layout::Pointer.size(cx);
485                     for i in 0..variant.fields.count() {
486                         let field_start = variant.fields.offset(i);
487                         if field_start <= offset {
488                             let field = variant.field(cx, i);
489                             if ptr_end <= field_start + field.size {
490                                 // We found the right field, look inside it.
491                                 result = field.pointee_info_at(cx, offset - field_start);
492                                 break;
493                             }
494                         }
495                     }
496                 }
497
498                 // FIXME(eddyb) This should be for `ptr::Unique<T>`, not `Box<T>`.
499                 if let Some(ref mut pointee) = result {
500                     if let ty::Adt(def, _) = self.ty.sty {
501                         if def.is_box() && offset.bytes() == 0 {
502                             pointee.safe = Some(PointerKind::UniqueOwned);
503                         }
504                     }
505                 }
506             }
507         }
508
509         cx.pointee_infos.borrow_mut().insert((self.ty, offset), result);
510         result
511     }
512 }