Skip to main content

rustc_trait_selection/traits/
vtable.rs

1use std::fmt::Debug;
2use std::ops::ControlFlow;
3
4use rustc_hir::def_id::DefId;
5use rustc_infer::traits::util::PredicateSet;
6use rustc_middle::query::Providers;
7use rustc_middle::ty::{
8    self, GenericArgs, GenericParamDefKind, Ty, TyCtxt, TypeVisitableExt, Unnormalized, Upcast,
9    VtblEntry,
10};
11use rustc_span::{DUMMY_SP, bug};
12use smallvec::{SmallVec, smallvec};
13use tracing::debug;
14
15use crate::traits::is_vtable_safe_method;
16
17#[derive(#[automatically_derived]impl<'tcx> ::core::clone::Clone for VtblSegment<'tcx>
    {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        match self {
            Self::MetadataDSA => VtblSegment::MetadataDSA,
            Self::TraitOwnEntries { trait_ref: __self_0, emit_vptr: __self_1 }
                =>
                VtblSegment::TraitOwnEntries {
                    trait_ref: ::core::clone::Clone::clone(__self_0),
                    emit_vptr: ::core::clone::Clone::clone(__self_1),
                },
        }
    }
}Clone, #[automatically_derived]impl<'tcx> ::core::fmt::Debug for VtblSegment<'tcx> {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::MetadataDSA =>
                ::core::fmt::Formatter::write_str(f, "MetadataDSA"),
            Self::TraitOwnEntries { trait_ref: __self_0, emit_vptr: __self_1 }
                =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "TraitOwnEntries trait_ref emit_vptr", __self_0, &__self_1),
        }
    }
}Debug)]
18pub enum VtblSegment<'tcx> {
19    /// The segment containing Drop, Size and Align.
20    MetadataDSA,
21    /// A segment with the methods of a particular trait.
22    TraitOwnEntries { trait_ref: ty::TraitRef<'tcx>, emit_vptr: bool },
23}
24
25/// Prepare the segments for a vtable
26// FIXME: This should take a `PolyExistentialTraitRef`, since we don't care
27// about our `Self` type here.
28pub fn prepare_vtable_segments<'tcx, T>(
29    tcx: TyCtxt<'tcx>,
30    trait_ref: ty::TraitRef<'tcx>,
31    segment_visitor: impl FnMut(VtblSegment<'tcx>) -> ControlFlow<T>,
32) -> Option<T> {
33    prepare_vtable_segments_inner(tcx, trait_ref, segment_visitor).break_value()
34}
35
36/// Helper for [`prepare_vtable_segments`] that returns `ControlFlow`,
37/// such that we can use `?` in the body.
38fn prepare_vtable_segments_inner<'tcx, T>(
39    tcx: TyCtxt<'tcx>,
40    trait_ref: ty::TraitRef<'tcx>,
41    mut segment_visitor: impl FnMut(VtblSegment<'tcx>) -> ControlFlow<T>,
42) -> ControlFlow<T> {
43    // The following constraints holds for the final arrangement.
44    // 1. The whole virtual table of the first direct super trait is included as the
45    //    the prefix. If this trait doesn't have any super traits, then this step
46    //    consists of the dsa metadata.
47    // 2. Then comes the proper pointer metadata(vptr) and all own methods for all
48    //    other super traits except those already included as part of the first
49    //    direct super trait virtual table.
50    // 3. finally, the own methods of this trait.
51
52    // This has the advantage that trait upcasting to the first direct super trait on each level
53    // is zero cost, and to another trait includes only replacing the pointer with one level indirection,
54    // while not using too much extra memory.
55
56    // For a single inheritance relationship like this,
57    //   D --> C --> B --> A
58    // The resulting vtable will consists of these segments:
59    //  DSA, A, B, C, D
60
61    // For a multiple inheritance relationship like this,
62    //   D --> C --> A
63    //           \-> B
64    // The resulting vtable will consists of these segments:
65    //  DSA, A, B, B-vptr, C, D
66
67    // For a diamond inheritance relationship like this,
68    //   D --> B --> A
69    //     \-> C -/
70    // The resulting vtable will consists of these segments:
71    //  DSA, A, B, C, C-vptr, D
72
73    // For a more complex inheritance relationship like this:
74    //   O --> G --> C --> A
75    //     \     \     \-> B
76    //     |     |-> F --> D
77    //     |           \-> E
78    //     |-> N --> J --> H
79    //           \     \-> I
80    //           |-> M --> K
81    //                 \-> L
82    // The resulting vtable will consists of these segments:
83    //  DSA, A, B, B-vptr, C, D, D-vptr, E, E-vptr, F, F-vptr, G,
84    //  H, H-vptr, I, I-vptr, J, J-vptr, K, K-vptr, L, L-vptr, M, M-vptr,
85    //  N, N-vptr, O
86
87    // emit dsa segment first.
88    segment_visitor(VtblSegment::MetadataDSA)?;
89
90    let mut emit_vptr_on_new_entry = false;
91    let mut visited = PredicateSet::new(tcx);
92    let predicate = trait_ref.upcast(tcx);
93    let mut stack: SmallVec<[(ty::TraitRef<'tcx>, _, _); 5]> =
94        {
    let count = 0usize + 1usize;
    let mut vec = ::smallvec::SmallVec::new();
    if count <= vec.inline_size() {
        vec.push((trait_ref, emit_vptr_on_new_entry, maybe_iter(None)));
        vec
    } else {
        ::smallvec::SmallVec::from_vec(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                    [(trait_ref, emit_vptr_on_new_entry, maybe_iter(None))])))
    }
}smallvec![(trait_ref, emit_vptr_on_new_entry, maybe_iter(None))];
95    visited.insert(predicate);
96
97    // the main traversal loop:
98    // basically we want to cut the inheritance directed graph into a few non-overlapping slices of nodes
99    // such that each node is emitted after all its descendants have been emitted.
100    // so we convert the directed graph into a tree by skipping all previously visited nodes using a visited set.
101    // this is done on the fly.
102    // Each loop run emits a slice - it starts by find a "childless" unvisited node, backtracking upwards, and it
103    // stops after it finds a node that has a next-sibling node.
104    // This next-sibling node will used as the starting point of next slice.
105
106    // Example:
107    // For a diamond inheritance relationship like this,
108    //   D#1 --> B#0 --> A#0
109    //     \-> C#1 -/
110
111    // Starting point 0 stack [D]
112    // Loop run #0: Stack after diving in is [D B A], A is "childless"
113    // after this point, all newly visited nodes won't have a vtable that equals to a prefix of this one.
114    // Loop run #0: Emitting the slice [B A] (in reverse order), B has a next-sibling node, so this slice stops here.
115    // Loop run #0: Stack after exiting out is [D C], C is the next starting point.
116    // Loop run #1: Stack after diving in is [D C], C is "childless", since its child A is skipped(already emitted).
117    // Loop run #1: Emitting the slice [D C] (in reverse order). No one has a next-sibling node.
118    // Loop run #1: Stack after exiting out is []. Now the function exits.
119
120    'outer: loop {
121        // dive deeper into the stack, recording the path
122        'diving_in: loop {
123            let &(inner_most_trait_ref, _, _) = stack.last().unwrap();
124
125            let mut direct_super_traits_iter = tcx
126                .explicit_super_clauses_of(inner_most_trait_ref.def_id)
127                .iter_identity_copied()
128                .map(Unnormalized::skip_norm_wip)
129                .filter_map(move |(clause, _)| {
130                    clause
131                        .instantiate_supertrait(tcx, ty::Binder::dummy(inner_most_trait_ref))
132                        .as_trait_clause()
133                })
134                .map(move |pred| {
135                    tcx.normalize_erasing_late_bound_regions(
136                        ty::TypingEnv::fully_monomorphized(),
137                        pred,
138                    )
139                    .trait_ref
140                });
141
142            // Find an unvisited supertrait
143            match direct_super_traits_iter
144                .find(|&super_trait| visited.insert(super_trait.upcast(tcx)))
145            {
146                // Push it to the stack for the next iteration of 'diving_in to pick up
147                Some(next_super_trait) => stack.push((
148                    next_super_trait,
149                    emit_vptr_on_new_entry,
150                    maybe_iter(Some(direct_super_traits_iter)),
151                )),
152
153                // There are no more unvisited direct super traits, dive-in finished
154                None => break 'diving_in,
155            }
156        }
157
158        // emit innermost item, move to next sibling and stop there if possible, otherwise jump to outer level.
159        while let Some((inner_most_trait_ref, emit_vptr, mut siblings)) = stack.pop() {
160            // We don't need to emit a vptr for "truly-empty" supertraits, but we *do* need to emit a
161            // vptr for supertraits that have no methods, but that themselves have supertraits
162            // with methods, so we check if any transitive supertrait has entries here (this includes
163            // the trait itself).
164            let has_entries = ty::elaborate::supertrait_def_ids(tcx, inner_most_trait_ref.def_id)
165                .any(|def_id| has_own_existential_vtable_entries(tcx, def_id));
166
167            segment_visitor(VtblSegment::TraitOwnEntries {
168                trait_ref: inner_most_trait_ref,
169                emit_vptr: emit_vptr && has_entries && !tcx.sess.opts.unstable_opts.no_trait_vptr,
170            })?;
171
172            // If we've emitted (fed to `segment_visitor`) a trait that has methods present in the vtable,
173            // we'll need to emit vptrs from now on.
174            emit_vptr_on_new_entry |= has_entries;
175
176            if let Some(next_inner_most_trait_ref) =
177                siblings.find(|&sibling| visited.insert(sibling.upcast(tcx)))
178            {
179                stack.push((next_inner_most_trait_ref, emit_vptr_on_new_entry, siblings));
180
181                // just pushed a new trait onto the stack, so we need to go through its super traits
182                continue 'outer;
183            }
184        }
185
186        // the stack is empty, all done
187        return ControlFlow::Continue(());
188    }
189}
190
191/// Turns option of iterator into an iterator (this is just flatten)
192fn maybe_iter<I: Iterator>(i: Option<I>) -> impl Iterator<Item = I::Item> {
193    i.into_flat_iter()
194}
195
196fn has_own_existential_vtable_entries(tcx: TyCtxt<'_>, trait_def_id: DefId) -> bool {
197    own_existential_vtable_entries_iter(tcx, trait_def_id).next().is_some()
198}
199
200fn own_existential_vtable_entries(tcx: TyCtxt<'_>, trait_def_id: DefId) -> &[DefId] {
201    tcx.arena.alloc_from_iter(own_existential_vtable_entries_iter(tcx, trait_def_id))
202}
203
204fn own_existential_vtable_entries_iter(
205    tcx: TyCtxt<'_>,
206    trait_def_id: DefId,
207) -> impl Iterator<Item = DefId> {
208    let trait_methods =
209        tcx.associated_items(trait_def_id).in_definition_order().filter(|item| item.is_fn());
210
211    // Now list each method's DefId (for within its trait).
212    let own_entries = trait_methods.filter_map(move |&trait_method| {
213        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/vtable.rs:213",
                        "rustc_trait_selection::traits::vtable",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/vtable.rs"),
                        ::tracing_core::__macro_support::Option::Some(213u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::vtable"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("own_existential_vtable_entry: trait_method={0:?}",
                                                    trait_method) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("own_existential_vtable_entry: trait_method={:?}", trait_method);
214        let def_id = trait_method.def_id;
215
216        // Final methods should not be included in the vtable.
217        if trait_method.defaultness(tcx).is_final() {
218            return None;
219        }
220
221        // Some methods cannot be called on an object; skip those.
222        if !is_vtable_safe_method(tcx, trait_def_id, trait_method) {
223            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/vtable.rs:223",
                        "rustc_trait_selection::traits::vtable",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/vtable.rs"),
                        ::tracing_core::__macro_support::Option::Some(223u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::vtable"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("own_existential_vtable_entry: not vtable safe")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("own_existential_vtable_entry: not vtable safe");
224            return None;
225        }
226
227        Some(def_id)
228    });
229
230    own_entries
231}
232
233/// Given a trait `trait_ref`, iterates the vtable entries
234/// that come from `trait_ref`, including its supertraits.
235fn vtable_entries<'tcx>(
236    tcx: TyCtxt<'tcx>,
237    trait_ref: ty::TraitRef<'tcx>,
238) -> &'tcx [VtblEntry<'tcx>] {
239    if true {
    if !(!trait_ref.has_non_region_infer() &&
                !trait_ref.has_non_region_param()) {
        ::core::panicking::panic("assertion failed: !trait_ref.has_non_region_infer() && !trait_ref.has_non_region_param()")
    };
};debug_assert!(!trait_ref.has_non_region_infer() && !trait_ref.has_non_region_param());
240    tcx.debug_assert_fully_normalized(ty::TypingEnv::fully_monomorphized(), trait_ref);
241
242    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/vtable.rs:242",
                        "rustc_trait_selection::traits::vtable",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/vtable.rs"),
                        ::tracing_core::__macro_support::Option::Some(242u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::vtable"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("vtable_entries({0:?})",
                                                    trait_ref) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("vtable_entries({:?})", trait_ref);
243
244    let mut entries = ::alloc::vec::Vec::new()vec![];
245
246    let vtable_segment_callback = |segment| -> ControlFlow<()> {
247        match segment {
248            VtblSegment::MetadataDSA => {
249                entries.extend(TyCtxt::COMMON_VTABLE_ENTRIES);
250            }
251            VtblSegment::TraitOwnEntries { trait_ref, emit_vptr } => {
252                let existential_trait_ref = ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref);
253
254                // Lookup the shape of vtable for the trait.
255                let own_existential_entries =
256                    tcx.own_existential_vtable_entries(existential_trait_ref.def_id);
257
258                let own_entries = own_existential_entries.iter().copied().map(|def_id| {
259                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/vtable.rs:259",
                        "rustc_trait_selection::traits::vtable",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/vtable.rs"),
                        ::tracing_core::__macro_support::Option::Some(259u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::vtable"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("vtable_entries: trait_method={0:?}",
                                                    def_id) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("vtable_entries: trait_method={:?}", def_id);
260
261                    // The method may have some early-bound lifetimes; add regions for those.
262                    // FIXME: Is this normalize needed?
263                    let args = tcx.normalize_erasing_regions(
264                        ty::TypingEnv::fully_monomorphized(),
265                        Unnormalized::new_wip(GenericArgs::for_item(tcx, def_id, |param, _| {
266                            match param.kind {
267                                GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(),
268                                GenericParamDefKind::Type { .. }
269                                | GenericParamDefKind::Const { .. } => {
270                                    trait_ref.args[param.index as usize]
271                                }
272                            }
273                        })),
274                    );
275
276                    // It's possible that the method relies on where-clauses that
277                    // do not hold for this particular set of type parameters.
278                    // Note that this method could then never be called, so we
279                    // do not want to try and codegen it, in that case (see #23435).
280                    if tcx.instantiate_and_check_impossible_clauses((def_id, args)) {
281                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/vtable.rs:281",
                        "rustc_trait_selection::traits::vtable",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/064405c5f7fbc7d41aa30b45da1e45a85777bd58/compiler/rustc_trait_selection/src/traits/vtable.rs"),
                        ::tracing_core::__macro_support::Option::Some(281u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::vtable"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("vtable_entries: clauses do not hold")
                                            as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("vtable_entries: clauses do not hold");
282                        return VtblEntry::Vacant;
283                    }
284
285                    let instance = ty::Instance::expect_resolve_for_vtable(
286                        tcx,
287                        ty::TypingEnv::fully_monomorphized(),
288                        def_id,
289                        args,
290                        DUMMY_SP,
291                    );
292
293                    VtblEntry::Method(instance)
294                });
295
296                entries.extend(own_entries);
297
298                if emit_vptr {
299                    entries.push(VtblEntry::TraitVPtr(trait_ref));
300                }
301            }
302        }
303
304        ControlFlow::Continue(())
305    };
306
307    let _ = prepare_vtable_segments(tcx, trait_ref, vtable_segment_callback);
308
309    tcx.arena.alloc_from_iter(entries)
310}
311
312// Given a `dyn Subtrait: Supertrait` trait ref, find corresponding first slot
313// for `Supertrait`'s methods in the vtable of `Subtrait`.
314//
315// Returns `None` if and only if an error was already reported elsewhere.
316pub(crate) fn first_method_vtable_slot<'tcx>(
317    tcx: TyCtxt<'tcx>,
318    key: ty::TraitRef<'tcx>,
319) -> Option<usize> {
320    if true {
    if !(!key.has_non_region_infer() && !key.has_non_region_param()) {
        ::core::panicking::panic("assertion failed: !key.has_non_region_infer() && !key.has_non_region_param()")
    };
};debug_assert!(!key.has_non_region_infer() && !key.has_non_region_param());
321    tcx.assert_fully_normalized(ty::TypingEnv::fully_monomorphized(), key);
322
323    let ty::Dynamic(source, _) = *key.self_ty().kind() else {
324        ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller());bug!();
325    };
326    let source_principal = tcx.instantiate_bound_regions_with_erased(
327        source.principal().unwrap().with_self_ty(tcx, key.self_ty()),
328    );
329
330    // We're monomorphizing a call to a dyn trait object that can never be constructed.
331    if tcx
332        .instantiate_and_check_impossible_clauses((source_principal.def_id, source_principal.args))
333    {
334        return Some(0);
335    }
336
337    let target_principal = ty::ExistentialTraitRef::erase_self_ty(tcx, key);
338
339    let vtable_segment_callback = {
340        let mut vptr_offset = 0;
341        move |segment| {
342            match segment {
343                VtblSegment::MetadataDSA => {
344                    vptr_offset += TyCtxt::COMMON_VTABLE_ENTRIES.len();
345                }
346                VtblSegment::TraitOwnEntries { trait_ref: vtable_principal, emit_vptr } => {
347                    if ty::ExistentialTraitRef::erase_self_ty(tcx, vtable_principal)
348                        == target_principal
349                    {
350                        return ControlFlow::Break(vptr_offset);
351                    }
352
353                    vptr_offset +=
354                        tcx.own_existential_vtable_entries(vtable_principal.def_id).len();
355
356                    if emit_vptr {
357                        vptr_offset += 1;
358                    }
359                }
360            }
361            ControlFlow::Continue(())
362        }
363    };
364
365    let index = prepare_vtable_segments(tcx, source_principal, vtable_segment_callback);
366
367    if index.is_none() {
368        // This can happen if the trait hierarchy is malformed (e.g., due to
369        // missing generics on a supertrait bound). There should already be an error
370        // emitted for this, so we just delay the ICE.
371        tcx.dcx().delayed_bug(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("could not find the supertrait vtable slot for `{0}` -> `{1}`",
                source, target_principal))
    })format!(
372            "could not find the supertrait vtable slot for `{}` -> `{}`",
373            source, target_principal
374        ));
375    }
376
377    index
378}
379
380/// Given a `dyn Subtrait` and `dyn Supertrait` trait object, find the slot of
381/// the trait vptr in the subtrait's vtable.
382///
383/// A return value of `None` means that the original vtable can be reused.
384pub(crate) fn supertrait_vtable_slot<'tcx>(
385    tcx: TyCtxt<'tcx>,
386    key: (
387        Ty<'tcx>, // Source -- `dyn Subtrait`.
388        Ty<'tcx>, // Target -- `dyn Supertrait` being coerced to.
389    ),
390) -> Option<usize> {
391    if true {
    if !(!key.has_non_region_infer() && !key.has_non_region_param()) {
        ::core::panicking::panic("assertion failed: !key.has_non_region_infer() && !key.has_non_region_param()")
    };
};debug_assert!(!key.has_non_region_infer() && !key.has_non_region_param());
392    tcx.debug_assert_fully_normalized(ty::TypingEnv::fully_monomorphized(), key);
393
394    let (source, target) = key;
395
396    // If the target principal is `None`, we can just return `None`.
397    let ty::Dynamic(target_data, _) = *target.kind() else {
398        ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller());bug!();
399    };
400    let target_principal = tcx.instantiate_bound_regions_with_erased(target_data.principal()?);
401
402    // Given that we have a target principal, it is a bug for there not to be a source principal.
403    let ty::Dynamic(source_data, _) = *source.kind() else {
404        ::rustc_span::macros::bug_impl(None, format_args!("impossible case reached"),
    Location::caller());bug!();
405    };
406    let source_principal = tcx.instantiate_bound_regions_with_erased(
407        source_data.principal().unwrap().with_self_ty(tcx, source),
408    );
409
410    // We're monomorphizing a dyn trait object upcast that can never be constructed.
411    if tcx
412        .instantiate_and_check_impossible_clauses((source_principal.def_id, source_principal.args))
413    {
414        return None;
415    }
416
417    let vtable_segment_callback = {
418        let mut vptr_offset = 0;
419        move |segment| {
420            match segment {
421                VtblSegment::MetadataDSA => {
422                    vptr_offset += TyCtxt::COMMON_VTABLE_ENTRIES.len();
423                }
424                VtblSegment::TraitOwnEntries { trait_ref: vtable_principal, emit_vptr } => {
425                    vptr_offset +=
426                        tcx.own_existential_vtable_entries(vtable_principal.def_id).len();
427                    if ty::ExistentialTraitRef::erase_self_ty(tcx, vtable_principal)
428                        == target_principal
429                    {
430                        if emit_vptr {
431                            return ControlFlow::Break(Some(vptr_offset));
432                        } else {
433                            return ControlFlow::Break(None);
434                        }
435                    }
436
437                    if emit_vptr {
438                        vptr_offset += 1;
439                    }
440                }
441            }
442            ControlFlow::Continue(())
443        }
444    };
445
446    prepare_vtable_segments(tcx, source_principal, vtable_segment_callback).unwrap_or_else(|| {
447        // This can happen if the trait hierarchy is malformed (e.g., due to
448        // missing generics on a supertrait bound). There should already be an error
449        // emitted for this, so we just delay the ICE.
450        tcx.dcx().delayed_bug(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("could not find the supertrait vtable slot for `{0}` -> `{1}`",
                source, target))
    })format!(
451            "could not find the supertrait vtable slot for `{}` -> `{}`",
452            source, target
453        ));
454        None
455    })
456}
457
458/// Returns the traits that are prefixes of this vtable, such that upcasting to these traits
459/// reuses the vtable pointer unchanged.
460///
461/// For a `trait Foo: A + B`, the methods for A are stored as a prefix to the vtable for Foo.
462/// If B has no methods, it is also part of this prefix (although it takes up no space).
463///
464/// This function returns the full set of these traits (A might have its own supertrait, etc.).
465/// The input trait is the last element of the output vector.
466pub fn vtable_prefix_traits<'tcx>(
467    tcx: TyCtxt<'tcx>,
468    key: ty::TraitRef<'tcx>,
469) -> Vec<ty::ExistentialTraitRef<'tcx>> {
470    if true {
    if !(!key.has_non_region_infer() && !key.has_non_region_param()) {
        ::core::panicking::panic("assertion failed: !key.has_non_region_infer() && !key.has_non_region_param()")
    };
};debug_assert!(!key.has_non_region_infer() && !key.has_non_region_param());
471
472    let mut entries = ::alloc::vec::Vec::new()vec![];
473
474    let vtable_segment_callback = |segment| -> ControlFlow<()> {
475        // When `emit_vptr: false`, this trait's vtable is a prefix of `key`'s vtable.
476        if let VtblSegment::TraitOwnEntries { trait_ref, emit_vptr: false } = segment {
477            entries.push(ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref));
478        }
479
480        ControlFlow::Continue(())
481    };
482
483    let _ = prepare_vtable_segments(tcx, key, vtable_segment_callback);
484
485    // The input trait is the last element in the output vector.
486    if true {
    {
        match (&entries.last(),
                &Some(&ty::ExistentialTraitRef::erase_self_ty(tcx, key))) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(entries.last(), Some(&ty::ExistentialTraitRef::erase_self_ty(tcx, key)));
487
488    entries
489}
490
491pub(super) fn provide(providers: &mut Providers) {
492    *providers = Providers {
493        own_existential_vtable_entries,
494        vtable_entries,
495        first_method_vtable_slot,
496        supertrait_vtable_slot,
497        ..*providers
498    };
499}