Skip to main content

rustc_monomorphize/
collector.rs

1//! Mono Item Collection
2//! ====================
3//!
4//! This module is responsible for discovering all items that will contribute
5//! to code generation of the crate. The important part here is that it not only
6//! needs to find syntax-level items (functions, structs, etc) but also all
7//! their monomorphized instantiations. Every non-generic, non-const function
8//! maps to one LLVM artifact. Every generic function can produce
9//! from zero to N artifacts, depending on the sets of type arguments it
10//! is instantiated with.
11//! This also applies to generic items from other crates: A generic definition
12//! in crate X might produce monomorphizations that are compiled into crate Y.
13//! We also have to collect these here.
14//!
15//! The following kinds of "mono items" are handled here:
16//!
17//! - Functions
18//! - Methods
19//! - Closures
20//! - Statics
21//! - Drop glue
22//!
23//! The following things also result in LLVM artifacts, but are not collected
24//! here, since we instantiate them locally on demand when needed in a given
25//! codegen unit:
26//!
27//! - Constants
28//! - VTables
29//! - Object Shims
30//!
31//! The main entry point is `collect_crate_mono_items`, at the bottom of this file.
32//!
33//! General Algorithm
34//! -----------------
35//! Let's define some terms first:
36//!
37//! - A "mono item" is something that results in a function or global in
38//!   the LLVM IR of a codegen unit. Mono items do not stand on their
39//!   own, they can use other mono items. For example, if function
40//!   `foo()` calls function `bar()` then the mono item for `foo()`
41//!   uses the mono item for function `bar()`. In general, the
42//!   definition for mono item A using a mono item B is that
43//!   the LLVM artifact produced for A uses the LLVM artifact produced
44//!   for B.
45//!
46//! - Mono items and the uses between them form a directed graph,
47//!   where the mono items are the nodes and uses form the edges.
48//!   Let's call this graph the "mono item graph".
49//!
50//! - The mono item graph for a program contains all mono items
51//!   that are needed in order to produce the complete LLVM IR of the program.
52//!
53//! The purpose of the algorithm implemented in this module is to build the
54//! mono item graph for the current crate. It runs in two phases:
55//!
56//! 1. Discover the roots of the graph by traversing the HIR of the crate.
57//! 2. Starting from the roots, find uses by inspecting the MIR
58//!    representation of the item corresponding to a given node, until no more
59//!    new nodes are found.
60//!
61//! ### Discovering roots
62//! The roots of the mono item graph correspond to the public non-generic
63//! syntactic items in the source code. We find them by walking the HIR of the
64//! crate, and whenever we hit upon a public function, method, or static item,
65//! we create a mono item consisting of the items DefId and, since we only
66//! consider non-generic items, an empty type-parameters set. (In eager
67//! collection mode, during incremental compilation, all non-generic functions
68//! are considered as roots, as well as when the `-Clink-dead-code` option is
69//! specified. Functions marked `#[no_mangle]` and functions called by inlinable
70//! functions also always act as roots.)
71//!
72//! ### Finding uses
73//! Given a mono item node, we can discover uses by inspecting its MIR. We walk
74//! the MIR to find other mono items used by each mono item. Since the mono
75//! item we are currently at is always monomorphic, we also know the concrete
76//! type arguments of its used mono items. The specific forms a use can take in
77//! MIR are quite diverse. Here is an overview:
78//!
79//! #### Calling Functions/Methods
80//! The most obvious way for one mono item to use another is a
81//! function or method call (represented by a CALL terminator in MIR). But
82//! calls are not the only thing that might introduce a use between two
83//! function mono items, and as we will see below, they are just a
84//! specialization of the form described next, and consequently will not get any
85//! special treatment in the algorithm.
86//!
87//! #### Taking a reference to a function or method
88//! A function does not need to actually be called in order to be used by
89//! another function. It suffices to just take a reference in order to introduce
90//! an edge. Consider the following example:
91//!
92//! ```
93//! # use core::fmt::Display;
94//! fn print_val<T: Display>(x: T) {
95//!     println!("{}", x);
96//! }
97//!
98//! fn call_fn(f: &dyn Fn(i32), x: i32) {
99//!     f(x);
100//! }
101//!
102//! fn main() {
103//!     let print_i32 = print_val::<i32>;
104//!     call_fn(&print_i32, 0);
105//! }
106//! ```
107//! The MIR of none of these functions will contain an explicit call to
108//! `print_val::<i32>`. Nonetheless, in order to mono this program, we need
109//! an instance of this function. Thus, whenever we encounter a function or
110//! method in operand position, we treat it as a use of the current
111//! mono item. Calls are just a special case of that.
112//!
113//! #### Drop glue
114//! Drop glue mono items are introduced by MIR drop-statements. The
115//! generated mono item will have additional drop-glue item uses if the
116//! type to be dropped contains nested values that also need to be dropped. It
117//! might also have a function item use for the explicit `Drop::drop`
118//! implementation of its type.
119//!
120//! #### Unsizing Casts
121//! A subtle way of introducing use edges is by casting to a trait object.
122//! Since the resulting wide-pointer contains a reference to a vtable, we need to
123//! instantiate all dyn-compatible methods of the trait, as we need to store
124//! pointers to these functions even if they never get called anywhere. This can
125//! be seen as a special case of taking a function reference.
126//!
127//!
128//! Interaction with Cross-Crate Inlining
129//! -------------------------------------
130//! The binary of a crate will not only contain machine code for the items
131//! defined in the source code of that crate. It will also contain monomorphic
132//! instantiations of any extern generic functions and of functions marked with
133//! `#[inline]`.
134//! The collection algorithm handles this more or less mono. If it is
135//! about to create a mono item for something with an external `DefId`,
136//! it will take a look if the MIR for that item is available, and if so just
137//! proceed normally. If the MIR is not available, it assumes that the item is
138//! just linked to and no node is created; which is exactly what we want, since
139//! no machine code should be generated in the current crate for such an item.
140//!
141//! Eager and Lazy Collection Strategy
142//! ----------------------------------
143//! Mono item collection can be performed with one of two strategies:
144//!
145//! - Lazy strategy means that items will only be instantiated when actually
146//!   used. The goal is to produce the least amount of machine code
147//!   possible.
148//!
149//! - Eager strategy is meant to be used in conjunction with incremental compilation
150//!   where a stable set of mono items is more important than a minimal
151//!   one. Thus, eager strategy will instantiate drop-glue for every drop-able type
152//!   in the crate, even if no drop call for that type exists (yet). It will
153//!   also instantiate default implementations of trait methods, something that
154//!   otherwise is only done on demand.
155//!
156//! Collection-time const evaluation and "mentioned" items
157//! ------------------------------------------------------
158//!
159//! One important role of collection is to evaluate all constants that are used by all the items
160//! which are being collected. Codegen can then rely on only encountering constants that evaluate
161//! successfully, and if a constant fails to evaluate, the collector has much better context to be
162//! able to show where this constant comes up.
163//!
164//! However, the exact set of "used" items (collected as described above), and therefore the exact
165//! set of used constants, can depend on optimizations. Optimizing away dead code may optimize away
166//! a function call that uses a failing constant, so an unoptimized build may fail where an
167//! optimized build succeeds. This is undesirable.
168//!
169//! To avoid this, the collector has the concept of "mentioned" items. Some time during the MIR
170//! pipeline, before any optimization-level-dependent optimizations, we compute a list of all items
171//! that syntactically appear in the code. These are considered "mentioned", and even if they are in
172//! dead code and get optimized away (which makes them no longer "used"), they are still
173//! "mentioned". For every used item, the collector ensures that all mentioned items, recursively,
174//! do not use a failing constant. This is reflected via the [`CollectionMode`], which determines
175//! whether we are visiting a used item or merely a mentioned item.
176//!
177//! The collector and "mentioned items" gathering (which lives in `rustc_mir_transform::mentioned_items`)
178//! need to stay in sync in the following sense:
179//!
180//! - For every item that the collector gather that could eventually lead to build failure (most
181//!   likely due to containing a constant that fails to evaluate), a corresponding mentioned item
182//!   must be added. This should use the exact same strategy as the ecollector to make sure they are
183//!   in sync. However, while the collector works on monomorphized types, mentioned items are
184//!   collected on generic MIR -- so any time the collector checks for a particular type (such as
185//!   `ty::FnDef`), we have to just onconditionally add this as a mentioned item.
186//! - In `visit_mentioned_item`, we then do with that mentioned item exactly what the collector
187//!   would have done during regular MIR visiting. Basically you can think of the collector having
188//!   two stages, a pre-monomorphization stage and a post-monomorphization stage (usually quite
189//!   literally separated by a call to `self.monomorphize`); the pre-monomorphizationn stage is
190//!   duplicated in mentioned items gathering and the post-monomorphization stage is duplicated in
191//!   `visit_mentioned_item`.
192//! - Finally, as a performance optimization, the collector should fill `used_mentioned_item` during
193//!   its MIR traversal with exactly what mentioned item gathering would have added in the same
194//!   situation. This detects mentioned items that have *not* been optimized away and hence don't
195//!   need a dedicated traversal.
196//!
197//! Open Issues
198//! -----------
199//! Some things are not yet fully implemented in the current version of this
200//! module.
201//!
202//! ### Const Fns
203//! Ideally, no mono item should be generated for const fns unless there
204//! is a call to them that cannot be evaluated at compile time. At the moment
205//! this is not implemented however: a mono item will be produced
206//! regardless of whether it is actually needed or not.
207
208use std::cell::OnceCell;
209use std::ops::ControlFlow;
210
211use rustc_data_structures::fx::FxIndexMap;
212use rustc_data_structures::sync::{Lock, par_for_each_in};
213use rustc_data_structures::unord::{UnordMap, UnordSet};
214use rustc_hir as hir;
215use rustc_hir::attrs::InlineAttr;
216use rustc_hir::def::DefKind;
217use rustc_hir::def_id::{DefId, DefIdMap, LocalDefId};
218use rustc_hir::lang_items::LangItem;
219use rustc_hir::limit::Limit;
220use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
221use rustc_middle::mir::interpret::{AllocId, ErrorHandled, GlobalAlloc, Scalar};
222use rustc_middle::mir::visit::Visitor as MirVisitor;
223use rustc_middle::mir::{self, Body, Location, MentionedItem, traversal};
224use rustc_middle::mono::{CollectionMode, InstantiationMode, MonoItem, NormalizationErrorInMono};
225use rustc_middle::query::TyCtxtAt;
226use rustc_middle::ty::adjustment::{CustomCoerceUnsized, PointerCoercion};
227use rustc_middle::ty::layout::ValidityRequirement;
228use rustc_middle::ty::{
229    self, GenericArgs, GenericParamDefKind, Instance, InstanceKind, ShimKind, Ty, TyCtxt,
230    TypeFoldable, TypeVisitable, TypeVisitableExt, TypeVisitor, Unnormalized, VtblEntry,
231};
232use rustc_middle::util::Providers;
233use rustc_middle::{bug, span_bug};
234use rustc_session::config::{DebugInfo, EntryFnType};
235use rustc_span::{DUMMY_SP, Span, Spanned, dummy_spanned, respan};
236use tracing::{debug, instrument, trace};
237
238use crate::diagnostics::{
239    self, EncounteredErrorWhileInstantiating, EncounteredErrorWhileInstantiatingGlobalAsm,
240    NoOptimizedMir, RecursionLimit,
241};
242
243#[derive(#[automatically_derived]
impl ::core::cmp::PartialEq for MonoItemCollectionStrategy {
    #[inline]
    fn eq(&self, other: &MonoItemCollectionStrategy) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq)]
