]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_middle/src/ty/vtable.rs
New upstream version 1.64.0+dfsg1
[rustc.git] / compiler / rustc_middle / src / ty / vtable.rs
CommitLineData
136023e0 1use std::convert::TryFrom;
94222f64 2use std::fmt;
136023e0
XL
3
4use crate::mir::interpret::{alloc_range, AllocId, Allocation, Pointer, Scalar, ScalarMaybeUninit};
94222f64 5use crate::ty::{self, Instance, PolyTraitRef, Ty, TyCtxt};
136023e0
XL
6use rustc_ast::Mutability;
7
94222f64 8#[derive(Clone, Copy, PartialEq, HashStable)]
136023e0 9pub enum VtblEntry<'tcx> {
94222f64 10 /// destructor of this type (used in vtable header)
136023e0 11 MetadataDropInPlace,
94222f64 12 /// layout size of this type (used in vtable header)
136023e0 13 MetadataSize,
94222f64 14 /// layout align of this type (used in vtable header)
136023e0 15 MetadataAlign,
94222f64 16 /// non-dispatchable associated function that is excluded from trait object
136023e0 17 Vacant,
94222f64
XL
18 /// dispatchable associated function
19 Method(Instance<'tcx>),
20 /// pointer to a separate supertrait vtable, can be used by trait upcasting coercion
21 TraitVPtr(PolyTraitRef<'tcx>),
22}
23
24impl<'tcx> fmt::Debug for VtblEntry<'tcx> {
25 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26 // We want to call `Display` on `Instance` and `PolyTraitRef`,
27 // so we implement this manually.
28 match self {
29 VtblEntry::MetadataDropInPlace => write!(f, "MetadataDropInPlace"),
30 VtblEntry::MetadataSize => write!(f, "MetadataSize"),
31 VtblEntry::MetadataAlign => write!(f, "MetadataAlign"),
32 VtblEntry::Vacant => write!(f, "Vacant"),
33 VtblEntry::Method(instance) => write!(f, "Method({})", instance),
34 VtblEntry::TraitVPtr(trait_ref) => write!(f, "TraitVPtr({})", trait_ref),
35 }
36 }
136023e0
XL
37}
38
923072b8
FG
39// Needs to be associated with the `'tcx` lifetime
40impl<'tcx> TyCtxt<'tcx> {
41 pub const COMMON_VTABLE_ENTRIES: &'tcx [VtblEntry<'tcx>] =
42 &[VtblEntry::MetadataDropInPlace, VtblEntry::MetadataSize, VtblEntry::MetadataAlign];
43}
136023e0
XL
44
45pub const COMMON_VTABLE_ENTRIES_DROPINPLACE: usize = 0;
46pub const COMMON_VTABLE_ENTRIES_SIZE: usize = 1;
47pub const COMMON_VTABLE_ENTRIES_ALIGN: usize = 2;
48
dc3f5686
XL
49/// Retrieves an allocation that represents the contents of a vtable.
50/// Since this is a query, allocations are cached and not duplicated.
51pub(super) fn vtable_allocation_provider<'tcx>(
52 tcx: TyCtxt<'tcx>,
53 key: (Ty<'tcx>, Option<ty::PolyExistentialTraitRef<'tcx>>),
54) -> AllocId {
55 let (ty, poly_trait_ref) = key;
136023e0 56
dc3f5686
XL
57 let vtable_entries = if let Some(poly_trait_ref) = poly_trait_ref {
58 let trait_ref = poly_trait_ref.with_self_ty(tcx, ty);
59 let trait_ref = tcx.erase_regions(trait_ref);
136023e0 60
dc3f5686
XL
61 tcx.vtable_entries(trait_ref)
62 } else {
923072b8 63 TyCtxt::COMMON_VTABLE_ENTRIES
dc3f5686 64 };
136023e0 65
dc3f5686
XL
66 let layout = tcx
67 .layout_of(ty::ParamEnv::reveal_all().and(ty))
68 .expect("failed to build vtable representation");
69 assert!(!layout.is_unsized(), "can't create a vtable for an unsized type");
70 let size = layout.size.bytes();
71 let align = layout.align.abi.bytes();
136023e0 72
dc3f5686
XL
73 let ptr_size = tcx.data_layout.pointer_size;
74 let ptr_align = tcx.data_layout.pointer_align.abi;
136023e0 75
dc3f5686
XL
76 let vtable_size = ptr_size * u64::try_from(vtable_entries.len()).unwrap();
77 let mut vtable = Allocation::uninit(vtable_size, ptr_align, /* panic_on_fail */ true).unwrap();
136023e0 78
dc3f5686
XL
79 // No need to do any alignment checks on the memory accesses below, because we know the
80 // allocation is correctly aligned as we created it above. Also we're only offsetting by
81 // multiples of `ptr_align`, which means that it will stay aligned to `ptr_align`.
136023e0 82
dc3f5686
XL
83 for (idx, entry) in vtable_entries.iter().enumerate() {
84 let idx: u64 = u64::try_from(idx).unwrap();
85 let scalar = match entry {
86 VtblEntry::MetadataDropInPlace => {
87 let instance = ty::Instance::resolve_drop_in_place(tcx, ty);
88 let fn_alloc_id = tcx.create_fn_alloc(instance);
89 let fn_ptr = Pointer::from(fn_alloc_id);
90 ScalarMaybeUninit::from_pointer(fn_ptr, &tcx)
91 }
92 VtblEntry::MetadataSize => Scalar::from_uint(size, ptr_size).into(),
93 VtblEntry::MetadataAlign => Scalar::from_uint(align, ptr_size).into(),
94 VtblEntry::Vacant => continue,
95 VtblEntry::Method(instance) => {
96 // Prepare the fn ptr we write into the vtable.
97 let instance = instance.polymorphize(tcx);
98 let fn_alloc_id = tcx.create_fn_alloc(instance);
99 let fn_ptr = Pointer::from(fn_alloc_id);
100 ScalarMaybeUninit::from_pointer(fn_ptr, &tcx)
101 }
102 VtblEntry::TraitVPtr(trait_ref) => {
103 let super_trait_ref = trait_ref
104 .map_bound(|trait_ref| ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref));
105 let supertrait_alloc_id = tcx.vtable_allocation((ty, Some(super_trait_ref)));
106 let vptr = Pointer::from(supertrait_alloc_id);
107 ScalarMaybeUninit::from_pointer(vptr, &tcx)
108 }
109 };
110 vtable
111 .write_scalar(&tcx, alloc_range(ptr_size * idx, ptr_size), scalar)
112 .expect("failed to build vtable representation");
136023e0 113 }
dc3f5686
XL
114
115 vtable.mutability = Mutability::Not;
116 tcx.create_memory_alloc(tcx.intern_const_alloc(vtable))
136023e0 117}