1 use crate::abi::{FnType, FnTypeExt};
3 use crate::type_::Type;
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::*;
13 fn uncached_llvm_type<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
14 layout: TyLayout<'tcx>,
15 defer: &mut Option<(&'a Type, TyLayout<'tcx>)>)
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
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");
31 return cx.type_x86_mmx()
33 let element = layout.scalar_llvm_type_at(cx, element, Size::ZERO);
34 return cx.type_vector(element, count);
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),
43 layout::Abi::Uninhabited |
44 layout::Abi::Aggregate { .. } => {}
47 let name = match layout.ty.sty {
51 // FIXME(eddyb) producing readable type names for trait objects can result
52 // in problematically distinct types due to HRTB and subtyping (see #47638).
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)
62 if def.is_enum() && !def.variants.is_empty() {
63 write!(&mut name, "::{}", def.variants[index].ident).unwrap();
66 if let (&ty::Generator(_, substs, _), &layout::Variants::Single { index })
67 = (&layout.ty.sty, &layout.variants)
69 write!(&mut name, "::{}", substs.variant_name(index)).unwrap();
77 layout::FieldPlacement::Union(_) => {
78 let fill = cx.type_padding_filler(layout.size, layout.align.abi);
82 cx.type_struct(&[fill], packed)
85 let llty = cx.type_named_struct(name);
86 cx.set_struct_body(llty, &[fill], packed);
91 layout::FieldPlacement::Array { count, .. } => {
92 cx.type_array(layout.field(cx, 0).llvm_type(cx), count)
94 layout::FieldPlacement::Arbitrary { .. } => {
97 let (llfields, packed) = struct_llfields(cx, layout);
98 cx.type_struct( &llfields, packed)
101 let llty = cx.type_named_struct( name);
102 *defer = Some((llty, layout));
110 fn struct_llfields<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
111 layout: TyLayout<'tcx>)
112 -> (Vec<&'a Type>, bool) {
113 debug!("struct_llfields: {:#?}", layout);
114 let field_count = layout.fields.count();
116 let mut packed = false;
117 let mut offset = Size::ZERO;
118 let mut prev_effective_align = layout.align.abi;
119 let mut result: Vec<_> = Vec::with_capacity(1 + field_count * 2);
120 for i in layout.fields.index_by_increasing_offset() {
121 let target_offset = layout.fields.offset(i as usize);
122 let field = layout.field(cx, i);
123 let effective_field_align = layout.align.abi
124 .min(field.align.abi)
125 .restrict_for_offset(target_offset);
126 packed |= effective_field_align < field.align.abi;
128 debug!("struct_llfields: {}: {:?} offset: {:?} target_offset: {:?} \
129 effective_field_align: {}",
130 i, field, offset, target_offset, effective_field_align.bytes());
131 assert!(target_offset >= offset);
132 let padding = target_offset - offset;
133 let padding_align = prev_effective_align.min(effective_field_align);
134 assert_eq!(offset.align_to(padding_align) + padding, target_offset);
135 result.push(cx.type_padding_filler( padding, padding_align));
136 debug!(" padding before: {:?}", padding);
138 result.push(field.llvm_type(cx));
139 offset = target_offset + field.size;
140 prev_effective_align = effective_field_align;
142 if !layout.is_unsized() && field_count > 0 {
143 if offset > layout.size {
144 bug!("layout: {:#?} stride: {:?} offset: {:?}",
145 layout, layout.size, offset);
147 let padding = layout.size - offset;
148 let padding_align = prev_effective_align;
149 assert_eq!(offset.align_to(padding_align) + padding, layout.size);
150 debug!("struct_llfields: pad_bytes: {:?} offset: {:?} stride: {:?}",
151 padding, offset, layout.size);
152 result.push(cx.type_padding_filler(padding, padding_align));
153 assert_eq!(result.len(), 1 + field_count * 2);
155 debug!("struct_llfields: offset: {:?} stride: {:?}",
156 offset, layout.size);
162 impl<'a, 'tcx> CodegenCx<'a, 'tcx> {
163 pub fn align_of(&self, ty: Ty<'tcx>) -> Align {
164 self.layout_of(ty).align.abi
167 pub fn size_of(&self, ty: Ty<'tcx>) -> Size {
168 self.layout_of(ty).size
171 pub fn size_and_align_of(&self, ty: Ty<'tcx>) -> (Size, Align) {
172 let layout = self.layout_of(ty);
173 (layout.size, layout.align.abi)
177 #[derive(Copy, Clone, PartialEq, Eq)]
178 pub enum PointerKind {
179 /// Most general case, we know no restrictions to tell LLVM.
182 /// `&T` where `T` contains no `UnsafeCell`, is `noalias` and `readonly`.
185 /// `&mut T`, when we know `noalias` is safe for LLVM.
188 /// `Box<T>`, unlike `UniqueBorrowed`, it also has `noalias` on returns.
192 #[derive(Copy, Clone)]
193 pub struct PointeeInfo {
196 pub safe: Option<PointerKind>,
199 pub trait LayoutLlvmExt<'tcx> {
200 fn is_llvm_immediate(&self) -> bool;
201 fn is_llvm_scalar_pair<'a>(&self) -> bool;
202 fn llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type;
203 fn immediate_llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type;
204 fn scalar_llvm_type_at<'a>(&self, cx: &CodegenCx<'a, 'tcx>,
205 scalar: &layout::Scalar, offset: Size) -> &'a Type;
206 fn scalar_pair_element_llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>,
207 index: usize, immediate: bool) -> &'a Type;
208 fn llvm_field_index(&self, index: usize) -> u64;
209 fn pointee_info_at<'a>(&self, cx: &CodegenCx<'a, 'tcx>, offset: Size)
210 -> Option<PointeeInfo>;
213 impl<'tcx> LayoutLlvmExt<'tcx> for TyLayout<'tcx> {
214 fn is_llvm_immediate(&self) -> bool {
216 layout::Abi::Scalar(_) |
217 layout::Abi::Vector { .. } => true,
218 layout::Abi::ScalarPair(..) => false,
219 layout::Abi::Uninhabited |
220 layout::Abi::Aggregate { .. } => self.is_zst()
224 fn is_llvm_scalar_pair<'a>(&self) -> bool {
226 layout::Abi::ScalarPair(..) => true,
227 layout::Abi::Uninhabited |
228 layout::Abi::Scalar(_) |
229 layout::Abi::Vector { .. } |
230 layout::Abi::Aggregate { .. } => false
234 /// Gets the LLVM type corresponding to a Rust type, i.e., `rustc::ty::Ty`.
235 /// The pointee type of the pointer in `PlaceRef` is always this type.
236 /// For sized types, it is also the right LLVM type for an `alloca`
237 /// containing a value of that type, and most immediates (except `bool`).
238 /// Unsized types, however, are represented by a "minimal unit", e.g.
239 /// `[T]` becomes `T`, while `str` and `Trait` turn into `i8` - this
240 /// is useful for indexing slices, as `&[T]`'s data pointer is `T*`.
241 /// If the type is an unsized struct, the regular layout is generated,
242 /// with the inner-most trailing unsized field using the "minimal unit"
243 /// of that field's type - this is useful for taking the address of
244 /// that field and ensuring the struct has the right alignment.
245 fn llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type {
246 if let layout::Abi::Scalar(ref scalar) = self.abi {
247 // Use a different cache for scalars because pointers to DSTs
248 // can be either fat or thin (data pointers of fat pointers).
249 if let Some(&llty) = cx.scalar_lltypes.borrow().get(&self.ty) {
252 let llty = match self.ty.sty {
254 ty::RawPtr(ty::TypeAndMut { ty, .. }) => {
255 cx.type_ptr_to(cx.layout_of(ty).llvm_type(cx))
257 ty::Adt(def, _) if def.is_box() => {
258 cx.type_ptr_to(cx.layout_of(self.ty.boxed_ty()).llvm_type(cx))
261 let sig = cx.tcx.normalize_erasing_late_bound_regions(
262 ty::ParamEnv::reveal_all(),
265 cx.fn_ptr_backend_type(&FnType::new(cx, sig, &[]))
267 _ => self.scalar_llvm_type_at(cx, scalar, Size::ZERO)
269 cx.scalar_lltypes.borrow_mut().insert(self.ty, llty);
275 let variant_index = match self.variants {
276 layout::Variants::Single { index } => Some(index),
279 if let Some(&llty) = cx.lltypes.borrow().get(&(self.ty, variant_index)) {
283 debug!("llvm_type({:#?})", self);
285 assert!(!self.ty.has_escaping_bound_vars(), "{:?} has escaping bound vars", self.ty);
287 // Make sure lifetimes are erased, to avoid generating distinct LLVM
288 // types for Rust types that only differ in the choice of lifetimes.
289 let normal_ty = cx.tcx.erase_regions(&self.ty);
291 let mut defer = None;
292 let llty = if self.ty != normal_ty {
293 let mut layout = cx.layout_of(normal_ty);
294 if let Some(v) = variant_index {
295 layout = layout.for_variant(cx, v);
299 uncached_llvm_type(cx, *self, &mut defer)
301 debug!("--> mapped {:#?} to llty={:?}", self, llty);
303 cx.lltypes.borrow_mut().insert((self.ty, variant_index), llty);
305 if let Some((llty, layout)) = defer {
306 let (llfields, packed) = struct_llfields(cx, layout);
307 cx.set_struct_body(llty, &llfields, packed)
313 fn immediate_llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>) -> &'a Type {
314 if let layout::Abi::Scalar(ref scalar) = self.abi {
315 if scalar.is_bool() {
322 fn scalar_llvm_type_at<'a>(&self, cx: &CodegenCx<'a, 'tcx>,
323 scalar: &layout::Scalar, offset: Size) -> &'a Type {
325 layout::Int(i, _) => cx.type_from_integer( i),
326 layout::Float(FloatTy::F32) => cx.type_f32(),
327 layout::Float(FloatTy::F64) => cx.type_f64(),
329 // If we know the alignment, pick something better than i8.
330 let pointee = if let Some(pointee) = self.pointee_info_at(cx, offset) {
331 cx.type_pointee_for_align(pointee.align)
335 cx.type_ptr_to(pointee)
340 fn scalar_pair_element_llvm_type<'a>(&self, cx: &CodegenCx<'a, 'tcx>,
341 index: usize, immediate: bool) -> &'a Type {
342 // HACK(eddyb) special-case fat pointers until LLVM removes
343 // pointee types, to avoid bitcasting every `OperandRef::deref`.
347 return self.field(cx, index).llvm_type(cx);
349 ty::Adt(def, _) if def.is_box() => {
350 let ptr_ty = cx.tcx.mk_mut_ptr(self.ty.boxed_ty());
351 return cx.layout_of(ptr_ty).scalar_pair_element_llvm_type(cx, index, immediate);
356 let (a, b) = match self.abi {
357 layout::Abi::ScalarPair(ref a, ref b) => (a, b),
358 _ => bug!("TyLayout::scalar_pair_element_llty({:?}): not applicable", self)
360 let scalar = [a, b][index];
362 // Make sure to return the same type `immediate_llvm_type` would when
363 // dealing with an immediate pair. This means that `(bool, bool)` is
364 // effectively represented as `{i8, i8}` in memory and two `i1`s as an
365 // immediate, just like `bool` is typically `i8` in memory and only `i1`
366 // when immediate. We need to load/store `bool` as `i8` to avoid
367 // crippling LLVM optimizations or triggering other LLVM bugs with `i1`.
368 if immediate && scalar.is_bool() {
372 let offset = if index == 0 {
375 a.value.size(cx).align_to(b.value.align(cx).abi)
377 self.scalar_llvm_type_at(cx, scalar, offset)
380 fn llvm_field_index(&self, index: usize) -> u64 {
382 layout::Abi::Scalar(_) |
383 layout::Abi::ScalarPair(..) => {
384 bug!("TyLayout::llvm_field_index({:?}): not applicable", self)
389 layout::FieldPlacement::Union(_) => {
390 bug!("TyLayout::llvm_field_index({:?}): not applicable", self)
393 layout::FieldPlacement::Array { .. } => {
397 layout::FieldPlacement::Arbitrary { .. } => {
398 1 + (self.fields.memory_index(index) as u64) * 2
403 fn pointee_info_at<'a>(&self, cx: &CodegenCx<'a, 'tcx>, offset: Size)
404 -> Option<PointeeInfo> {
405 if let Some(&pointee) = cx.pointee_infos.borrow().get(&(self.ty, offset)) {
409 let mut result = None;
411 ty::RawPtr(mt) if offset.bytes() == 0 => {
412 let (size, align) = cx.size_and_align_of(mt.ty);
413 result = Some(PointeeInfo {
420 ty::Ref(_, ty, mt) if offset.bytes() == 0 => {
421 let (size, align) = cx.size_and_align_of(ty);
423 let kind = match mt {
424 hir::MutImmutable => if cx.type_is_freeze(ty) {
430 // Previously we would only emit noalias annotations for LLVM >= 6 or in
431 // panic=abort mode. That was deemed right, as prior versions had many bugs
432 // in conjunction with unwinding, but later versions didn’t seem to have
433 // said issues. See issue #31681.
435 // Alas, later on we encountered a case where noalias would generate wrong
436 // code altogether even with recent versions of LLVM in *safe* code with no
437 // unwinding involved. See #54462.
439 // For now, do not enable mutable_noalias by default at all, while the
440 // issue is being figured out.
441 let mutable_noalias = cx.tcx.sess.opts.debugging_opts.mutable_noalias
444 PointerKind::UniqueBorrowed
451 result = Some(PointeeInfo {
459 let mut data_variant = match self.variants {
460 // Within the discriminant field, only the niche itself is
461 // always initialized, so we only check for a pointer at its
464 // If the niche is a pointer, it's either valid (according
465 // to its type), or null (which the niche field's scalar
466 // validity range encodes). This allows using
467 // `dereferenceable_or_null` for e.g., `Option<&T>`, and
468 // this will continue to work as long as we don't start
469 // using more niches than just null (e.g., the first page of
470 // the address space, or unaligned pointers).
471 layout::Variants::Multiple {
472 discr_kind: layout::DiscriminantKind::Niche {
478 } if self.fields.offset(discr_index) == offset =>
479 Some(self.for_variant(cx, dataful_variant)),
483 if let Some(variant) = data_variant {
484 // We're not interested in any unions.
485 if let layout::FieldPlacement::Union(_) = variant.fields {
490 if let Some(variant) = data_variant {
491 let ptr_end = offset + layout::Pointer.size(cx);
492 for i in 0..variant.fields.count() {
493 let field_start = variant.fields.offset(i);
494 if field_start <= offset {
495 let field = variant.field(cx, i);
496 if ptr_end <= field_start + field.size {
497 // We found the right field, look inside it.
498 result = field.pointee_info_at(cx, offset - field_start);
505 // FIXME(eddyb) This should be for `ptr::Unique<T>`, not `Box<T>`.
506 if let Some(ref mut pointee) = result {
507 if let ty::Adt(def, _) = self.ty.sty {
508 if def.is_box() && offset.bytes() == 0 {
509 pointee.safe = Some(PointerKind::UniqueOwned);
516 cx.pointee_infos.borrow_mut().insert((self.ty, offset), result);