244pub(crate) enum MonoItemCollectionStrategy {
245    Eager,
246    Lazy,
247}
248
249/// The state that is shared across the concurrent threads that are doing collection.
250struct SharedState<'tcx> {
251    /// Items that have been or are currently being recursively collected.
252    visited: Lock<UnordSet<MonoItem<'tcx>>>,
253    /// Items that have been or are currently being recursively treated as "mentioned", i.e., their
254    /// consts are evaluated but nothing is added to the collection.
255    mentioned: Lock<UnordSet<MonoItem<'tcx>>>,
256    /// Which items are being used where, for better errors.
257    usage_map: Lock<UsageMap<'tcx>>,
258}
259
260pub(crate) struct UsageMap<'tcx> {
261    // Maps every mono item to the mono items used by it.
262    pub used_map: UnordMap<MonoItem<'tcx>, Vec<MonoItem<'tcx>>>,
263
264    // Maps each mono item with users to the mono items that use it.
265    // Be careful: subsets `used_map`, so unused items are vacant.
266    user_map: UnordMap<MonoItem<'tcx>, Vec<MonoItem<'tcx>>>,
267}
268
269impl<'tcx> UsageMap<'tcx> {
270    fn new() -> UsageMap<'tcx> {
271        UsageMap { used_map: Default::default(), user_map: Default::default() }
272    }
273
274    fn record_used<'a>(&mut self, user_item: MonoItem<'tcx>, used_items: &'a MonoItems<'tcx>)
275    where
276        'tcx: 'a,
277    {
278        for used_item in used_items.items() {
279            self.user_map.entry(used_item).or_default().push(user_item);
280        }
281
282        if !self.used_map.insert(user_item, used_items.items().collect()).is_none() {
    ::core::panicking::panic("assertion failed: self.used_map.insert(user_item, used_items.items().collect()).is_none()")
};assert!(self.used_map.insert(user_item, used_items.items().collect()).is_none());
283    }
284
285    pub(crate) fn get_user_items(&self, item: MonoItem<'tcx>) -> &[MonoItem<'tcx>] {
286        self.user_map.get(&item).map(|items| items.as_slice()).unwrap_or(&[])
287    }
288
289    /// Internally iterate over all inlined items used by `item`.
290    pub(crate) fn for_each_inlined_used_item<F>(
291        &self,
292        tcx: TyCtxt<'tcx>,
293        item: MonoItem<'tcx>,
294        mut f: F,
295    ) where
296        F: FnMut(MonoItem<'tcx>),
297    {
298        let used_items = self.used_map.get(&item).unwrap();
299        for used_item in used_items.iter() {
300            let is_inlined = used_item.instantiation_mode(tcx) == InstantiationMode::LocalCopy;
301            if is_inlined {
302                f(*used_item);
303            }
304        }
305    }
306}
307
308struct MonoItems<'tcx> {
309    // We want a set of MonoItem + Span where trying to re-insert a MonoItem with a different Span
310    // is ignored. Map does that, but it looks odd.
311    items: FxIndexMap<MonoItem<'tcx>, Span>,
312}
313
314impl<'tcx> MonoItems<'tcx> {
315    fn new() -> Self {
316        Self { items: FxIndexMap::default() }
317    }
318
319    fn is_empty(&self) -> bool {
320        self.items.is_empty()
321    }
322
323    fn push(&mut self, item: Spanned<MonoItem<'tcx>>) {
324        // Insert only if the entry does not exist. A normal insert would stomp the first span that
325        // got inserted.
326        self.items.entry(item.node).or_insert(item.span);
327    }
328
329    fn items(&self) -> impl Iterator<Item = MonoItem<'tcx>> {
330        self.items.keys().cloned()
331    }
332}
333
334impl<'tcx> IntoIterator for MonoItems<'tcx> {
335    type Item = Spanned<MonoItem<'tcx>>;
336    type IntoIter = impl Iterator<Item = Spanned<MonoItem<'tcx>>>;
337
338    fn into_iter(self) -> Self::IntoIter {
339        self.items.into_iter().map(|(item, span)| respan(span, item))
340    }
341}
342
343impl<'tcx> Extend<Spanned<MonoItem<'tcx>>> for MonoItems<'tcx> {
344    fn extend<I>(&mut self, iter: I)
345    where
346        I: IntoIterator<Item = Spanned<MonoItem<'tcx>>>,
347    {
348        for item in iter {
349            self.push(item)
350        }
351    }
352}
353
354fn collect_items_root<'tcx>(
355    tcx: TyCtxt<'tcx>,
356    starting_item: Spanned<MonoItem<'tcx>>,
357    state: &SharedState<'tcx>,
358    recursion_limit: Limit,
359) {
360    if !state.visited.lock().insert(starting_item.node) {
361        // We've been here already, no need to search again.
362        return;
363    }
364    let mut recursion_depths = DefIdMap::default();
365    collect_items_rec(
366        tcx,
367        starting_item,
368        state,
369        &mut recursion_depths,
370        recursion_limit,
371        CollectionMode::UsedItems,
372    );
373}
374
375/// Collect all monomorphized items reachable from `starting_point`, and emit a note diagnostic if a
376/// post-monomorphization error is encountered during a collection step.
377///
378/// `mode` determined whether we are scanning for [used items][CollectionMode::UsedItems]
379/// or [mentioned items][CollectionMode::MentionedItems].
380#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("collect_items_rec",
                                    "rustc_monomorphize::collector", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
                                    ::tracing_core::__macro_support::Option::Some(380u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
                                    ::tracing_core::field::FieldSet::new(&["starting_item",
                                                    "mode"], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&starting_item)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&mode)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let mut used_items = MonoItems::new();
            let mut mentioned_items = MonoItems::new();
            let recursion_depth_reset;
            let error_count = tcx.dcx().err_count_on_current_thread();
            match starting_item.node {
                MonoItem::Static(def_id) => {
                    recursion_depth_reset = None;
                    if mode == CollectionMode::UsedItems {
                        let instance = Instance::mono(tcx, def_id);
                        if true {
                            if !tcx.should_codegen_locally(instance) {
                                ::core::panicking::panic("assertion failed: tcx.should_codegen_locally(instance)")
                            };
                        };
                        let DefKind::Static { nested, .. } =
                            tcx.def_kind(def_id) else {
                                ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))
                            };
                        if !nested {
                            let ty =
                                instance.ty(tcx, ty::TypingEnv::fully_monomorphized());
                            visit_drop_use(tcx, ty, true, starting_item.span,
                                &mut used_items);
                        }
                        if let Ok(alloc) = tcx.eval_static_initializer(def_id) {
                            for &prov in alloc.inner().provenance().ptrs().values() {
                                collect_alloc(tcx, prov.alloc_id(), &mut used_items);
                            }
                        }
                        if tcx.needs_thread_local_shim(def_id) {
                            used_items.push(respan(starting_item.span,
                                    MonoItem::Fn(Instance {
                                            def: InstanceKind::Shim(ShimKind::ThreadLocal(def_id)),
                                            args: GenericArgs::empty(),
                                        })));
                        }
                    }
                }
                MonoItem::Fn(instance) => {
                    if true {
                        if !tcx.should_codegen_locally(instance) {
                            ::core::panicking::panic("assertion failed: tcx.should_codegen_locally(instance)")
                        };
                    };
                    recursion_depth_reset =
                        Some(check_recursion_limit(tcx, instance,
                                starting_item.span, recursion_depths, recursion_limit));
                    rustc_data_structures::stack::ensure_sufficient_stack(||
                            {
                                let Ok((used, mentioned)) =
                                    tcx.items_of_instance((instance,
                                            mode)) else {
                                        let def_id = instance.def_id();
                                        let def_span = tcx.def_span(def_id);
                                        let def_path_str = tcx.def_path_str(def_id);
                                        tcx.dcx().emit_fatal(RecursionLimit {
                                                span: starting_item.span,
                                                instance,
                                                def_span,
                                                def_path_str,
                                            });
                                    };
                                used_items.extend(used.into_iter().copied());
                                mentioned_items.extend(mentioned.into_iter().copied());
                            });
                }
                MonoItem::GlobalAsm(item_id) => {
                    if !(mode == CollectionMode::UsedItems) {
                        {
                            ::core::panicking::panic_fmt(format_args!("should never encounter global_asm when collecting mentioned items"));
                        }
                    };
                    recursion_depth_reset = None;
                    let item = tcx.hir_item(item_id);
                    if let hir::ItemKind::GlobalAsm { asm, .. } = item.kind {
                        for (op, op_sp) in asm.operands {
                            match *op {
                                hir::InlineAsmOperand::Const { .. } => {}
                                hir::InlineAsmOperand::SymFn { expr } => {
                                    let fn_ty = tcx.typeck(item_id.owner_id).expr_ty(expr);
                                    visit_fn_use(tcx, fn_ty, false, *op_sp, &mut used_items);
                                }
                                hir::InlineAsmOperand::SymStatic { path: _, def_id } => {
                                    let instance = Instance::mono(tcx, def_id);
                                    if tcx.should_codegen_locally(instance) {
                                        {
                                            use ::tracing::__macro_support::Callsite as _;
                                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                                {
                                                    static META: ::tracing::Metadata<'static> =
                                                        {
                                                            ::tracing_core::metadata::Metadata::new("event compiler/rustc_monomorphize/src/collector.rs:518",
                                                                "rustc_monomorphize::collector", ::tracing::Level::TRACE,
                                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
                                                                ::tracing_core::__macro_support::Option::Some(518u32),
                                                                ::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
                                                                ::tracing_core::field::FieldSet::new(&["message"],
                                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                                ::tracing::metadata::Kind::EVENT)
                                                        };
                                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                                };
                                            let enabled =
                                                ::tracing::Level::TRACE <=
                                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                        ::tracing::Level::TRACE <=
                                                            ::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};
                                                        let mut iter = __CALLSITE.metadata().fields().iter();
                                                        __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                                            ::tracing::__macro_support::Option::Some(&format_args!("collecting static {0:?}",
                                                                                            def_id) as &dyn Value))])
                                                    });
                                            } else { ; }
                                        };
                                        used_items.push(dummy_spanned(MonoItem::Static(def_id)));
                                    }
                                }
                                hir::InlineAsmOperand::In { .. } |
                                    hir::InlineAsmOperand::Out { .. } |
                                    hir::InlineAsmOperand::InOut { .. } |
                                    hir::InlineAsmOperand::SplitInOut { .. } |
                                    hir::InlineAsmOperand::Label { .. } => {
                                    ::rustc_middle::util::bug::span_bug_fmt(*op_sp,
                                        format_args!("invalid operand type for global_asm!"))
                                }
                            }
                        }
                    } else {
                        ::rustc_middle::util::bug::span_bug_fmt(item.span,
                            format_args!("Mismatch between hir::Item type and MonoItem type"))
                    }
                }
            };
            if tcx.dcx().err_count_on_current_thread() > error_count &&
                        starting_item.node.is_generic_fn() &&
                    starting_item.node.is_user_defined() {
                match starting_item.node {
                    MonoItem::Fn(instance) =>
                        tcx.dcx().emit_note(EncounteredErrorWhileInstantiating {
                                span: starting_item.span,
                                kind: "fn",
                                instance,
                            }),
                    MonoItem::Static(def_id) =>
                        tcx.dcx().emit_note(EncounteredErrorWhileInstantiating {
                                span: starting_item.span,
                                kind: "static",
                                instance: Instance::new_raw(def_id, GenericArgs::empty()),
                            }),
                    MonoItem::GlobalAsm(_) => {
                        tcx.dcx().emit_note(EncounteredErrorWhileInstantiatingGlobalAsm {
                                span: starting_item.span,
                            })
                    }
                }
            }
            if mode == CollectionMode::UsedItems {
                state.usage_map.lock().record_used(starting_item.node,
                    &used_items);
            }
            {
                let mut visited = OnceCell::default();
                if mode == CollectionMode::UsedItems {
                    used_items.items.retain(|k, _|
                            visited.get_mut_or_init(||
                                        state.visited.lock()).insert(*k));
                }
                let mut mentioned = OnceCell::default();
                mentioned_items.items.retain(|k, _|
                        {
                            !visited.get_or_init(|| state.visited.lock()).contains(k) &&
                                mentioned.get_mut_or_init(||
                                            state.mentioned.lock()).insert(*k)
                        });
            }
            if mode == CollectionMode::MentionedItems {
                if !used_items.is_empty() {
                    {
                        ::core::panicking::panic_fmt(format_args!("\'mentioned\' collection should never encounter used items"));
                    }
                };
            } else {
                for used_item in used_items {
                    collect_items_rec(tcx, used_item, state, recursion_depths,
                        recursion_limit, CollectionMode::UsedItems);
                }
            }
            for mentioned_item in mentioned_items {
                collect_items_rec(tcx, mentioned_item, state,
                    recursion_depths, recursion_limit,
                    CollectionMode::MentionedItems);
            }
            if let Some((def_id, depth)) = recursion_depth_reset {
                recursion_depths.insert(def_id, depth);
            }
        }
    }
}#[instrument(skip(tcx, state, recursion_depths, recursion_limit), level = "debug")]
381fn collect_items_rec<'tcx>(
382    tcx: TyCtxt<'tcx>,
383    starting_item: Spanned<MonoItem<'tcx>>,
384    state: &SharedState<'tcx>,
385    recursion_depths: &mut DefIdMap<usize>,
386    recursion_limit: Limit,
387    mode: CollectionMode,
388) {
389    let mut used_items = MonoItems::new();
390    let mut mentioned_items = MonoItems::new();
391    let recursion_depth_reset;
392
393    // Post-monomorphization errors MVP
394    //
395    // We can encounter errors while monomorphizing an item, but we don't have a good way of
396    // showing a complete stack of spans ultimately leading to collecting the erroneous one yet.
397    // (It's also currently unclear exactly which diagnostics and information would be interesting
398    // to report in such cases)
399    //
400    // This leads to suboptimal error reporting: a post-monomorphization error (PME) will be
401    // shown with just a spanned piece of code causing the error, without information on where
402    // it was called from. This is especially obscure if the erroneous mono item is in a
403    // dependency. See for example issue #85155, where, before minimization, a PME happened two
404    // crates downstream from libcore's stdarch, without a way to know which dependency was the
405    // cause.
406    //
407    // If such an error occurs in the current crate, its span will be enough to locate the
408    // source. If the cause is in another crate, the goal here is to quickly locate which mono
409    // item in the current crate is ultimately responsible for causing the error.
410    //
411    // To give at least _some_ context to the user: while collecting mono items, we check the
412    // error count. If it has changed, a PME occurred, and we trigger some diagnostics about the
413    // current step of mono items collection.
414    //
415    // FIXME: don't rely on global state, instead bubble up errors. Note: this is very hard to do.
416    let error_count = tcx.dcx().err_count_on_current_thread();
417
418    // In `mentioned_items` we collect items that were mentioned in this MIR but possibly do not
419    // need to be monomorphized. This is done to ensure that optimizing away function calls does not
420    // hide const-eval errors that those calls would otherwise have triggered.
421    match starting_item.node {
422        MonoItem::Static(def_id) => {
423            recursion_depth_reset = None;
424
425            // Statics always get evaluated (which is possible because they can't be generic), so for
426            // `MentionedItems` collection there's nothing to do here.
427            if mode == CollectionMode::UsedItems {
428                let instance = Instance::mono(tcx, def_id);
429
430                // Sanity check whether this ended up being collected accidentally
431                debug_assert!(tcx.should_codegen_locally(instance));
432
433                let DefKind::Static { nested, .. } = tcx.def_kind(def_id) else { bug!() };
434                // Nested statics have no type.
435                if !nested {
436                    let ty = instance.ty(tcx, ty::TypingEnv::fully_monomorphized());
437                    visit_drop_use(tcx, ty, true, starting_item.span, &mut used_items);
438                }
439
440                if let Ok(alloc) = tcx.eval_static_initializer(def_id) {
441                    for &prov in alloc.inner().provenance().ptrs().values() {
442                        collect_alloc(tcx, prov.alloc_id(), &mut used_items);
443                    }
444                }
445
446                if tcx.needs_thread_local_shim(def_id) {
447                    used_items.push(respan(
448                        starting_item.span,
449                        MonoItem::Fn(Instance {
450                            def: InstanceKind::Shim(ShimKind::ThreadLocal(def_id)),
451                            args: GenericArgs::empty(),
452                        }),
453                    ));
454                }
455            }
456
457            // mentioned_items stays empty since there's no codegen for statics. statics don't get
458            // optimized, and if they did then the const-eval interpreter would have to worry about
459            // mentioned_items.
460        }
461        MonoItem::Fn(instance) => {
462            // Sanity check whether this ended up being collected accidentally
463            debug_assert!(tcx.should_codegen_locally(instance));
464
465            // Keep track of the monomorphization recursion depth
466            recursion_depth_reset = Some(check_recursion_limit(
467                tcx,
468                instance,
469                starting_item.span,
470                recursion_depths,
471                recursion_limit,
472            ));
473
474            rustc_data_structures::stack::ensure_sufficient_stack(|| {
475                let Ok((used, mentioned)) = tcx.items_of_instance((instance, mode)) else {
476                    // Normalization errors here are usually due to trait solving overflow.
477                    // FIXME: I assume that there are few type errors at post-analysis stage, but not
478                    // entirely sure.
479                    // We have to emit the error outside of `items_of_instance` to access the
480                    // span of the `starting_item`.
481                    let def_id = instance.def_id();
482                    let def_span = tcx.def_span(def_id);
483                    let def_path_str = tcx.def_path_str(def_id);
484                    tcx.dcx().emit_fatal(RecursionLimit {
485                        span: starting_item.span,
486                        instance,
487                        def_span,
488                        def_path_str,
489                    });
490                };
491                used_items.extend(used.into_iter().copied());
492                mentioned_items.extend(mentioned.into_iter().copied());
493            });
494        }
495        MonoItem::GlobalAsm(item_id) => {
496            assert!(
497                mode == CollectionMode::UsedItems,
498                "should never encounter global_asm when collecting mentioned items"
499            );
500            recursion_depth_reset = None;
501
502            let item = tcx.hir_item(item_id);
503            if let hir::ItemKind::GlobalAsm { asm, .. } = item.kind {
504                for (op, op_sp) in asm.operands {
505                    match *op {
506                        hir::InlineAsmOperand::Const { .. } => {
507                            // Only constants which resolve to a plain integer
508                            // are supported. Therefore the value should not
509                            // depend on any other items.
510                        }
511                        hir::InlineAsmOperand::SymFn { expr } => {
512                            let fn_ty = tcx.typeck(item_id.owner_id).expr_ty(expr);
513                            visit_fn_use(tcx, fn_ty, false, *op_sp, &mut used_items);
514                        }
515                        hir::InlineAsmOperand::SymStatic { path: _, def_id } => {
516                            let instance = Instance::mono(tcx, def_id);
517                            if tcx.should_codegen_locally(instance) {
518                                trace!("collecting static {:?}", def_id);
519                                used_items.push(dummy_spanned(MonoItem::Static(def_id)));
520                            }
521                        }
522                        hir::InlineAsmOperand::In { .. }
523                        | hir::InlineAsmOperand::Out { .. }
524                        | hir::InlineAsmOperand::InOut { .. }
525                        | hir::InlineAsmOperand::SplitInOut { .. }
526                        | hir::InlineAsmOperand::Label { .. } => {
527                            span_bug!(*op_sp, "invalid operand type for global_asm!")
528                        }
529                    }
530                }
531            } else {
532                span_bug!(item.span, "Mismatch between hir::Item type and MonoItem type")
533            }
534
535            // mention_items stays empty as nothing gets optimized here.
536        }
537    };
538
539    // Check for PMEs and emit a diagnostic if one happened. To try to show relevant edges of the
540    // mono item graph.
541    if tcx.dcx().err_count_on_current_thread() > error_count
542        && starting_item.node.is_generic_fn()
543        && starting_item.node.is_user_defined()
544    {
545        match starting_item.node {
546            MonoItem::Fn(instance) => tcx.dcx().emit_note(EncounteredErrorWhileInstantiating {
547                span: starting_item.span,
548                kind: "fn",
549                instance,
550            }),
551            MonoItem::Static(def_id) => tcx.dcx().emit_note(EncounteredErrorWhileInstantiating {
552                span: starting_item.span,
553                kind: "static",
554                instance: Instance::new_raw(def_id, GenericArgs::empty()),
555            }),
556            MonoItem::GlobalAsm(_) => {
557                tcx.dcx().emit_note(EncounteredErrorWhileInstantiatingGlobalAsm {
558                    span: starting_item.span,
559                })
560            }
561        }
562    }
563    // Only updating `usage_map` for used items as otherwise we may be inserting the same item
564    // multiple times (if it is first 'mentioned' and then later actually used), and the usage map
565    // logic does not like that.
566    // This is part of the output of collection and hence only relevant for "used" items.
567    // ("Mentioned" items are only considered internally during collection.)
568    if mode == CollectionMode::UsedItems {
569        state.usage_map.lock().record_used(starting_item.node, &used_items);
570    }
571
572    {
573        let mut visited = OnceCell::default();
574        if mode == CollectionMode::UsedItems {
575            used_items
576                .items
577                .retain(|k, _| visited.get_mut_or_init(|| state.visited.lock()).insert(*k));
578        }
579
580        let mut mentioned = OnceCell::default();
581        mentioned_items.items.retain(|k, _| {
582            !visited.get_or_init(|| state.visited.lock()).contains(k)
583                && mentioned.get_mut_or_init(|| state.mentioned.lock()).insert(*k)
584        });
585    }
586    if mode == CollectionMode::MentionedItems {
587        assert!(used_items.is_empty(), "'mentioned' collection should never encounter used items");
588    } else {
589        for used_item in used_items {
590            collect_items_rec(
591                tcx,
592                used_item,
593                state,
594                recursion_depths,
595                recursion_limit,
596                CollectionMode::UsedItems,
597            );
598        }
599    }
600
601    // Walk over mentioned items *after* used items, so that if an item is both mentioned and used then
602    // the loop above has fully collected it, so this loop will skip it.
603    for mentioned_item in mentioned_items {
604        collect_items_rec(
605            tcx,
606            mentioned_item,
607            state,
608            recursion_depths,
609            recursion_limit,
610            CollectionMode::MentionedItems,
611        );
612    }
613
614    if let Some((def_id, depth)) = recursion_depth_reset {
615        recursion_depths.insert(def_id, depth);
616    }
617}
618
619// Check whether we can normalize every type in the instantiated MIR body.
620fn check_normalization_error<'tcx>(
621    tcx: TyCtxt<'tcx>,
622    instance: Instance<'tcx>,
623    body: &Body<'tcx>,
624) -> Result<(), NormalizationErrorInMono> {
625    struct NormalizationChecker<'tcx> {
626        tcx: TyCtxt<'tcx>,
627        instance: Instance<'tcx>,
628    }
629    impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for NormalizationChecker<'tcx> {
630        type Result = ControlFlow<()>;
631
632        fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
633            match self.instance.try_instantiate_mir_and_normalize_erasing_regions(
634                self.tcx,
635                ty::TypingEnv::fully_monomorphized(),
636                ty::EarlyBinder::bind(self.tcx, t),
637            ) {
638                Ok(_) => ControlFlow::Continue(()),
639                Err(_) => ControlFlow::Break(()),
640            }
641        }
642    }
643
644    let mut checker = NormalizationChecker { tcx, instance };
645    if body.visit_with(&mut checker).is_break() { Err(NormalizationErrorInMono) } else { Ok(()) }
646}
647
648fn check_recursion_limit<'tcx>(
649    tcx: TyCtxt<'tcx>,
650    instance: Instance<'tcx>,
651    span: Span,
652    recursion_depths: &mut DefIdMap<usize>,
653    recursion_limit: Limit,
654) -> (DefId, usize) {
655    let def_id = instance.def_id();
656    let recursion_depth = recursion_depths.get(&def_id).cloned().unwrap_or(0);
657    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_monomorphize/src/collector.rs:657",
                        "rustc_monomorphize::collector", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
                        ::tracing_core::__macro_support::Option::Some(657u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!(" => recursion depth={0}",
                                                    recursion_depth) as &dyn Value))])
            });
    } else { ; }
};debug!(" => recursion depth={}", recursion_depth);
658
659    let adjusted_recursion_depth = if tcx.is_lang_item(def_id, LangItem::DropGlue) {
660        // HACK: `drop_glue` creates tight monomorphization loops. Give
661        // it more margin.
662        recursion_depth / 4
663    } else {
664        recursion_depth
665    };
666
667    // Code that needs to instantiate the same function recursively
668    // more than the recursion limit is assumed to be causing an
669    // infinite expansion.
670    if !recursion_limit.value_within_limit(adjusted_recursion_depth) {
671        let def_span = tcx.def_span(def_id);
672        let def_path_str = tcx.def_path_str(def_id);
673        tcx.dcx().emit_fatal(RecursionLimit { span, instance, def_span, def_path_str });
674    }
675
676    recursion_depths.insert(def_id, recursion_depth + 1);
677
678    (def_id, recursion_depth)
679}
680
681struct MirUsedCollector<'a, 'tcx> {
682    tcx: TyCtxt<'tcx>,
683    body: &'a mir::Body<'tcx>,
684    used_items: &'a mut MonoItems<'tcx>,
685    /// See the comment in `collect_items_of_instance` for the purpose of this set.
686    /// Note that this contains *not-monomorphized* items!
687    used_mentioned_items: &'a mut UnordSet<MentionedItem<'tcx>>,
688    instance: Instance<'tcx>,
689}
690
691impl<'a, 'tcx> MirUsedCollector<'a, 'tcx> {
692    fn monomorphize<T>(&self, value: T) -> T
693    where
694        T: TypeFoldable<TyCtxt<'tcx>>,
695    {
696        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_monomorphize/src/collector.rs:696",
                        "rustc_monomorphize::collector", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
                        ::tracing_core::__macro_support::Option::Some(696u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("monomorphize: self.instance={0:?}",
                                                    self.instance) as &dyn Value))])
            });
    } else { ; }
};trace!("monomorphize: self.instance={:?}", self.instance);
697        self.instance.instantiate_mir_and_normalize_erasing_regions(
698            self.tcx,
699            ty::TypingEnv::fully_monomorphized(),
700            ty::EarlyBinder::bind(self.tcx, value),
701        )
702    }
703
704    /// Evaluates a *not yet monomorphized* constant.
705    fn eval_constant(&mut self, constant: &mir::ConstOperand<'tcx>) -> Option<mir::ConstValue> {
706        let const_ = self.monomorphize(constant.const_);
707        // Evaluate the constant. This makes const eval failure a collection-time error (rather than
708        // a codegen-time error). rustc stops after collection if there was an error, so this
709        // ensures codegen never has to worry about failing consts.
710        // (codegen relies on this and ICEs will happen if this is violated.)
711        match const_.eval(self.tcx, ty::TypingEnv::fully_monomorphized(), constant.span) {
712            Ok(v) => Some(v),
713            Err(ErrorHandled::TooGeneric(..)) => ::rustc_middle::util::bug::span_bug_fmt(constant.span,
    format_args!("collection encountered polymorphic constant: {0:?}",
        const_))span_bug!(
714                constant.span,
715                "collection encountered polymorphic constant: {:?}",
716                const_
717            ),
718            Err(err @ ErrorHandled::Reported(..)) => {
719                err.emit_note(self.tcx);
720                return None;
721            }
722        }
723    }
724}
725
726impl<'a, 'tcx> MirVisitor<'tcx> for MirUsedCollector<'a, 'tcx> {
727    fn visit_rvalue(&mut self, rvalue: &mir::Rvalue<'tcx>, location: Location) {
728        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_monomorphize/src/collector.rs:728",
                        "rustc_monomorphize::collector", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
                        ::tracing_core::__macro_support::Option::Some(728u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("visiting rvalue {0:?}",
                                                    *rvalue) as &dyn Value))])
            });
    } else { ; }
};debug!("visiting rvalue {:?}", *rvalue);
729
730        let span = self.body.source_info(location).span;
731
732        match *rvalue {
733            // When doing an cast from a regular pointer to a wide pointer, we
734            // have to instantiate all methods of the trait being cast to, so we
735            // can build the appropriate vtable.
736            mir::Rvalue::Cast(
737                mir::CastKind::PointerCoercion(PointerCoercion::Unsize, _),
738                ref operand,
739                target_ty,
740            ) => {
741                let source_ty = operand.ty(self.body, self.tcx);
742                // *Before* monomorphizing, record that we already handled this mention.
743                self.used_mentioned_items
744                    .insert(MentionedItem::UnsizeCast { source_ty, target_ty });
745                let target_ty = self.monomorphize(target_ty);
746                let source_ty = self.monomorphize(source_ty);
747                let (source_ty, target_ty) =
748                    find_tails_for_unsizing(self.tcx.at(span), source_ty, target_ty);
749                // This could also be a different Unsize instruction, like
750                // from a fixed sized array to a slice. But we are only
751                // interested in things that produce a vtable.
752                if target_ty.is_trait() && !source_ty.is_trait() {
753                    create_mono_items_for_vtable_methods(
754                        self.tcx,
755                        target_ty,
756                        source_ty,
757                        span,
758                        self.used_items,
759                    );
760                }
761            }
762            mir::Rvalue::Cast(
763                mir::CastKind::PointerCoercion(PointerCoercion::ReifyFnPointer(_), _),
764                ref operand,
765                _,
766            ) => {
767                let fn_ty = operand.ty(self.body, self.tcx);
768                // *Before* monomorphizing, record that we already handled this mention.
769                self.used_mentioned_items.insert(MentionedItem::Fn(fn_ty));
770                let fn_ty = self.monomorphize(fn_ty);
771                visit_fn_use(self.tcx, fn_ty, false, span, self.used_items);
772            }
773            mir::Rvalue::Cast(
774                mir::CastKind::PointerCoercion(PointerCoercion::ClosureFnPointer(_), _),
775                ref operand,
776                _,
777            ) => {
778                let source_ty = operand.ty(self.body, self.tcx);
779                // *Before* monomorphizing, record that we already handled this mention.
780                self.used_mentioned_items.insert(MentionedItem::Closure(source_ty));
781                let source_ty = self.monomorphize(source_ty);
782                if let ty::Closure(def_id, args) = *source_ty.kind() {
783                    let instance =
784                        Instance::resolve_closure(self.tcx, def_id, args, ty::ClosureKind::FnOnce);
785                    if self.tcx.should_codegen_locally(instance) {
786                        self.used_items.push(create_fn_mono_item(self.tcx, instance, span));
787                    }
788                } else {
789                    ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!()
790                }
791            }
792            mir::Rvalue::ThreadLocalRef(def_id) => {
793                if !self.tcx.is_thread_local_static(def_id) {
    ::core::panicking::panic("assertion failed: self.tcx.is_thread_local_static(def_id)")
};assert!(self.tcx.is_thread_local_static(def_id));
794                let instance = Instance::mono(self.tcx, def_id);
795                if self.tcx.should_codegen_locally(instance) {
796                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_monomorphize/src/collector.rs:796",
                        "rustc_monomorphize::collector", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
                        ::tracing_core::__macro_support::Option::Some(796u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("collecting thread-local static {0:?}",
                                                    def_id) as &dyn Value))])
            });
    } else { ; }
};trace!("collecting thread-local static {:?}", def_id);
797                    self.used_items.push(respan(span, MonoItem::Static(def_id)));
798                }
799            }
800            _ => { /* not interesting */ }
801        }
802
803        self.super_rvalue(rvalue, location);
804    }
805
806    /// This does not walk the MIR of the constant as that is not needed for codegen, all we need is
807    /// to ensure that the constant evaluates successfully and walk the result.
808    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("visit_const_operand",
                                    "rustc_monomorphize::collector", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
                                    ::tracing_core::__macro_support::Option::Some(808u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
                                    ::tracing_core::field::FieldSet::new(&["constant",
                                                    "_location"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&constant)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&_location)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let Some(val) = self.eval_constant(constant) else { return };
            collect_const_value(self.tcx, val, self.used_items);
        }
    }
}#[instrument(skip(self), level = "debug")]
809    fn visit_const_operand(&mut self, constant: &mir::ConstOperand<'tcx>, _location: Location) {
810        // No `super_constant` as we don't care about `visit_ty`/`visit_ty_const`.
811        let Some(val) = self.eval_constant(constant) else { return };
812        collect_const_value(self.tcx, val, self.used_items);
813    }
814
815    fn visit_terminator(&mut self, terminator: &mir::Terminator<'tcx>, location: Location) {
816        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_monomorphize/src/collector.rs:816",
                        "rustc_monomorphize::collector", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
                        ::tracing_core::__macro_support::Option::Some(816u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("visiting terminator {0:?} @ {1:?}",
                                                    terminator, location) as &dyn Value))])
            });
    } else { ; }
};debug!("visiting terminator {:?} @ {:?}", terminator, location);
817        let source = self.body.source_info(location).span;
818
819        let tcx = self.tcx;
820        let push_mono_lang_item = |this: &mut Self, lang_item: LangItem| {
821            let instance = Instance::mono(tcx, tcx.require_lang_item(lang_item, source));
822            if tcx.should_codegen_locally(instance) {
823                this.used_items.push(create_fn_mono_item(tcx, instance, source));
824            }
825        };
826
827        match terminator.kind {
828            mir::TerminatorKind::Call { ref func, .. }
829            | mir::TerminatorKind::TailCall { ref func, .. } => {
830                let callee_ty = func.ty(self.body, tcx);
831                // *Before* monomorphizing, record that we already handled this mention.
832                self.used_mentioned_items.insert(MentionedItem::Fn(callee_ty));
833                let callee_ty = self.monomorphize(callee_ty);
834
835                // HACK(explicit_tail_calls): collect tail calls to `#[track_caller]` functions as indirect,
836                // because we later call them as such, to prevent issues with ABI incompatibility.
837                // Ideally we'd replace such tail calls with normal call + return, but this requires
838                // post-mono MIR optimizations, which we don't yet have.
839                let force_indirect_call =
840                    if #[allow(non_exhaustive_omitted_patterns)] match terminator.kind {
    mir::TerminatorKind::TailCall { .. } => true,
    _ => false,
}matches!(terminator.kind, mir::TerminatorKind::TailCall { .. })
841                        && let &ty::FnDef(def_id, args) = callee_ty.kind()
842                        && let instance = ty::Instance::expect_resolve(
843                            self.tcx,
844                            ty::TypingEnv::fully_monomorphized(),
845                            def_id,
846                            args,
847                            source,
848                        )
849                        && instance.def.requires_caller_location(self.tcx)
850                    {
851                        true
852                    } else {
853                        false
854                    };
855
856                visit_fn_use(
857                    self.tcx,
858                    callee_ty,
859                    !force_indirect_call,
860                    source,
861                    &mut self.used_items,
862                )
863            }
864            mir::TerminatorKind::Drop { ref place, .. } => {
865                let ty = place.ty(self.body, self.tcx).ty;
866                // *Before* monomorphizing, record that we already handled this mention.
867                self.used_mentioned_items.insert(MentionedItem::Drop(ty));
868                let ty = self.monomorphize(ty);
869                visit_drop_use(self.tcx, ty, true, source, self.used_items);
870            }
871            mir::TerminatorKind::InlineAsm { ref operands, .. } => {
872                for op in operands {
873                    match *op {
874                        mir::InlineAsmOperand::SymFn { ref value } => {
875                            let fn_ty = value.const_.ty();
876                            // *Before* monomorphizing, record that we already handled this mention.
877                            self.used_mentioned_items.insert(MentionedItem::Fn(fn_ty));
878                            let fn_ty = self.monomorphize(fn_ty);
879                            visit_fn_use(self.tcx, fn_ty, false, source, self.used_items);
880                        }
881                        mir::InlineAsmOperand::SymStatic { def_id } => {
882                            let instance = Instance::mono(self.tcx, def_id);
883                            if self.tcx.should_codegen_locally(instance) {
884                                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_monomorphize/src/collector.rs:884",
                        "rustc_monomorphize::collector", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
                        ::tracing_core::__macro_support::Option::Some(884u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("collecting asm sym static {0:?}",
                                                    def_id) as &dyn Value))])
            });
    } else { ; }
};trace!("collecting asm sym static {:?}", def_id);
885                                self.used_items.push(respan(source, MonoItem::Static(def_id)));
886                            }
887                        }
888                        _ => {}
889                    }
890                }
891            }
892            mir::TerminatorKind::Assert { ref msg, .. } => match &**msg {
893                mir::AssertKind::BoundsCheck { .. } => {
894                    push_mono_lang_item(self, LangItem::PanicBoundsCheck);
895                }
896                mir::AssertKind::MisalignedPointerDereference { .. } => {
897                    push_mono_lang_item(self, LangItem::PanicMisalignedPointerDereference);
898                }
899                mir::AssertKind::NullPointerDereference => {
900                    push_mono_lang_item(self, LangItem::PanicNullPointerDereference);
901                }
902                mir::AssertKind::NullReferenceConstructed => {
903                    push_mono_lang_item(self, LangItem::PanicNullReferenceConstructed);
904                }
905                mir::AssertKind::InvalidEnumConstruction(_) => {
906                    push_mono_lang_item(self, LangItem::PanicInvalidEnumConstruction);
907                }
908                _ => {
909                    push_mono_lang_item(self, msg.panic_function());
910                }
911            },
912            mir::TerminatorKind::UnwindTerminate(reason) => {
913                push_mono_lang_item(self, reason.lang_item());
914            }
915            mir::TerminatorKind::Goto { .. }
916            | mir::TerminatorKind::SwitchInt { .. }
917            | mir::TerminatorKind::UnwindResume
918            | mir::TerminatorKind::Return
919            | mir::TerminatorKind::Unreachable => {}
920            mir::TerminatorKind::CoroutineDrop
921            | mir::TerminatorKind::Yield { .. }
922            | mir::TerminatorKind::FalseEdge { .. }
923            | mir::TerminatorKind::FalseUnwind { .. } => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
924        }
925
926        if let Some(mir::UnwindAction::Terminate(reason)) = terminator.unwind() {
927            push_mono_lang_item(self, reason.lang_item());
928        }
929
930        self.super_terminator(terminator, location);
931    }
932}
933
934fn visit_drop_use<'tcx>(
935    tcx: TyCtxt<'tcx>,
936    ty: Ty<'tcx>,
937    is_direct_call: bool,
938    source: Span,
939    output: &mut MonoItems<'tcx>,
940) {
941    let instance = Instance::resolve_drop_glue(tcx, ty);
942    visit_instance_use(tcx, instance, is_direct_call, source, output);
943}
944
945/// For every call of this function in the visitor, make sure there is a matching call in the
946/// `mentioned_items` pass!
947fn visit_fn_use<'tcx>(
948    tcx: TyCtxt<'tcx>,
949    ty: Ty<'tcx>,
950    is_direct_call: bool,
951    source: Span,
952    output: &mut MonoItems<'tcx>,
953) {
954    if let ty::FnDef(def_id, args) = *ty.kind() {
955        let instance = if is_direct_call {
956            ty::Instance::expect_resolve(
957                tcx,
958                ty::TypingEnv::fully_monomorphized(),
959                def_id,
960                args,
961                source,
962            )
963        } else {
964            match ty::Instance::resolve_for_fn_ptr(
965                tcx,
966                ty::TypingEnv::fully_monomorphized(),
967                def_id,
968                args,
969            ) {
970                Some(instance) => instance,
971                _ => ::rustc_middle::util::bug::bug_fmt(format_args!("failed to resolve instance for {0}",
        ty))bug!("failed to resolve instance for {ty}"),
972            }
973        };
974        visit_instance_use(tcx, instance, is_direct_call, source, output);
975    }
976}
977
978fn visit_instance_use<'tcx>(
979    tcx: TyCtxt<'tcx>,
980    instance: ty::Instance<'tcx>,
981    is_direct_call: bool,
982    source: Span,
983    output: &mut MonoItems<'tcx>,
984) {
985    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_monomorphize/src/collector.rs:985",
                        "rustc_monomorphize::collector", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
                        ::tracing_core::__macro_support::Option::Some(985u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("visit_item_use({0:?}, is_direct_call={1:?})",
                                                    instance, is_direct_call) as &dyn Value))])
            });
    } else { ; }
};debug!("visit_item_use({:?}, is_direct_call={:?})", instance, is_direct_call);
986    if !tcx.should_codegen_locally(instance) {
987        return;
988    }
989    if let Some(intrinsic) = tcx.intrinsic(instance.def_id()) {
990        if let Some(_requirement) = ValidityRequirement::from_intrinsic(intrinsic.name) {
991            // The intrinsics assert_inhabited, assert_zero_valid, and assert_mem_uninitialized_valid will
992            // be lowered in codegen to nothing or a call to panic_nounwind. So if we encounter any
993            // of those intrinsics, we need to include a mono item for panic_nounwind, else we may try to
994            // codegen a call to that function without generating code for the function itself.
995            let def_id = tcx.require_lang_item(LangItem::PanicNounwind, source);
996            let panic_instance = Instance::mono(tcx, def_id);
997            if tcx.should_codegen_locally(panic_instance) {
998                output.push(create_fn_mono_item(tcx, panic_instance, source));
999            }
1000        } else if !intrinsic.must_be_overridden
1001            && (tcx.sess.opts.unstable_opts.force_intrinsic_fallback
1002                || !tcx.sess.replaced_intrinsics.contains(&intrinsic.name))
1003        {
1004            // Codegen the fallback body of intrinsics with fallback bodies.
1005            // We have to skip this otherwise as there's no body to codegen.
1006            //
1007            // We also skip `replaced_intrinsics` which are always replaced by the backend and hence
1008            // monomorphizing the fallback body would be pointless.
1009            //
1010            // However, when -Zforce-intrinsic-fallback is set (e.g. to test the fallback
1011            // implementations) we ignore the optimization hint and do monomorphize
1012            // the fallback body.
1013            let instance = ty::Instance::new_raw(instance.def_id(), instance.args);
1014            if tcx.should_codegen_locally(instance) {
1015                output.push(create_fn_mono_item(tcx, instance, source));
1016            }
1017        }
1018    }
1019
1020    match instance.def {
1021        ty::InstanceKind::Virtual(..) | ty::InstanceKind::Intrinsic(_) => {
1022            if !is_direct_call {
1023                ::rustc_middle::util::bug::bug_fmt(format_args!("{0:?} being reified",
        instance));bug!("{:?} being reified", instance);
1024            }
1025        }
1026        ty::InstanceKind::Shim(ty::ShimKind::ThreadLocal(..)) => {
1027            ::rustc_middle::util::bug::bug_fmt(format_args!("{0:?} being reified",
        instance));bug!("{:?} being reified", instance);
1028        }
1029        ty::InstanceKind::Shim(ty::ShimKind::DropGlue(_, None)) => {
1030            // Don't need to emit noop drop glue if we are calling directly.
1031            //
1032            // Note that we also optimize away the call to visit_instance_use in vtable construction
1033            // (see create_mono_items_for_vtable_methods).
1034            if !is_direct_call {
1035                output.push(create_fn_mono_item(tcx, instance, source));
1036            }
1037        }
1038        ty::InstanceKind::Item(..)
1039        | ty::InstanceKind::Shim(ty::ShimKind::DropGlue(_, Some(_)))
1040        | ty::InstanceKind::Shim(ty::ShimKind::FutureDropPoll(..))
1041        | ty::InstanceKind::Shim(ty::ShimKind::AsyncDropGlue(_, _))
1042        | ty::InstanceKind::Shim(ty::ShimKind::AsyncDropGlueCtor(_, _))
1043        | ty::InstanceKind::Shim(ty::ShimKind::VTable(..))
1044        | ty::InstanceKind::Shim(ty::ShimKind::Reify(..))
1045        | ty::InstanceKind::Shim(ty::ShimKind::ClosureOnce { .. })
1046        | ty::InstanceKind::Shim(ty::ShimKind::ConstructCoroutineInClosure { .. })
1047        | ty::InstanceKind::Shim(ty::ShimKind::FnPtr(..))
1048        | ty::InstanceKind::Shim(ty::ShimKind::Clone(..))
1049        | ty::InstanceKind::Shim(ty::ShimKind::FnPtrAddr(..)) => {
1050            output.push(create_fn_mono_item(tcx, instance, source));
1051        }
1052    }
1053}
1054
1055/// Returns `true` if we should codegen an instance in the local crate, or returns `false` if we
1056/// can just link to the upstream crate and therefore don't need a mono item.
1057fn should_codegen_locally<'tcx>(tcx: TyCtxt<'tcx>, instance: Instance<'tcx>) -> bool {
1058    let Some(def_id) = instance.def.def_id_if_not_guaranteed_local_codegen() else {
1059        return true;
1060    };
1061
1062    if tcx.is_foreign_item(def_id) {
1063        // Foreign items are always linked against, there's no way of instantiating them.
1064        return false;
1065    }
1066
1067    if tcx.def_kind(def_id).has_codegen_attrs()
1068        && #[allow(non_exhaustive_omitted_patterns)] match tcx.codegen_fn_attrs(def_id).inline
    {
    InlineAttr::Force { .. } => true,
    _ => false,
}matches!(tcx.codegen_fn_attrs(def_id).inline, InlineAttr::Force { .. })
1069    {
1070        // `#[rustc_force_inline]` items should never be codegened. This should be caught by
1071        // the MIR validator.
1072        tcx.dcx().delayed_bug("attempt to codegen `#[rustc_force_inline]` item");
1073    }
1074
1075    if def_id.is_local() {
1076        // Local items cannot be referred to locally without monomorphizing them locally.
1077        return true;
1078    }
1079
1080    if tcx.is_reachable_non_generic(def_id) || instance.upstream_monomorphization(tcx).is_some() {
1081        // We can link to the item in question, no instance needed in this crate.
1082        return false;
1083    }
1084
1085    if let DefKind::Static { .. } = tcx.def_kind(def_id) {
1086        // We cannot monomorphize statics from upstream crates.
1087        return false;
1088    }
1089
1090    // See comment in should_encode_mir in rustc_metadata for why we don't report
1091    // an error for constructors.
1092    if !tcx.is_mir_available(def_id) && !#[allow(non_exhaustive_omitted_patterns)] match tcx.def_kind(def_id) {
    DefKind::Ctor(..) => true,
    _ => false,
}matches!(tcx.def_kind(def_id), DefKind::Ctor(..)) {
1093        tcx.dcx().emit_fatal(NoOptimizedMir {
1094            span: tcx.def_span(def_id),
1095            crate_name: tcx.crate_name(def_id.krate),
1096            instance: instance.to_string(),
1097        });
1098    }
1099
1100    true
1101}
1102
1103/// For a given pair of source and target type that occur in an unsizing coercion,
1104/// this function finds the pair of types that determines the vtable linking
1105/// them.
1106///
1107/// For example, the source type might be `&SomeStruct` and the target type
1108/// might be `&dyn SomeTrait` in a cast like:
1109///
1110/// ```rust,ignore (not real code)
1111/// let src: &SomeStruct = ...;
1112/// let target = src as &dyn SomeTrait;
1113/// ```
1114///
1115/// Then the output of this function would be (SomeStruct, SomeTrait) since for
1116/// constructing the `target` wide-pointer we need the vtable for that pair.
1117///
1118/// Things can get more complicated though because there's also the case where
1119/// the unsized type occurs as a field:
1120///
1121/// ```rust
1122/// struct ComplexStruct<T: ?Sized> {
1123///    a: u32,
1124///    b: f64,
1125///    c: T
1126/// }
1127/// ```
1128///
1129/// In this case, if `T` is sized, `&ComplexStruct<T>` is a thin pointer. If `T`
1130/// is unsized, `&SomeStruct` is a wide pointer, and the vtable it points to is
1131/// for the pair of `T` (which is a trait) and the concrete type that `T` was
1132/// originally coerced from:
1133///
1134/// ```rust,ignore (not real code)
1135/// let src: &ComplexStruct<SomeStruct> = ...;
1136/// let target = src as &ComplexStruct<dyn SomeTrait>;
1137/// ```
1138///
1139/// Again, we want this `find_vtable_types_for_unsizing()` to provide the pair
1140/// `(SomeStruct, SomeTrait)`.
1141///
1142/// Finally, there is also the case of custom unsizing coercions, e.g., for
1143/// smart pointers such as `Rc` and `Arc`.
1144fn find_tails_for_unsizing<'tcx>(
1145    tcx: TyCtxtAt<'tcx>,
1146    source_ty: Ty<'tcx>,
1147    target_ty: Ty<'tcx>,
1148) -> (Ty<'tcx>, Ty<'tcx>) {
1149    let typing_env = ty::TypingEnv::fully_monomorphized();
1150    if true {
    if !!source_ty.has_param() {
        {
            ::core::panicking::panic_fmt(format_args!("{0} should be fully monomorphic",
                    source_ty));
        }
    };
};debug_assert!(!source_ty.has_param(), "{source_ty} should be fully monomorphic");
1151    if true {
    if !!target_ty.has_param() {
        {
            ::core::panicking::panic_fmt(format_args!("{0} should be fully monomorphic",
                    target_ty));
        }
    };
};debug_assert!(!target_ty.has_param(), "{target_ty} should be fully monomorphic");
1152
1153    match (source_ty.kind(), target_ty.kind()) {
1154        (&ty::Pat(source, _), &ty::Pat(target, _)) => find_tails_for_unsizing(tcx, source, target),
1155        (
1156            &ty::Ref(_, source_pointee, _),
1157            &ty::Ref(_, target_pointee, _) | &ty::RawPtr(target_pointee, _),
1158        )
1159        | (&ty::RawPtr(source_pointee, _), &ty::RawPtr(target_pointee, _)) => {
1160            tcx.struct_lockstep_tails_for_codegen(source_pointee, target_pointee, typing_env)
1161        }
1162
1163        // `Box<T>` could go through the ADT code below, b/c it'll unpeel to `Unique<T>`,
1164        // and eventually bottom out in a raw ref, but we can micro-optimize it here.
1165        (_, _)
1166            if let Some(source_boxed) = source_ty.boxed_ty()
1167                && let Some(target_boxed) = target_ty.boxed_ty() =>
1168        {
1169            tcx.struct_lockstep_tails_for_codegen(source_boxed, target_boxed, typing_env)
1170        }
1171
1172        (&ty::Adt(source_adt_def, source_args), &ty::Adt(target_adt_def, target_args)) => {
1173            {
    match (&source_adt_def, &target_adt_def) {
        (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);
            }
        }
    }
};assert_eq!(source_adt_def, target_adt_def);
1174            let CustomCoerceUnsized::Struct(coerce_index) =
1175                match crate::custom_coerce_unsize_info(tcx, source_ty, target_ty) {
1176                    Ok(ccu) => ccu,
1177                    Err(e) => {
1178                        let e = Ty::new_error(tcx.tcx, e);
1179                        return (e, e);
1180                    }
1181                };
1182            let coerce_field = &source_adt_def.non_enum_variant().fields[coerce_index];
1183            // We're getting a possibly unnormalized type, so normalize it.
1184            let source_field =
1185                tcx.normalize_erasing_regions(typing_env, coerce_field.ty(*tcx, source_args));
1186            let target_field =
1187                tcx.normalize_erasing_regions(typing_env, coerce_field.ty(*tcx, target_args));
1188            find_tails_for_unsizing(tcx, source_field, target_field)
1189        }
1190
1191        _ => ::rustc_middle::util::bug::bug_fmt(format_args!("find_vtable_types_for_unsizing: invalid coercion {0:?} -> {1:?}",
        source_ty, target_ty))bug!(
1192            "find_vtable_types_for_unsizing: invalid coercion {:?} -> {:?}",
1193            source_ty,
1194            target_ty
1195        ),
1196    }
1197}
1198
1199x;#[instrument(skip(tcx), level = "debug", ret)]
1200fn create_fn_mono_item<'tcx>(
1201    tcx: TyCtxt<'tcx>,
1202    instance: Instance<'tcx>,
1203    source: Span,
1204) -> Spanned<MonoItem<'tcx>> {
1205    let def_id = instance.def_id();
1206    if tcx.sess.opts.unstable_opts.profile_closures
1207        && def_id.is_local()
1208        && tcx.is_closure_like(def_id)
1209    {
1210        crate::util::dump_closure_profile(tcx, instance);
1211    }
1212
1213    respan(source, MonoItem::Fn(instance))
1214}
1215
1216/// Creates a `MonoItem` for each method that is referenced by the vtable for
1217/// the given trait/impl pair.
1218fn create_mono_items_for_vtable_methods<'tcx>(
1219    tcx: TyCtxt<'tcx>,
1220    trait_ty: Ty<'tcx>,
1221    impl_ty: Ty<'tcx>,
1222    source: Span,
1223    output: &mut MonoItems<'tcx>,
1224) {
1225    if !(!trait_ty.has_escaping_bound_vars() &&
            !impl_ty.has_escaping_bound_vars()) {
    ::core::panicking::panic("assertion failed: !trait_ty.has_escaping_bound_vars() && !impl_ty.has_escaping_bound_vars()")
};assert!(!trait_ty.has_escaping_bound_vars() && !impl_ty.has_escaping_bound_vars());
1226
1227    let ty::Dynamic(trait_ty, ..) = trait_ty.kind() else {
1228        ::rustc_middle::util::bug::bug_fmt(format_args!("create_mono_items_for_vtable_methods: {0:?} not a trait type",
        trait_ty));bug!("create_mono_items_for_vtable_methods: {trait_ty:?} not a trait type");
1229    };
1230    if let Some(principal) = trait_ty.principal() {
1231        let trait_ref =
1232            tcx.instantiate_bound_regions_with_erased(principal.with_self_ty(tcx, impl_ty));
1233        if !!trait_ref.has_escaping_bound_vars() {
    ::core::panicking::panic("assertion failed: !trait_ref.has_escaping_bound_vars()")
};assert!(!trait_ref.has_escaping_bound_vars());
1234
1235        // Walk all methods of the trait, including those of its supertraits
1236        let entries = tcx.vtable_entries(trait_ref);
1237        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_monomorphize/src/collector.rs:1237",
                        "rustc_monomorphize::collector", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
                        ::tracing_core::__macro_support::Option::Some(1237u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
                        ::tracing_core::field::FieldSet::new(&["entries"],
                            ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&debug(&entries) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(?entries);
1238        let methods = entries
1239            .iter()
1240            .filter_map(|entry| match entry {
1241                VtblEntry::MetadataDropInPlace
1242                | VtblEntry::MetadataSize
1243                | VtblEntry::MetadataAlign
1244                | VtblEntry::Vacant => None,
1245                VtblEntry::TraitVPtr(_) => {
1246                    // all super trait items already covered, so skip them.
1247                    None
1248                }
1249                VtblEntry::Method(instance) => {
1250                    Some(*instance).filter(|instance| tcx.should_codegen_locally(*instance))
1251                }
1252            })
1253            .map(|item| create_fn_mono_item(tcx, item, source));
1254        output.extend(methods);
1255    }
1256
1257    // Also add the destructor, if it's necessary.
1258    //
1259    // This matches the check in vtable_allocation_provider in middle/ty/vtable.rs,
1260    // if we don't need drop we're not adding an actual pointer to the vtable.
1261    if impl_ty.needs_drop(tcx, ty::TypingEnv::fully_monomorphized()) {
1262        visit_drop_use(tcx, impl_ty, false, source, output);
1263    }
1264}
1265
1266/// Scans the CTFE alloc in order to find function pointers and statics that must be monomorphized.
1267fn collect_alloc<'tcx>(tcx: TyCtxt<'tcx>, alloc_id: AllocId, output: &mut MonoItems<'tcx>) {
1268    match tcx.global_alloc(alloc_id) {
1269        GlobalAlloc::Static(def_id) => {
1270            if !!tcx.is_thread_local_static(def_id) {
    ::core::panicking::panic("assertion failed: !tcx.is_thread_local_static(def_id)")
};assert!(!tcx.is_thread_local_static(def_id));
1271            let instance = Instance::mono(tcx, def_id);
1272            if tcx.should_codegen_locally(instance) {
1273                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_monomorphize/src/collector.rs:1273",
                        "rustc_monomorphize::collector", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
                        ::tracing_core::__macro_support::Option::Some(1273u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("collecting static {0:?}",
                                                    def_id) as &dyn Value))])
            });
    } else { ; }
};trace!("collecting static {:?}", def_id);
1274                output.push(dummy_spanned(MonoItem::Static(def_id)));
1275            }
1276        }
1277        GlobalAlloc::Memory(alloc) => {
1278            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_monomorphize/src/collector.rs:1278",
                        "rustc_monomorphize::collector", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
                        ::tracing_core::__macro_support::Option::Some(1278u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("collecting {0:?} with {1:#?}",
                                                    alloc_id, alloc) as &dyn Value))])
            });
    } else { ; }
};trace!("collecting {:?} with {:#?}", alloc_id, alloc);
1279            let ptrs = alloc.inner().provenance().ptrs();
1280            // avoid `ensure_sufficient_stack` in the common case of "no pointers"
1281            if !ptrs.is_empty() {
1282                rustc_data_structures::stack::ensure_sufficient_stack(move || {
1283                    for &prov in ptrs.values() {
1284                        collect_alloc(tcx, prov.alloc_id(), output);
1285                    }
1286                });
1287            }
1288        }
1289        GlobalAlloc::Function { instance, .. } => {
1290            if tcx.should_codegen_locally(instance) {
1291                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_monomorphize/src/collector.rs:1291",
                        "rustc_monomorphize::collector", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
                        ::tracing_core::__macro_support::Option::Some(1291u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("collecting {0:?} with {1:#?}",
                                                    alloc_id, instance) as &dyn Value))])
            });
    } else { ; }
};trace!("collecting {:?} with {:#?}", alloc_id, instance);
1292                output.push(create_fn_mono_item(tcx, instance, DUMMY_SP));
1293            }
1294        }
1295        GlobalAlloc::VTable(ty, dyn_ty) => {
1296            let alloc_id = tcx.vtable_allocation((
1297                ty,
1298                dyn_ty
1299                    .principal()
1300                    .map(|principal| tcx.instantiate_bound_regions_with_erased(principal)),
1301            ));
1302            collect_alloc(tcx, alloc_id, output)
1303        }
1304        GlobalAlloc::TypeId { .. } => {}
1305    }
1306}
1307
1308/// Scans the MIR in order to find function calls, closures, and drop-glue.
1309///
1310/// Anything that's found is added to `output`. Furthermore the "mentioned items" of the MIR are returned.
1311#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("collect_items_of_instance",
                                    "rustc_monomorphize::collector", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1311u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
                                    ::tracing_core::field::FieldSet::new(&["instance", "mode"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&instance)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&mode)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return:
                    Result<(MonoItems<'tcx>, MonoItems<'tcx>),
                    NormalizationErrorInMono> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let body = tcx.instance_mir(instance.def);
            check_normalization_error(tcx, instance, body)?;
            tcx.ensure_ok().check_mono_item(instance);
            let mut used_items = MonoItems::new();
            let mut mentioned_items = MonoItems::new();
            let mut used_mentioned_items = Default::default();
            let mut collector =
                MirUsedCollector {
                    tcx,
                    body,
                    used_items: &mut used_items,
                    used_mentioned_items: &mut used_mentioned_items,
                    instance,
                };
            if mode == CollectionMode::UsedItems {
                if tcx.sess.opts.debuginfo == DebugInfo::Full {
                    for var_debug_info in &body.var_debug_info {
                        collector.visit_var_debug_info(var_debug_info);
                    }
                }
                for (bb, data) in
                    traversal::mono_reachable(body, tcx, instance) {
                    collector.visit_basic_block_data(bb, data)
                }
            }
            for const_op in body.required_consts() {
                if let Some(val) = collector.eval_constant(const_op) {
                    collect_const_value(tcx, val, &mut mentioned_items);
                }
            }
            for item in body.mentioned_items() {
                if !collector.used_mentioned_items.contains(&item.node) {
                    let item_mono = collector.monomorphize(item.node);
                    visit_mentioned_item(tcx, &item_mono, item.span,
                        &mut mentioned_items);
                }
            }
            Ok((used_items, mentioned_items))
        }
    }
}#[instrument(skip(tcx), level = "debug")]
1312fn collect_items_of_instance<'tcx>(
1313    tcx: TyCtxt<'tcx>,
1314    instance: Instance<'tcx>,
1315    mode: CollectionMode,
1316) -> Result<(MonoItems<'tcx>, MonoItems<'tcx>), NormalizationErrorInMono> {
1317    // This item is getting monomorphized, do mono-time checks.
1318    let body = tcx.instance_mir(instance.def);
1319    // Plenty of code paths later assume that everything can be normalized. So we have to check
1320    // normalization first.
1321    // We choose to emit the error outside to provide helpful diagnostics.
1322    check_normalization_error(tcx, instance, body)?;
1323    tcx.ensure_ok().check_mono_item(instance);
1324
1325    // Naively, in "used" collection mode, all functions get added to *both* `used_items` and
1326    // `mentioned_items`. Mentioned items processing will then notice that they have already been
1327    // visited, but at that point each mentioned item has been monomorphized, added to the
1328    // `mentioned_items` worklist, and checked in the global set of visited items. To remove that
1329    // overhead, we have a special optimization that avoids adding items to `mentioned_items` when
1330    // they are already added in `used_items`. We could just scan `used_items`, but that's a linear
1331    // scan and not very efficient. Furthermore we can only do that *after* monomorphizing the
1332    // mentioned item. So instead we collect all pre-monomorphized `MentionedItem` that were already
1333    // added to `used_items` in a hash set, which can efficiently query in the
1334    // `body.mentioned_items` loop below without even having to monomorphize the item.
1335    let mut used_items = MonoItems::new();
1336    let mut mentioned_items = MonoItems::new();
1337    let mut used_mentioned_items = Default::default();
1338    let mut collector = MirUsedCollector {
1339        tcx,
1340        body,
1341        used_items: &mut used_items,
1342        used_mentioned_items: &mut used_mentioned_items,
1343        instance,
1344    };
1345
1346    if mode == CollectionMode::UsedItems {
1347        if tcx.sess.opts.debuginfo == DebugInfo::Full {
1348            for var_debug_info in &body.var_debug_info {
1349                collector.visit_var_debug_info(var_debug_info);
1350            }
1351        }
1352        for (bb, data) in traversal::mono_reachable(body, tcx, instance) {
1353            collector.visit_basic_block_data(bb, data)
1354        }
1355    }
1356
1357    // Always visit all `required_consts`, so that we evaluate them and abort compilation if any of
1358    // them errors.
1359    for const_op in body.required_consts() {
1360        if let Some(val) = collector.eval_constant(const_op) {
1361            collect_const_value(tcx, val, &mut mentioned_items);
1362        }
1363    }
1364
1365    // Always gather mentioned items. We try to avoid processing items that we have already added to
1366    // `used_items` above.
1367    for item in body.mentioned_items() {
1368        if !collector.used_mentioned_items.contains(&item.node) {
1369            let item_mono = collector.monomorphize(item.node);
1370            visit_mentioned_item(tcx, &item_mono, item.span, &mut mentioned_items);
1371        }
1372    }
1373
1374    Ok((used_items, mentioned_items))
1375}
1376
1377fn items_of_instance<'tcx>(
1378    tcx: TyCtxt<'tcx>,
1379    (instance, mode): (Instance<'tcx>, CollectionMode),
1380) -> Result<
1381    (&'tcx [Spanned<MonoItem<'tcx>>], &'tcx [Spanned<MonoItem<'tcx>>]),
1382    NormalizationErrorInMono,
1383> {
1384    let (used_items, mentioned_items) = collect_items_of_instance(tcx, instance, mode)?;
1385
1386    let used_items = tcx.arena.alloc_from_iter(used_items);
1387    let mentioned_items = tcx.arena.alloc_from_iter(mentioned_items);
1388
1389    Ok((used_items, mentioned_items))
1390}
1391
1392/// `item` must be already monomorphized.
1393#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("visit_mentioned_item",
                                    "rustc_monomorphize::collector", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1393u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
                                    ::tracing_core::field::FieldSet::new(&["item"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            match *item {
                MentionedItem::Fn(ty) => {
                    if let ty::FnDef(def_id, args) = *ty.kind() {
                        let instance =
                            Instance::expect_resolve(tcx,
                                ty::TypingEnv::fully_monomorphized(), def_id, args, span);
                        visit_instance_use(tcx, instance, true, span, output);
                    }
                }
                MentionedItem::Drop(ty) => {
                    visit_drop_use(tcx, ty, true, span, output);
                }
                MentionedItem::UnsizeCast { source_ty, target_ty } => {
                    let (source_ty, target_ty) =
                        find_tails_for_unsizing(tcx.at(span), source_ty, target_ty);
                    if target_ty.is_trait() && !source_ty.is_trait() {
                        create_mono_items_for_vtable_methods(tcx, target_ty,
                            source_ty, span, output);
                    }
                }
                MentionedItem::Closure(source_ty) => {
                    if let ty::Closure(def_id, args) = *source_ty.kind() {
                        let instance =
                            Instance::resolve_closure(tcx, def_id, args,
                                ty::ClosureKind::FnOnce);
                        if tcx.should_codegen_locally(instance) {
                            output.push(create_fn_mono_item(tcx, instance, span));
                        }
                    } else {
                        ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))
                    }
                }
            }
        }
    }
}#[instrument(skip(tcx, span, output), level = "debug")]
1394fn visit_mentioned_item<'tcx>(
1395    tcx: TyCtxt<'tcx>,
1396    item: &MentionedItem<'tcx>,
1397    span: Span,
1398    output: &mut MonoItems<'tcx>,
1399) {
1400    match *item {
1401        MentionedItem::Fn(ty) => {
1402            if let ty::FnDef(def_id, args) = *ty.kind() {
1403                let instance = Instance::expect_resolve(
1404                    tcx,
1405                    ty::TypingEnv::fully_monomorphized(),
1406                    def_id,
1407                    args,
1408                    span,
1409                );
1410                // `visit_instance_use` was written for "used" item collection but works just as well
1411                // for "mentioned" item collection.
1412                // We can set `is_direct_call`; that just means we'll skip a bunch of shims that anyway
1413                // can't have their own failing constants.
1414                visit_instance_use(tcx, instance, /*is_direct_call*/ true, span, output);
1415            }
1416        }
1417        MentionedItem::Drop(ty) => {
1418            visit_drop_use(tcx, ty, /*is_direct_call*/ true, span, output);
1419        }
1420        MentionedItem::UnsizeCast { source_ty, target_ty } => {
1421            let (source_ty, target_ty) =
1422                find_tails_for_unsizing(tcx.at(span), source_ty, target_ty);
1423            // This could also be a different Unsize instruction, like
1424            // from a fixed sized array to a slice. But we are only
1425            // interested in things that produce a vtable.
1426            if target_ty.is_trait() && !source_ty.is_trait() {
1427                create_mono_items_for_vtable_methods(tcx, target_ty, source_ty, span, output);
1428            }
1429        }
1430        MentionedItem::Closure(source_ty) => {
1431            if let ty::Closure(def_id, args) = *source_ty.kind() {
1432                let instance =
1433                    Instance::resolve_closure(tcx, def_id, args, ty::ClosureKind::FnOnce);
1434                if tcx.should_codegen_locally(instance) {
1435                    output.push(create_fn_mono_item(tcx, instance, span));
1436                }
1437            } else {
1438                bug!()
1439            }
1440        }
1441    }
1442}
1443
1444#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("collect_const_value",
                                    "rustc_monomorphize::collector", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1444u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
                                    ::tracing_core::field::FieldSet::new(&["value"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&value)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            match value {
                mir::ConstValue::Scalar(Scalar::Ptr(ptr, _size)) => {
                    collect_alloc(tcx, ptr.provenance.alloc_id(), output)
                }
                mir::ConstValue::Indirect { alloc_id, .. } |
                    mir::ConstValue::Slice { alloc_id, meta: _ } =>
                    collect_alloc(tcx, alloc_id, output),
                _ => {}
            }
        }
    }
}#[instrument(skip(tcx, output), level = "debug")]
1445fn collect_const_value<'tcx>(
1446    tcx: TyCtxt<'tcx>,
1447    value: mir::ConstValue,
1448    output: &mut MonoItems<'tcx>,
1449) {
1450    match value {
1451        mir::ConstValue::Scalar(Scalar::Ptr(ptr, _size)) => {
1452            collect_alloc(tcx, ptr.provenance.alloc_id(), output)
1453        }
1454        mir::ConstValue::Indirect { alloc_id, .. }
1455        | mir::ConstValue::Slice { alloc_id, meta: _ } => collect_alloc(tcx, alloc_id, output),
1456        _ => {}
1457    }
1458}
1459
1460//=-----------------------------------------------------------------------------
1461// Root Collection
1462//=-----------------------------------------------------------------------------
1463
1464// Find all non-generic items by walking the HIR. These items serve as roots to
1465// start monomorphizing from.
1466#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("collect_roots",
                                    "rustc_monomorphize::collector", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1466u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: Vec<MonoItem<'_>> = loop {};
            return __tracing_attr_fake_return;
        }
        {
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_monomorphize/src/collector.rs:1468",
                                    "rustc_monomorphize::collector", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1468u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
                                    ::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};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("collecting roots")
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            let mut roots = MonoItems::new();
            {
                let entry_fn = tcx.entry_fn(());
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_monomorphize/src/collector.rs:1474",
                                        "rustc_monomorphize::collector", ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
                                        ::tracing_core::__macro_support::Option::Some(1474u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
                                        ::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};
                                let mut iter = __CALLSITE.metadata().fields().iter();
                                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&format_args!("collect_roots: entry_fn = {0:?}",
                                                                    entry_fn) as &dyn Value))])
                            });
                    } else { ; }
                };
                let mut collector =
                    RootCollector {
                        tcx,
                        strategy: mode,
                        entry_fn,
                        output: &mut roots,
                    };
                let crate_items = tcx.hir_crate_items(());
                for id in crate_items.free_items() {
                    collector.process_item(id);
                }
                for id in crate_items.impl_items() {
                    collector.process_impl_item(id);
                }
                for id in crate_items.nested_bodies() {
                    collector.process_nested_body(id);
                }
                collector.push_extra_entry_roots();
            }
            roots.into_iter().filter_map(|Spanned { node: mono_item, .. }|
                        {
                            mono_item.is_instantiable(tcx).then_some(mono_item)
                        }).collect()
        }
    }
}#[instrument(skip(tcx, mode), level = "debug")]
1467fn collect_roots(tcx: TyCtxt<'_>, mode: MonoItemCollectionStrategy) -> Vec<MonoItem<'_>> {
1468    debug!("collecting roots");
1469    let mut roots = MonoItems::new();
1470
1471    {
1472        let entry_fn = tcx.entry_fn(());
1473
1474        debug!("collect_roots: entry_fn = {:?}", entry_fn);
1475
1476        let mut collector = RootCollector { tcx, strategy: mode, entry_fn, output: &mut roots };
1477
1478        let crate_items = tcx.hir_crate_items(());
1479
1480        for id in crate_items.free_items() {
1481            collector.process_item(id);
1482        }
1483
1484        for id in crate_items.impl_items() {
1485            collector.process_impl_item(id);
1486        }
1487
1488        for id in crate_items.nested_bodies() {
1489            collector.process_nested_body(id);
1490        }
1491
1492        collector.push_extra_entry_roots();
1493    }
1494
1495    // We can only codegen items that are instantiable - items all of
1496    // whose predicates hold. Luckily, items that aren't instantiable
1497    // can't actually be used, so we can just skip codegenning them.
1498    roots
1499        .into_iter()
1500        .filter_map(|Spanned { node: mono_item, .. }| {
1501            mono_item.is_instantiable(tcx).then_some(mono_item)
1502        })
1503        .collect()
1504}
1505
1506struct RootCollector<'a, 'tcx> {
1507    tcx: TyCtxt<'tcx>,
1508    strategy: MonoItemCollectionStrategy,
1509    output: &'a mut MonoItems<'tcx>,
1510    entry_fn: Option<(DefId, EntryFnType)>,
1511}
1512
1513impl<'v> RootCollector<'_, 'v> {
1514    fn process_item(&mut self, id: hir::ItemId) {
1515        match self.tcx.def_kind(id.owner_id) {
1516            DefKind::Enum | DefKind::Struct | DefKind::Union => {
1517                if self.strategy == MonoItemCollectionStrategy::Eager
1518                    && !self.tcx.generics_of(id.owner_id).requires_monomorphization(self.tcx)
1519                {
1520                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_monomorphize/src/collector.rs:1520",
                        "rustc_monomorphize::collector", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
                        ::tracing_core::__macro_support::Option::Some(1520u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("RootCollector: ADT drop-glue for `{0:?}`",
                                                    id) as &dyn Value))])
            });
    } else { ; }
};debug!("RootCollector: ADT drop-glue for `{id:?}`",);
1521                    let id_args =
1522                        ty::GenericArgs::for_item(self.tcx, id.owner_id.to_def_id(), |param, _| {
1523                            match param.kind {
1524                                GenericParamDefKind::Lifetime => {
1525                                    self.tcx.lifetimes.re_erased.into()
1526                                }
1527                                GenericParamDefKind::Type { .. }
1528                                | GenericParamDefKind::Const { .. } => {
1529                                    {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("`own_requires_monomorphization` check means that we should have no type/const params")));
}unreachable!(
1530                                        "`own_requires_monomorphization` check means that \
1531                                we should have no type/const params"
1532                                    )
1533                                }
1534                            }
1535                        });
1536
1537                    // This type is impossible to instantiate, so we should not try to
1538                    // generate a `drop_glue` instance for it.
1539                    if self.tcx.instantiate_and_check_impossible_predicates((
1540                        id.owner_id.to_def_id(),
1541                        id_args,
1542                    )) {
1543                        return;
1544                    }
1545
1546                    let ty = self
1547                        .tcx
1548                        .type_of(id.owner_id.to_def_id())
1549                        .instantiate(self.tcx, id_args)
1550                        .skip_norm_wip();
1551                    if !!ty.has_non_region_param() {
    ::core::panicking::panic("assertion failed: !ty.has_non_region_param()")
};assert!(!ty.has_non_region_param());
1552                    visit_drop_use(self.tcx, ty, true, DUMMY_SP, self.output);
1553                }
1554            }
1555            DefKind::GlobalAsm => {
1556                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_monomorphize/src/collector.rs:1556",
                        "rustc_monomorphize::collector", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
                        ::tracing_core::__macro_support::Option::Some(1556u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("RootCollector: ItemKind::GlobalAsm({0})",
                                                    self.tcx.def_path_str(id.owner_id)) as &dyn Value))])
            });
    } else { ; }
};debug!(
1557                    "RootCollector: ItemKind::GlobalAsm({})",
1558                    self.tcx.def_path_str(id.owner_id)
1559                );
1560                self.output.push(dummy_spanned(MonoItem::GlobalAsm(id)));
1561            }
1562            DefKind::Static { .. } => {
1563                let def_id = id.owner_id.to_def_id();
1564                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_monomorphize/src/collector.rs:1564",
                        "rustc_monomorphize::collector", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
                        ::tracing_core::__macro_support::Option::Some(1564u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
                        ::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};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("RootCollector: ItemKind::Static({0})",
                                                    self.tcx.def_path_str(def_id)) as &dyn Value))])
            });
    } else { ; }
};debug!("RootCollector: ItemKind::Static({})", self.tcx.def_path_str(def_id));
1565                self.output.push(dummy_spanned(MonoItem::Static(def_id)));
1566            }
1567            DefKind::Const { .. } => {
1568                // Const items only generate mono items if they are actually used somewhere.
1569                // Just declaring them is insufficient.
1570
1571                // If we're collecting items eagerly, then recurse into all constants.
1572                // Otherwise the value is only collected when explicitly mentioned in other items.
1573                if self.strategy == MonoItemCollectionStrategy::Eager {
1574                    let def_id = id.owner_id.to_def_id();
1575                    // Type Consts don't have bodies to evaluate
1576                    // nor do they make sense as a static.
1577                    if self.tcx.is_type_const(def_id) {
1578                        // FIXME(mgca): Is this actually what we want? We may want to
1579                        // normalize to a ValTree then convert to a const allocation and
1580                        // collect that?
1581                        return;
1582                    }
1583                    if self.tcx.generics_of(id.owner_id).own_requires_monomorphization() {
1584                        return;
1585                    }
1586                    let Ok(val) = self.tcx.const_eval_poly(def_id) else {
1587                        return;
1588                    };
1589                    collect_const_value(self.tcx, val, self.output);
1590                }
1591            }
1592            DefKind::Impl { of_trait: true } => {
1593                if self.strategy == MonoItemCollectionStrategy::Eager {
1594                    create_mono_items_for_default_impls(self.tcx, id, self.output);
1595                }
1596            }
1597            DefKind::Fn => {
1598                self.push_if_root(id.owner_id.def_id);
1599            }
1600            _ => {}
1601        }
1602    }
1603
1604    fn process_impl_item(&mut self, id: hir::ImplItemId) {
1605        if self.tcx.def_kind(id.owner_id) == DefKind::AssocFn {
1606            self.push_if_root(id.owner_id.def_id);
1607        }
1608    }
1609
1610    fn process_nested_body(&mut self, def_id: LocalDefId) {
1611        match self.tcx.def_kind(def_id) {
1612            DefKind::Closure => {
1613                // for 'pub async fn foo(..)' also trying to monomorphize foo::{closure}
1614                let is_pub_fn_coroutine =
1615                    match *self.tcx.type_of(def_id).instantiate_identity().skip_norm_wip().kind() {
1616                        ty::Coroutine(cor_id, _args) => {
1617                            let tcx = self.tcx;
1618                            let parent_id = tcx.parent(cor_id);
1619                            tcx.def_kind(parent_id) == DefKind::Fn
1620                                && tcx.asyncness(parent_id).is_async()
1621                                && tcx.visibility(parent_id).is_public()
1622                        }
1623                        ty::Closure(..) | ty::CoroutineClosure(..) => false,
1624                        _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1625                    };
1626                if (self.strategy == MonoItemCollectionStrategy::Eager || is_pub_fn_coroutine)
1627                    && !self
1628                        .tcx
1629                        .generics_of(self.tcx.typeck_root_def_id_local(def_id))
1630                        .requires_monomorphization(self.tcx)
1631                {
1632                    let instance = match *self
1633                        .tcx
1634                        .type_of(def_id)
1635                        .instantiate_identity()
1636                        .skip_norm_wip()
1637                        .kind()
1638                    {
1639                        ty::Closure(def_id, args)
1640                        | ty::Coroutine(def_id, args)
1641                        | ty::CoroutineClosure(def_id, args) => {
1642                            Instance::new_raw(def_id, self.tcx.erase_and_anonymize_regions(args))
1643                        }
1644                        _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1645                    };
1646                    let Ok(instance) = self.tcx.try_normalize_erasing_regions(
1647                        ty::TypingEnv::fully_monomorphized(),
1648                        Unnormalized::new_wip(instance),
1649                    ) else {
1650                        // Don't ICE on an impossible-to-normalize closure.
1651                        return;
1652                    };
1653                    let mono_item = create_fn_mono_item(self.tcx, instance, DUMMY_SP);
1654                    if mono_item.node.is_instantiable(self.tcx) {
1655                        self.output.push(mono_item);
1656                    }
1657                }
1658            }
1659            _ => {}
1660        }
1661    }
1662
1663    fn is_root(&self, def_id: LocalDefId) -> bool {
1664        !self.tcx.generics_of(def_id).requires_monomorphization(self.tcx)
1665            && match self.strategy {
1666                MonoItemCollectionStrategy::Eager => {
1667                    !#[allow(non_exhaustive_omitted_patterns)] match self.tcx.codegen_fn_attrs(def_id).inline
    {
    InlineAttr::Force { .. } => true,
    _ => false,
}matches!(self.tcx.codegen_fn_attrs(def_id).inline, InlineAttr::Force { .. })
1668                }
1669                MonoItemCollectionStrategy::Lazy => {
1670                    self.entry_fn.and_then(|(id, _)| id.as_local()) == Some(def_id)
1671                        || self.tcx.is_reachable_non_generic(def_id)
1672                        || {
1673                            let flags = self.tcx.codegen_fn_attrs(def_id).flags;
1674                            flags.intersects(
1675                                CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL
1676                                    | CodegenFnAttrFlags::EXTERNALLY_IMPLEMENTABLE_ITEM,
1677                            )
1678                        }
1679                }
1680            }
1681    }
1682
1683    /// If `def_id` represents a root, pushes it onto the list of
1684    /// outputs. (Note that all roots must be monomorphic.)
1685    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("push_if_root",
                                    "rustc_monomorphize::collector", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1685u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
                                    ::tracing_core::field::FieldSet::new(&["def_id"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&def_id)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if self.is_root(def_id) {
                {
                    use ::tracing::__macro_support::Callsite as _;
                    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                        {
                            static META: ::tracing::Metadata<'static> =
                                {
                                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_monomorphize/src/collector.rs:1688",
                                        "rustc_monomorphize::collector", ::tracing::Level::DEBUG,
                                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
                                        ::tracing_core::__macro_support::Option::Some(1688u32),
                                        ::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
                                        ::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};
                                let mut iter = __CALLSITE.metadata().fields().iter();
                                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&format_args!("found root")
                                                            as &dyn Value))])
                            });
                    } else { ; }
                };
                let instance = Instance::mono(self.tcx, def_id.to_def_id());
                self.output.push(create_fn_mono_item(self.tcx, instance,
                        DUMMY_SP));
            }
        }
    }
}#[instrument(skip(self), level = "debug")]
1686    fn push_if_root(&mut self, def_id: LocalDefId) {
1687        if self.is_root(def_id) {
1688            debug!("found root");
1689
1690            let instance = Instance::mono(self.tcx, def_id.to_def_id());
1691            self.output.push(create_fn_mono_item(self.tcx, instance, DUMMY_SP));
1692        }
1693    }
1694
1695    /// As a special case, when/if we encounter the
1696    /// `main()` function, we also have to generate a
1697    /// monomorphized copy of the start lang item based on
1698    /// the return type of `main`. This is not needed when
1699    /// the user writes their own `start` manually.
1700    fn push_extra_entry_roots(&mut self) {
1701        let Some((main_def_id, EntryFnType::Main { .. })) = self.entry_fn else {
1702            return;
1703        };
1704
1705        let main_instance = Instance::mono(self.tcx, main_def_id);
1706        if self.tcx.should_codegen_locally(main_instance) {
1707            self.output.push(create_fn_mono_item(
1708                self.tcx,
1709                main_instance,
1710                self.tcx.def_span(main_def_id),
1711            ));
1712        }
1713
1714        let Some(start_def_id) = self.tcx.lang_items().start_fn() else {
1715            self.tcx.dcx().emit_fatal(diagnostics::StartNotFound);
1716        };
1717        let main_ret_ty = self.tcx.fn_sig(main_def_id).no_bound_vars().unwrap().output();
1718
1719        // Given that `main()` has no arguments,
1720        // then its return type cannot have
1721        // late-bound regions, since late-bound
1722        // regions must appear in the argument
1723        // listing.
1724        let main_ret_ty = self.tcx.normalize_erasing_regions(
1725            ty::TypingEnv::fully_monomorphized(),
1726            Unnormalized::new_wip(main_ret_ty.no_bound_vars().unwrap()),
1727        );
1728
1729        let start_instance = Instance::expect_resolve(
1730            self.tcx,
1731            ty::TypingEnv::fully_monomorphized(),
1732            start_def_id,
1733            self.tcx.mk_args(&[main_ret_ty.into()]),
1734            DUMMY_SP,
1735        );
1736
1737        self.output.push(create_fn_mono_item(self.tcx, start_instance, DUMMY_SP));
1738    }
1739}
1740
1741#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("create_mono_items_for_default_impls",
                                    "rustc_monomorphize::collector", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1741u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
                                    ::tracing_core::field::FieldSet::new(&["item"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&item)
                                                            as &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let impl_ = tcx.impl_trait_header(item.owner_id);
            if impl_.polarity == ty::ImplPolarity::Negative { return; }
            if tcx.generics_of(item.owner_id).own_requires_monomorphization()
                {
                return;
            }
            let only_region_params =
                |param: &ty::GenericParamDef, _: &_|
                    match param.kind {
                        GenericParamDefKind::Lifetime =>
                            tcx.lifetimes.re_erased.into(),
                        GenericParamDefKind::Type { .. } |
                            GenericParamDefKind::Const { .. } => {
                            {
                                ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
                                        format_args!("`own_requires_monomorphization` check means that we should have no type/const params")));
                            }
                        }
                    };
            let impl_args =
                GenericArgs::for_item(tcx, item.owner_id.to_def_id(),
                    only_region_params);
            let trait_ref =
                impl_.trait_ref.instantiate(tcx, impl_args).skip_norm_wip();
            if tcx.instantiate_and_check_impossible_predicates((item.owner_id.to_def_id(),
                        impl_args)) {
                return;
            }
            let typing_env = ty::TypingEnv::fully_monomorphized();
            let trait_ref =
                tcx.normalize_erasing_regions(typing_env,
                    Unnormalized::new_wip(trait_ref));
            let overridden_methods =
                tcx.impl_item_implementor_ids(item.owner_id);
            for method in tcx.provided_trait_methods(trait_ref.def_id) {
                if overridden_methods.contains_key(&method.def_id) {
                    continue;
                }
                if tcx.generics_of(method.def_id).own_requires_monomorphization()
                    {
                    continue;
                }
                let args =
                    trait_ref.args.extend_to(tcx, method.def_id,
                        only_region_params);
                let instance =
                    ty::Instance::expect_resolve(tcx, typing_env, method.def_id,
                        args, DUMMY_SP);
                let mono_item = create_fn_mono_item(tcx, instance, DUMMY_SP);
                if mono_item.node.is_instantiable(tcx) &&
                        tcx.should_codegen_locally(instance) {
                    output.push(mono_item);
                }
            }
        }
    }
}#[instrument(level = "debug", skip(tcx, output))]
1742fn create_mono_items_for_default_impls<'tcx>(
1743    tcx: TyCtxt<'tcx>,
1744    item: hir::ItemId,
1745    output: &mut MonoItems<'tcx>,
1746) {
1747    let impl_ = tcx.impl_trait_header(item.owner_id);
1748
1749    if impl_.polarity == ty::ImplPolarity::Negative {
1750        return;
1751    }
1752
1753    if tcx.generics_of(item.owner_id).own_requires_monomorphization() {
1754        return;
1755    }
1756
1757    // Lifetimes never affect trait selection, so we are allowed to eagerly
1758    // instantiate an instance of an impl method if the impl (and method,
1759    // which we check below) is only parameterized over lifetime. In that case,
1760    // we use the ReErased, which has no lifetime information associated with
1761    // it, to validate whether or not the impl is legal to instantiate at all.
1762    let only_region_params = |param: &ty::GenericParamDef, _: &_| match param.kind {
1763        GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(),
1764        GenericParamDefKind::Type { .. } | GenericParamDefKind::Const { .. } => {
1765            unreachable!(
1766                "`own_requires_monomorphization` check means that \
1767                we should have no type/const params"
1768            )
1769        }
1770    };
1771    let impl_args = GenericArgs::for_item(tcx, item.owner_id.to_def_id(), only_region_params);
1772    let trait_ref = impl_.trait_ref.instantiate(tcx, impl_args).skip_norm_wip();
1773
1774    // Unlike 'lazy' monomorphization that begins by collecting items transitively
1775    // called by `main` or other global items, when eagerly monomorphizing impl
1776    // items, we never actually check that the predicates of this impl are satisfied
1777    // in a empty param env (i.e. with no assumptions).
1778    //
1779    // Even though this impl has no type or const generic parameters, because we don't
1780    // consider higher-ranked predicates such as `for<'a> &'a mut [u8]: Copy` to
1781    // be trivially false. We must now check that the impl has no impossible-to-satisfy
1782    // predicates.
1783    if tcx.instantiate_and_check_impossible_predicates((item.owner_id.to_def_id(), impl_args)) {
1784        return;
1785    }
1786
1787    let typing_env = ty::TypingEnv::fully_monomorphized();
1788    let trait_ref = tcx.normalize_erasing_regions(typing_env, Unnormalized::new_wip(trait_ref));
1789    let overridden_methods = tcx.impl_item_implementor_ids(item.owner_id);
1790    for method in tcx.provided_trait_methods(trait_ref.def_id) {
1791        if overridden_methods.contains_key(&method.def_id) {
1792            continue;
1793        }
1794
1795        if tcx.generics_of(method.def_id).own_requires_monomorphization() {
1796            continue;
1797        }
1798
1799        // As mentioned above, the method is legal to eagerly instantiate if it
1800        // only has lifetime generic parameters. This is validated by calling
1801        // `own_requires_monomorphization` on both the impl and method.
1802        let args = trait_ref.args.extend_to(tcx, method.def_id, only_region_params);
1803        let instance = ty::Instance::expect_resolve(tcx, typing_env, method.def_id, args, DUMMY_SP);
1804
1805        let mono_item = create_fn_mono_item(tcx, instance, DUMMY_SP);
1806        if mono_item.node.is_instantiable(tcx) && tcx.should_codegen_locally(instance) {
1807            output.push(mono_item);
1808        }
1809    }
1810}
1811
1812//=-----------------------------------------------------------------------------
1813// Top-level entry point, tying it all together
1814//=-----------------------------------------------------------------------------
1815
1816#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("collect_crate_mono_items",
                                    "rustc_monomorphize::collector", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1816u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
                                    ::tracing_core::field::FieldSet::new(&[],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{ meta.fields().value_set(&[]) })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return:
                    (Vec<MonoItem<'tcx>>, UsageMap<'tcx>) = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let _prof_timer =
                tcx.prof.generic_activity("monomorphization_collector");
            let roots =
                tcx.sess.time("monomorphization_collector_root_collections",
                    || collect_roots(tcx, strategy));
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event compiler/rustc_monomorphize/src/collector.rs:1827",
                                    "rustc_monomorphize::collector", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_monomorphize/src/collector.rs"),
                                    ::tracing_core::__macro_support::Option::Some(1827u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_monomorphize::collector"),
                                    ::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};
                            let mut iter = __CALLSITE.metadata().fields().iter();
                            __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                ::tracing::__macro_support::Option::Some(&format_args!("building mono item graph, beginning at roots")
                                                        as &dyn Value))])
                        });
                } else { ; }
            };
            let state =
                SharedState {
                    visited: Lock::new(UnordSet::default()),
                    mentioned: Lock::new(UnordSet::default()),
                    usage_map: Lock::new(UsageMap::new()),
                };
            let recursion_limit = tcx.recursion_limit();
            tcx.sess.time("monomorphization_collector_graph_walk",
                ||
                    {
                        par_for_each_in(roots,
                            |root|
                                {
                                    collect_items_root(tcx, dummy_spanned(*root), &state,
                                        recursion_limit);
                                });
                    });
            let mono_items =
                tcx.with_stable_hashing_context(move |mut hcx|
                        { state.visited.into_inner().into_sorted(&mut hcx, true) });
            (mono_items, state.usage_map.into_inner())
        }
    }
}#[instrument(skip(tcx, strategy), level = "debug")]
1817pub(crate) fn collect_crate_mono_items<'tcx>(
1818    tcx: TyCtxt<'tcx>,
1819    strategy: MonoItemCollectionStrategy,
1820) -> (Vec<MonoItem<'tcx>>, UsageMap<'tcx>) {
1821    let _prof_timer = tcx.prof.generic_activity("monomorphization_collector");
1822
1823    let roots = tcx
1824        .sess
1825        .time("monomorphization_collector_root_collections", || collect_roots(tcx, strategy));
1826
1827    debug!("building mono item graph, beginning at roots");
1828
1829    let state = SharedState {
1830        visited: Lock::new(UnordSet::default()),
1831        mentioned: Lock::new(UnordSet::default()),
1832        usage_map: Lock::new(UsageMap::new()),
1833    };
1834    let recursion_limit = tcx.recursion_limit();
1835
1836    tcx.sess.time("monomorphization_collector_graph_walk", || {
1837        par_for_each_in(roots, |root| {
1838            collect_items_root(tcx, dummy_spanned(*root), &state, recursion_limit);
1839        });
1840    });
1841
1842    // The set of MonoItems was created in an inherently indeterministic order because
1843    // of parallelism. We sort it here to ensure that the output is deterministic.
1844    let mono_items = tcx.with_stable_hashing_context(move |mut hcx| {
1845        state.visited.into_inner().into_sorted(&mut hcx, true)
1846    });
1847
1848    (mono_items, state.usage_map.into_inner())
1849}
1850
1851pub(crate) fn provide(providers: &mut Providers) {
1852    providers.hooks.should_codegen_locally = should_codegen_locally;
1853    providers.queries.items_of_instance = items_of_instance;
1854}