• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 use crate::errors::DumpVTableEntries;
2 use crate::traits::{impossible_predicates, is_vtable_safe_method};
3 use rustc_hir::def_id::DefId;
4 use rustc_hir::lang_items::LangItem;
5 use rustc_infer::traits::util::PredicateSet;
6 use rustc_infer::traits::ImplSource;
7 use rustc_middle::query::Providers;
8 use rustc_middle::ty::visit::TypeVisitableExt;
9 use rustc_middle::ty::InternalSubsts;
10 use rustc_middle::ty::{self, GenericParamDefKind, ToPredicate, Ty, TyCtxt, VtblEntry};
11 use rustc_span::{sym, Span};
12 use smallvec::SmallVec;
13 
14 use std::fmt::Debug;
15 use std::ops::ControlFlow;
16 
17 #[derive(Clone, Debug)]
18 pub enum VtblSegment<'tcx> {
19     MetadataDSA,
20     TraitOwnEntries { trait_ref: ty::PolyTraitRef<'tcx>, emit_vptr: bool },
21 }
22 
23 /// Prepare the segments for a vtable
prepare_vtable_segments<'tcx, T>( tcx: TyCtxt<'tcx>, trait_ref: ty::PolyTraitRef<'tcx>, mut segment_visitor: impl FnMut(VtblSegment<'tcx>) -> ControlFlow<T>, ) -> Option<T>24 pub fn prepare_vtable_segments<'tcx, T>(
25     tcx: TyCtxt<'tcx>,
26     trait_ref: ty::PolyTraitRef<'tcx>,
27     mut segment_visitor: impl FnMut(VtblSegment<'tcx>) -> ControlFlow<T>,
28 ) -> Option<T> {
29     // The following constraints holds for the final arrangement.
30     // 1. The whole virtual table of the first direct super trait is included as the
31     //    the prefix. If this trait doesn't have any super traits, then this step
32     //    consists of the dsa metadata.
33     // 2. Then comes the proper pointer metadata(vptr) and all own methods for all
34     //    other super traits except those already included as part of the first
35     //    direct super trait virtual table.
36     // 3. finally, the own methods of this trait.
37 
38     // This has the advantage that trait upcasting to the first direct super trait on each level
39     // is zero cost, and to another trait includes only replacing the pointer with one level indirection,
40     // while not using too much extra memory.
41 
42     // For a single inheritance relationship like this,
43     //   D --> C --> B --> A
44     // The resulting vtable will consists of these segments:
45     //  DSA, A, B, C, D
46 
47     // For a multiple inheritance relationship like this,
48     //   D --> C --> A
49     //           \-> B
50     // The resulting vtable will consists of these segments:
51     //  DSA, A, B, B-vptr, C, D
52 
53     // For a diamond inheritance relationship like this,
54     //   D --> B --> A
55     //     \-> C -/
56     // The resulting vtable will consists of these segments:
57     //  DSA, A, B, C, C-vptr, D
58 
59     // For a more complex inheritance relationship like this:
60     //   O --> G --> C --> A
61     //     \     \     \-> B
62     //     |     |-> F --> D
63     //     |           \-> E
64     //     |-> N --> J --> H
65     //           \     \-> I
66     //           |-> M --> K
67     //                 \-> L
68     // The resulting vtable will consists of these segments:
69     //  DSA, A, B, B-vptr, C, D, D-vptr, E, E-vptr, F, F-vptr, G,
70     //  H, H-vptr, I, I-vptr, J, J-vptr, K, K-vptr, L, L-vptr, M, M-vptr,
71     //  N, N-vptr, O
72 
73     // emit dsa segment first.
74     if let ControlFlow::Break(v) = (segment_visitor)(VtblSegment::MetadataDSA) {
75         return Some(v);
76     }
77 
78     let mut emit_vptr_on_new_entry = false;
79     let mut visited = PredicateSet::new(tcx);
80     let predicate = trait_ref.without_const().to_predicate(tcx);
81     let mut stack: SmallVec<[(ty::PolyTraitRef<'tcx>, _, _); 5]> =
82         smallvec![(trait_ref, emit_vptr_on_new_entry, None)];
83     visited.insert(predicate);
84 
85     // the main traversal loop:
86     // basically we want to cut the inheritance directed graph into a few non-overlapping slices of nodes
87     // that each node is emitted after all its descendents have been emitted.
88     // so we convert the directed graph into a tree by skipping all previously visited nodes using a visited set.
89     // this is done on the fly.
90     // Each loop run emits a slice - it starts by find a "childless" unvisited node, backtracking upwards, and it
91     // stops after it finds a node that has a next-sibling node.
92     // This next-sibling node will used as the starting point of next slice.
93 
94     // Example:
95     // For a diamond inheritance relationship like this,
96     //   D#1 --> B#0 --> A#0
97     //     \-> C#1 -/
98 
99     // Starting point 0 stack [D]
100     // Loop run #0: Stack after diving in is [D B A], A is "childless"
101     // after this point, all newly visited nodes won't have a vtable that equals to a prefix of this one.
102     // Loop run #0: Emitting the slice [B A] (in reverse order), B has a next-sibling node, so this slice stops here.
103     // Loop run #0: Stack after exiting out is [D C], C is the next starting point.
104     // Loop run #1: Stack after diving in is [D C], C is "childless", since its child A is skipped(already emitted).
105     // Loop run #1: Emitting the slice [D C] (in reverse order). No one has a next-sibling node.
106     // Loop run #1: Stack after exiting out is []. Now the function exits.
107 
108     loop {
109         // dive deeper into the stack, recording the path
110         'diving_in: loop {
111             if let Some((inner_most_trait_ref, _, _)) = stack.last() {
112                 let inner_most_trait_ref = *inner_most_trait_ref;
113                 let mut direct_super_traits_iter = tcx
114                     .super_predicates_of(inner_most_trait_ref.def_id())
115                     .predicates
116                     .into_iter()
117                     .filter_map(move |(pred, _)| {
118                         pred.subst_supertrait(tcx, &inner_most_trait_ref).as_trait_clause()
119                     });
120 
121                 'diving_in_skip_visited_traits: loop {
122                     if let Some(next_super_trait) = direct_super_traits_iter.next() {
123                         if visited.insert(next_super_trait.to_predicate(tcx)) {
124                             // We're throwing away potential constness of super traits here.
125                             // FIXME: handle ~const super traits
126                             let next_super_trait = next_super_trait.map_bound(|t| t.trait_ref);
127                             stack.push((
128                                 next_super_trait,
129                                 emit_vptr_on_new_entry,
130                                 Some(direct_super_traits_iter),
131                             ));
132                             break 'diving_in_skip_visited_traits;
133                         } else {
134                             continue 'diving_in_skip_visited_traits;
135                         }
136                     } else {
137                         break 'diving_in;
138                     }
139                 }
140             }
141         }
142 
143         // Other than the left-most path, vptr should be emitted for each trait.
144         emit_vptr_on_new_entry = true;
145 
146         // emit innermost item, move to next sibling and stop there if possible, otherwise jump to outer level.
147         'exiting_out: loop {
148             if let Some((inner_most_trait_ref, emit_vptr, siblings_opt)) = stack.last_mut() {
149                 if let ControlFlow::Break(v) = (segment_visitor)(VtblSegment::TraitOwnEntries {
150                     trait_ref: *inner_most_trait_ref,
151                     emit_vptr: *emit_vptr,
152                 }) {
153                     return Some(v);
154                 }
155 
156                 'exiting_out_skip_visited_traits: loop {
157                     if let Some(siblings) = siblings_opt {
158                         if let Some(next_inner_most_trait_ref) = siblings.next() {
159                             if visited.insert(next_inner_most_trait_ref.to_predicate(tcx)) {
160                                 // We're throwing away potential constness of super traits here.
161                                 // FIXME: handle ~const super traits
162                                 let next_inner_most_trait_ref =
163                                     next_inner_most_trait_ref.map_bound(|t| t.trait_ref);
164                                 *inner_most_trait_ref = next_inner_most_trait_ref;
165                                 *emit_vptr = emit_vptr_on_new_entry;
166                                 break 'exiting_out;
167                             } else {
168                                 continue 'exiting_out_skip_visited_traits;
169                             }
170                         }
171                     }
172                     stack.pop();
173                     continue 'exiting_out;
174                 }
175             }
176             // all done
177             return None;
178         }
179     }
180 }
181 
dump_vtable_entries<'tcx>( tcx: TyCtxt<'tcx>, sp: Span, trait_ref: ty::PolyTraitRef<'tcx>, entries: &[VtblEntry<'tcx>], )182 fn dump_vtable_entries<'tcx>(
183     tcx: TyCtxt<'tcx>,
184     sp: Span,
185     trait_ref: ty::PolyTraitRef<'tcx>,
186     entries: &[VtblEntry<'tcx>],
187 ) {
188     tcx.sess.emit_err(DumpVTableEntries {
189         span: sp,
190         trait_ref,
191         entries: format!("{:#?}", entries),
192     });
193 }
194 
own_existential_vtable_entries(tcx: TyCtxt<'_>, trait_def_id: DefId) -> &[DefId]195 fn own_existential_vtable_entries(tcx: TyCtxt<'_>, trait_def_id: DefId) -> &[DefId] {
196     let trait_methods = tcx
197         .associated_items(trait_def_id)
198         .in_definition_order()
199         .filter(|item| item.kind == ty::AssocKind::Fn);
200     // Now list each method's DefId (for within its trait).
201     let own_entries = trait_methods.filter_map(move |&trait_method| {
202         debug!("own_existential_vtable_entry: trait_method={:?}", trait_method);
203         let def_id = trait_method.def_id;
204 
205         // Some methods cannot be called on an object; skip those.
206         if !is_vtable_safe_method(tcx, trait_def_id, trait_method) {
207             debug!("own_existential_vtable_entry: not vtable safe");
208             return None;
209         }
210 
211         Some(def_id)
212     });
213 
214     tcx.arena.alloc_from_iter(own_entries.into_iter())
215 }
216 
217 /// Given a trait `trait_ref`, iterates the vtable entries
218 /// that come from `trait_ref`, including its supertraits.
vtable_entries<'tcx>( tcx: TyCtxt<'tcx>, trait_ref: ty::PolyTraitRef<'tcx>, ) -> &'tcx [VtblEntry<'tcx>]219 fn vtable_entries<'tcx>(
220     tcx: TyCtxt<'tcx>,
221     trait_ref: ty::PolyTraitRef<'tcx>,
222 ) -> &'tcx [VtblEntry<'tcx>] {
223     debug!("vtable_entries({:?})", trait_ref);
224 
225     let mut entries = vec![];
226 
227     let vtable_segment_callback = |segment| -> ControlFlow<()> {
228         match segment {
229             VtblSegment::MetadataDSA => {
230                 entries.extend(TyCtxt::COMMON_VTABLE_ENTRIES);
231             }
232             VtblSegment::TraitOwnEntries { trait_ref, emit_vptr } => {
233                 let existential_trait_ref = trait_ref
234                     .map_bound(|trait_ref| ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref));
235 
236                 // Lookup the shape of vtable for the trait.
237                 let own_existential_entries =
238                     tcx.own_existential_vtable_entries(existential_trait_ref.def_id());
239 
240                 let own_entries = own_existential_entries.iter().copied().map(|def_id| {
241                     debug!("vtable_entries: trait_method={:?}", def_id);
242 
243                     // The method may have some early-bound lifetimes; add regions for those.
244                     let substs = trait_ref.map_bound(|trait_ref| {
245                         InternalSubsts::for_item(tcx, def_id, |param, _| match param.kind {
246                             GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(),
247                             GenericParamDefKind::Type { .. }
248                             | GenericParamDefKind::Const { .. } => {
249                                 trait_ref.substs[param.index as usize]
250                             }
251                         })
252                     });
253 
254                     // The trait type may have higher-ranked lifetimes in it;
255                     // erase them if they appear, so that we get the type
256                     // at some particular call site.
257                     let substs = tcx
258                         .normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), substs);
259 
260                     // It's possible that the method relies on where-clauses that
261                     // do not hold for this particular set of type parameters.
262                     // Note that this method could then never be called, so we
263                     // do not want to try and codegen it, in that case (see #23435).
264                     let predicates = tcx.predicates_of(def_id).instantiate_own(tcx, substs);
265                     if impossible_predicates(
266                         tcx,
267                         predicates.map(|(predicate, _)| predicate).collect(),
268                     ) {
269                         debug!("vtable_entries: predicates do not hold");
270                         return VtblEntry::Vacant;
271                     }
272 
273                     let instance = ty::Instance::resolve_for_vtable(
274                         tcx,
275                         ty::ParamEnv::reveal_all(),
276                         def_id,
277                         substs,
278                     )
279                     .expect("resolution failed during building vtable representation");
280                     VtblEntry::Method(instance)
281                 });
282 
283                 entries.extend(own_entries);
284 
285                 if emit_vptr {
286                     entries.push(VtblEntry::TraitVPtr(trait_ref));
287                 }
288             }
289         }
290 
291         ControlFlow::Continue(())
292     };
293 
294     let _ = prepare_vtable_segments(tcx, trait_ref, vtable_segment_callback);
295 
296     if tcx.has_attr(trait_ref.def_id(), sym::rustc_dump_vtable) {
297         let sp = tcx.def_span(trait_ref.def_id());
298         dump_vtable_entries(tcx, sp, trait_ref, &entries);
299     }
300 
301     tcx.arena.alloc_from_iter(entries.into_iter())
302 }
303 
304 /// Find slot base for trait methods within vtable entries of another trait
vtable_trait_first_method_offset<'tcx>( tcx: TyCtxt<'tcx>, key: ( ty::PolyTraitRef<'tcx>, ty::PolyTraitRef<'tcx>, ), ) -> usize305 pub(super) fn vtable_trait_first_method_offset<'tcx>(
306     tcx: TyCtxt<'tcx>,
307     key: (
308         ty::PolyTraitRef<'tcx>, // trait_to_be_found
309         ty::PolyTraitRef<'tcx>, // trait_owning_vtable
310     ),
311 ) -> usize {
312     let (trait_to_be_found, trait_owning_vtable) = key;
313 
314     // #90177
315     let trait_to_be_found_erased = tcx.erase_regions(trait_to_be_found);
316 
317     let vtable_segment_callback = {
318         let mut vtable_base = 0;
319 
320         move |segment| {
321             match segment {
322                 VtblSegment::MetadataDSA => {
323                     vtable_base += TyCtxt::COMMON_VTABLE_ENTRIES.len();
324                 }
325                 VtblSegment::TraitOwnEntries { trait_ref, emit_vptr } => {
326                     if tcx.erase_regions(trait_ref) == trait_to_be_found_erased {
327                         return ControlFlow::Break(vtable_base);
328                     }
329                     vtable_base += count_own_vtable_entries(tcx, trait_ref);
330                     if emit_vptr {
331                         vtable_base += 1;
332                     }
333                 }
334             }
335             ControlFlow::Continue(())
336         }
337     };
338 
339     if let Some(vtable_base) =
340         prepare_vtable_segments(tcx, trait_owning_vtable, vtable_segment_callback)
341     {
342         vtable_base
343     } else {
344         bug!("Failed to find info for expected trait in vtable");
345     }
346 }
347 
348 /// Find slot offset for trait vptr within vtable entries of another trait
vtable_trait_upcasting_coercion_new_vptr_slot<'tcx>( tcx: TyCtxt<'tcx>, key: ( Ty<'tcx>, Ty<'tcx>, ), ) -> Option<usize>349 pub(crate) fn vtable_trait_upcasting_coercion_new_vptr_slot<'tcx>(
350     tcx: TyCtxt<'tcx>,
351     key: (
352         Ty<'tcx>, // trait object type whose trait owning vtable
353         Ty<'tcx>, // trait object for supertrait
354     ),
355 ) -> Option<usize> {
356     let (source, target) = key;
357     assert!(matches!(&source.kind(), &ty::Dynamic(..)) && !source.has_infer());
358     assert!(matches!(&target.kind(), &ty::Dynamic(..)) && !target.has_infer());
359 
360     // this has been typecked-before, so diagnostics is not really needed.
361     let unsize_trait_did = tcx.require_lang_item(LangItem::Unsize, None);
362 
363     let trait_ref = ty::TraitRef::new(tcx, unsize_trait_did, [source, target]);
364 
365     match tcx.codegen_select_candidate((ty::ParamEnv::reveal_all(), trait_ref)) {
366         Ok(ImplSource::TraitUpcasting(implsrc_traitcasting)) => {
367             implsrc_traitcasting.vtable_vptr_slot
368         }
369         otherwise => bug!("expected TraitUpcasting candidate, got {otherwise:?}"),
370     }
371 }
372 
373 /// Given a trait `trait_ref`, returns the number of vtable entries
374 /// that come from `trait_ref`, excluding its supertraits. Used in
375 /// computing the vtable base for an upcast trait of a trait object.
count_own_vtable_entries<'tcx>( tcx: TyCtxt<'tcx>, trait_ref: ty::PolyTraitRef<'tcx>, ) -> usize376 pub(crate) fn count_own_vtable_entries<'tcx>(
377     tcx: TyCtxt<'tcx>,
378     trait_ref: ty::PolyTraitRef<'tcx>,
379 ) -> usize {
380     tcx.own_existential_vtable_entries(trait_ref.def_id()).len()
381 }
382 
provide(providers: &mut Providers)383 pub(super) fn provide(providers: &mut Providers) {
384     *providers = Providers {
385         own_existential_vtable_entries,
386         vtable_entries,
387         vtable_trait_upcasting_coercion_new_vptr_slot,
388         ..*providers
389     };
390 }
391