]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/type_of.rs
Rollup merge of #52465 - sekineh:add-ci-thumb, r=alexcrichton
[rust.git] / src / librustc_codegen_llvm / type_of.rs
1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use abi::{FnType, FnTypeExt};
12 use common::*;
13 use llvm;
14 use rustc::hir;
15 use rustc::ty::{self, Ty, TypeFoldable};
16 use rustc::ty::layout::{self, Align, LayoutOf, Size, TyLayout};
17 use rustc_target::spec::PanicStrategy;
18 use rustc_target::abi::FloatTy;
19 use rustc_mir::monomorphize::item::DefPathBasedNames;
20 use type_::Type;
21
22 use std::fmt::Write;
23
24 fn uncached_llvm_type<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
25                                 layout: TyLayout<'tcx>,
26                                 defer: &mut Option<(Type, TyLayout<'tcx>)>)
27                                 -> Type {
28     match layout.abi {
29         layout::Abi::Scalar(_) => bug!("handled elsewhere"),
30         layout::Abi::Vector { ref element, count } => {
31             // LLVM has a separate type for 64-bit SIMD vectors on X86 called
32             // `x86_mmx` which is needed for some SIMD operations. As a bit of a
33             // hack (all SIMD definitions are super unstable anyway) we
34             // recognize any one-element SIMD vector as "this should be an
35             // x86_mmx" type. In general there shouldn't be a need for other
36             // one-element SIMD vectors, so it's assumed this won't clash with
37             // much else.
38             let use_x86_mmx = count == 1 && layout.size.bits() == 64 &&
39                 (cx.sess().target.target.arch == "x86" ||
40                  cx.sess().target.target.arch == "x86_64");
41             if use_x86_mmx {
42                 return Type::x86_mmx(cx)
43             } else {
44                 let element = layout.scalar_llvm_type_at(cx, element, Size::ZERO);
45                 return Type::vector(&element, count);
46             }
47         }
48         layout::Abi::ScalarPair(..) => {
49             return Type::struct_(cx, &[
50                 layout.scalar_pair_element_llvm_type(cx, 0, false),
51                 layout.scalar_pair_element_llvm_type(cx, 1, false),
52             ], false);
53         }
54         layout::Abi::Uninhabited |
55         layout::Abi::Aggregate { .. } => {}
56     }
57
58     let name = match layout.ty.sty {
59         ty::TyClosure(..) |
60         ty::TyGenerator(..) |
61         ty::TyAdt(..) |
62         // FIXME(eddyb) producing readable type names for trait objects can result
63         // in problematically distinct types due to HRTB and subtyping (see #47638).
64         // ty::TyDynamic(..) |
65         ty::TyForeign(..) |
66         ty::TyStr => {
67             let mut name = String::with_capacity(32);
68             let printer = DefPathBasedNames::new(cx.tcx, true, true);
69             printer.push_type_name(layout.ty, &mut name);
70             match (&layout.ty.sty, &layout.variants) {
71                 (&ty::TyAdt(def, _), &layout::Variants::Single { index }) => {
72                     if def.is_enum() && !def.variants.is_empty() {
73                         write!(&mut name, "::{}", def.variants[index].name).unwrap();
74                     }
75                 }
76                 _ => {}
77             }
78             Some(name)
79         }
80         _ => None
81     };
82
83     match layout.fields {
84         layout::FieldPlacement::Union(_) => {
85             let fill = Type::padding_filler(cx, layout.size, layout.align);
86             let packed = false;
87             match name {
88                 None => {
89                     Type::struct_(cx, &[fill], packed)
90                 }
91                 Some(ref name) => {
92                     let mut llty = Type::named_struct(cx, name);
93                     llty.set_struct_body(&[fill], packed);
94                     llty
95                 }
96             }
97         }
98         layout::FieldPlacement::Array { count, .. } => {
99             Type::array(&layout.field(cx, 0).llvm_type(cx), count)
100         }
101         layout::FieldPlacement::Arbitrary { .. } => {
102             match name {
103                 None => {
104                     let (llfields, packed) = struct_llfields(cx, layout);
105                     Type::struct_(cx, &llfields, packed)
106                 }
107                 Some(ref name) => {
108                     let llty = Type::named_struct(cx, name);
109                     *defer = Some((llty, layout));
110                     llty
111                 }
112             }
113         }
114     }
115 }
116
117 fn struct_llfields<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
118                              layout: TyLayout<'tcx>)
119                              -> (Vec<Type>, bool) {
120     debug!("struct_llfields: {:#?}", layout);
121     let field_count = layout.fields.count();
122
123     let mut packed = false;
124     let mut offset = Size::ZERO;
125     let mut prev_align = layout.align;
126     let mut result: Vec<Type> = Vec::with_capacity(1 + field_count * 2);
127     for i in layout.fields.index_by_increasing_offset() {
128         let field = layout.field(cx, i);
129         packed |= layout.align.abi() < field.align.abi();
130
131         let target_offset = layout.fields.offset(i as usize);
132         debug!("struct_llfields: {}: {:?} offset: {:?} target_offset: {:?}",
133             i, field, offset, target_offset);
134         assert!(target_offset >= offset);
135         let padding = target_offset - offset;
136         let padding_align = layout.align.min(prev_align).min(field.align);
137         assert_eq!(offset.abi_align(padding_align) + padding, target_offset);
138         result.push(Type::padding_filler(cx, padding, padding_align));
139         debug!("    padding before: {:?}", padding);
140
141         result.push(field.llvm_type(cx));
142         offset = target_offset + field.size;
143         prev_align = field.align;
144     }
145     if !layout.is_unsized() && field_count > 0 {
146         if offset > layout.size {
147             bug!("layout: {:#?} stride: {:?} offset: {:?}",
148                  layout, layout.size, offset);
149         }
150         let padding = layout.size - offset;
151         let padding_align = layout.align.min(prev_align);
152         assert_eq!(offset.abi_align(padding_align) + padding, layout.size);
153         debug!("struct_llfields: pad_bytes: {:?} offset: {:?} stride: {:?}",
154                padding, offset, layout.size);
155         result.push(Type::padding_filler(cx, padding, padding_align));
156         assert!(result.len() == 1 + field_count * 2);
157     } else {
158         debug!("struct_llfields: offset: {:?} stride: {:?}",
159                offset, layout.size);
160     }
161
162     (result, packed)
163 }
164
165 impl<'a, 'tcx> CodegenCx<'a, 'tcx> {
166     pub fn align_of(&self, ty: Ty<'tcx>) -> Align {
167         self.layout_of(ty).align
168     }
169
170     pub fn size_of(&self, ty: Ty<'tcx>) -> Size {
171         self.layout_of(ty).size
172     }
173
174     pub fn size_and_align_of(&self, ty: Ty<'tcx>) -> (Size, Align) {
175         self.layout_of(ty).size_and_align()
176     }
177 }
178
179 #[derive(Copy, Clone, PartialEq, Eq)]
180 pub enum PointerKind {
181     /// Most general case, we know no restrictions to tell LLVM.
182     Shared,
183
184     /// `&T` where `T` contains no `UnsafeCell`, is `noalias` and `readonly`.
185     Frozen,
186
187     /// `&mut T`, when we know `noalias` is safe for LLVM.
188     UniqueBorrowed,
189
190     /// `Box<T>`, unlike `UniqueBorrowed`, it also has `noalias` on returns.
191     UniqueOwned
192 }
193
194 #[derive(Copy, Clone)]
195 pub struct PointeeInfo {
196     pub size: Size,
197     pub align: Align,
198     pub safe: Option<PointerKind>,
199 }
200
201 pub trait LayoutLlvmExt<'tcx> {
202     fn is_llvm_immediate(&self) -> bool;
203     fn is_llvm_scalar_pair<'a>(&self) -> bool;
204     fn llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> Type;
205     fn immediate_llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> Type;
206     fn scalar_llvm_type_at<'a>(&self, cx: &CodegenCx<'a, 'tcx>,
207                                scalar: &layout::Scalar, offset: Size) -> Type;
208     fn scalar_pair_element_llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>,
209                                          index: usize, immediate: bool) -> Type;
210     fn llvm_field_index(&self, index: usize) -> u64;
211     fn pointee_info_at<'a>(&self, cx: &CodegenCx<'a, 'tcx>, offset: Size)
212                            -> Option<PointeeInfo>;
213 }
214
215 impl<'tcx> LayoutLlvmExt<'tcx> for TyLayout<'tcx> {
216     fn is_llvm_immediate(&self) -> bool {
217         match self.abi {
218             layout::Abi::Scalar(_) |
219             layout::Abi::Vector { .. } => true,
220             layout::Abi::ScalarPair(..) => false,
221             layout::Abi::Uninhabited |
222             layout::Abi::Aggregate { .. } => self.is_zst()
223         }
224     }
225
226     fn is_llvm_scalar_pair<'a>(&self) -> bool {
227         match self.abi {
228             layout::Abi::ScalarPair(..) => true,
229             layout::Abi::Uninhabited |
230             layout::Abi::Scalar(_) |
231             layout::Abi::Vector { .. } |
232             layout::Abi::Aggregate { .. } => false
233         }
234     }
235
236     /// Get the LLVM type corresponding to a Rust type, i.e. `rustc::ty::Ty`.
237     /// The pointee type of the pointer in `PlaceRef` is always this type.
238     /// For sized types, it is also the right LLVM type for an `alloca`
239     /// containing a value of that type, and most immediates (except `bool`).
240     /// Unsized types, however, are represented by a "minimal unit", e.g.
241     /// `[T]` becomes `T`, while `str` and `Trait` turn into `i8` - this
242     /// is useful for indexing slices, as `&[T]`'s data pointer is `T*`.
243     /// If the type is an unsized struct, the regular layout is generated,
244     /// with the inner-most trailing unsized field using the "minimal unit"
245     /// of that field's type - this is useful for taking the address of
246     /// that field and ensuring the struct has the right alignment.
247     fn llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> Type {
248         if let layout::Abi::Scalar(ref scalar) = self.abi {
249             // Use a different cache for scalars because pointers to DSTs
250             // can be either fat or thin (data pointers of fat pointers).
251             if let Some(&llty) = cx.scalar_lltypes.borrow().get(&self.ty) {
252                 return llty;
253             }
254             let llty = match self.ty.sty {
255                 ty::TyRef(_, ty, _) |
256                 ty::TyRawPtr(ty::TypeAndMut { ty, .. }) => {
257                     cx.layout_of(ty).llvm_type(cx).ptr_to()
258                 }
259                 ty::TyAdt(def, _) if def.is_box() => {
260                     cx.layout_of(self.ty.boxed_ty()).llvm_type(cx).ptr_to()
261                 }
262                 ty::TyFnPtr(sig) => {
263                     let sig = cx.tcx.normalize_erasing_late_bound_regions(
264                         ty::ParamEnv::reveal_all(),
265                         &sig,
266                     );
267                     FnType::new(cx, sig, &[]).llvm_type(cx).ptr_to()
268                 }
269                 _ => self.scalar_llvm_type_at(cx, scalar, Size::ZERO)
270             };
271             cx.scalar_lltypes.borrow_mut().insert(self.ty, llty);
272             return llty;
273         }
274
275
276         // Check the cache.
277         let variant_index = match self.variants {
278             layout::Variants::Single { index } => Some(index),
279             _ => None
280         };
281         if let Some(&llty) = cx.lltypes.borrow().get(&(self.ty, variant_index)) {
282             return llty;
283         }
284
285         debug!("llvm_type({:#?})", self);
286
287         assert!(!self.ty.has_escaping_regions(), "{:?} has escaping regions", self.ty);
288
289         // Make sure lifetimes are erased, to avoid generating distinct LLVM
290         // types for Rust types that only differ in the choice of lifetimes.
291         let normal_ty = cx.tcx.erase_regions(&self.ty);
292
293         let mut defer = None;
294         let llty = if self.ty != normal_ty {
295             let mut layout = cx.layout_of(normal_ty);
296             if let Some(v) = variant_index {
297                 layout = layout.for_variant(cx, v);
298             }
299             layout.llvm_type(cx)
300         } else {
301             uncached_llvm_type(cx, *self, &mut defer)
302         };
303         debug!("--> mapped {:#?} to llty={:?}", self, llty);
304
305         cx.lltypes.borrow_mut().insert((self.ty, variant_index), llty);
306
307         if let Some((mut llty, layout)) = defer {
308             let (llfields, packed) = struct_llfields(cx, layout);
309             llty.set_struct_body(&llfields, packed)
310         }
311
312         llty
313     }
314
315     fn immediate_llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> Type {
316         if let layout::Abi::Scalar(ref scalar) = self.abi {
317             if scalar.is_bool() {
318                 return Type::i1(cx);
319             }
320         }
321         self.llvm_type(cx)
322     }
323
324     fn scalar_llvm_type_at<'a>(&self, cx: &CodegenCx<'a, 'tcx>,
325                                scalar: &layout::Scalar, offset: Size) -> Type {
326         match scalar.value {
327             layout::Int(i, _) => Type::from_integer(cx, i),
328             layout::Float(FloatTy::F32) => Type::f32(cx),
329             layout::Float(FloatTy::F64) => Type::f64(cx),
330             layout::Pointer => {
331                 // If we know the alignment, pick something better than i8.
332                 let pointee = if let Some(pointee) = self.pointee_info_at(cx, offset) {
333                     Type::pointee_for_abi_align(cx, pointee.align)
334                 } else {
335                     Type::i8(cx)
336                 };
337                 pointee.ptr_to()
338             }
339         }
340     }
341
342     fn scalar_pair_element_llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>,
343                                          index: usize, immediate: bool) -> Type {
344         // HACK(eddyb) special-case fat pointers until LLVM removes
345         // pointee types, to avoid bitcasting every `OperandRef::deref`.
346         match self.ty.sty {
347             ty::TyRef(..) |
348             ty::TyRawPtr(_) => {
349                 return self.field(cx, index).llvm_type(cx);
350             }
351             ty::TyAdt(def, _) if def.is_box() => {
352                 let ptr_ty = cx.tcx.mk_mut_ptr(self.ty.boxed_ty());
353                 return cx.layout_of(ptr_ty).scalar_pair_element_llvm_type(cx, index, immediate);
354             }
355             _ => {}
356         }
357
358         let (a, b) = match self.abi {
359             layout::Abi::ScalarPair(ref a, ref b) => (a, b),
360             _ => bug!("TyLayout::scalar_pair_element_llty({:?}): not applicable", self)
361         };
362         let scalar = [a, b][index];
363
364         // Make sure to return the same type `immediate_llvm_type` would when
365         // dealing with an immediate pair.  This means that `(bool, bool)` is
366         // effectively represented as `{i8, i8}` in memory and two `i1`s as an
367         // immediate, just like `bool` is typically `i8` in memory and only `i1`
368         // when immediate.  We need to load/store `bool` as `i8` to avoid
369         // crippling LLVM optimizations or triggering other LLVM bugs with `i1`.
370         if immediate && scalar.is_bool() {
371             return Type::i1(cx);
372         }
373
374         let offset = if index == 0 {
375             Size::ZERO
376         } else {
377             a.value.size(cx).abi_align(b.value.align(cx))
378         };
379         self.scalar_llvm_type_at(cx, scalar, offset)
380     }
381
382     fn llvm_field_index(&self, index: usize) -> u64 {
383         match self.abi {
384             layout::Abi::Scalar(_) |
385             layout::Abi::ScalarPair(..) => {
386                 bug!("TyLayout::llvm_field_index({:?}): not applicable", self)
387             }
388             _ => {}
389         }
390         match self.fields {
391             layout::FieldPlacement::Union(_) => {
392                 bug!("TyLayout::llvm_field_index({:?}): not applicable", self)
393             }
394
395             layout::FieldPlacement::Array { .. } => {
396                 index as u64
397             }
398
399             layout::FieldPlacement::Arbitrary { .. } => {
400                 1 + (self.fields.memory_index(index) as u64) * 2
401             }
402         }
403     }
404
405     fn pointee_info_at<'a>(&self, cx: &CodegenCx<'a, 'tcx>, offset: Size)
406                            -> Option<PointeeInfo> {
407         if let Some(&pointee) = cx.pointee_infos.borrow().get(&(self.ty, offset)) {
408             return pointee;
409         }
410
411         let mut result = None;
412         match self.ty.sty {
413             ty::TyRawPtr(mt) if offset.bytes() == 0 => {
414                 let (size, align) = cx.size_and_align_of(mt.ty);
415                 result = Some(PointeeInfo {
416                     size,
417                     align,
418                     safe: None
419                 });
420             }
421
422             ty::TyRef(_, ty, mt) if offset.bytes() == 0 => {
423                 let (size, align) = cx.size_and_align_of(ty);
424
425                 let kind = match mt {
426                     hir::MutImmutable => if cx.type_is_freeze(ty) {
427                         PointerKind::Frozen
428                     } else {
429                         PointerKind::Shared
430                     },
431                     hir::MutMutable => {
432                         // Only emit noalias annotations for LLVM >= 6 or in panic=abort
433                         // mode, as prior versions had many bugs in conjunction with
434                         // unwinding. See also issue #31681.
435                         let mutable_noalias = cx.tcx.sess.opts.debugging_opts.mutable_noalias
436                             .unwrap_or(unsafe { llvm::LLVMRustVersionMajor() >= 6 }
437                                 || cx.tcx.sess.panic_strategy() == PanicStrategy::Abort);
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::TyAdt(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 }