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
208mod autodiff;
209
210use std::cell::OnceCell;
211use std::ops::ControlFlow;
212
213use rustc_data_structures::fx::FxIndexMap;
214use rustc_data_structures::sync::{MTLock, par_for_each_in};
215use rustc_data_structures::unord::{UnordMap, UnordSet};
216use rustc_hir as hir;
217use rustc_hir::attrs::InlineAttr;
218use rustc_hir::def::DefKind;
219use rustc_hir::def_id::{DefId, DefIdMap, LocalDefId};
220use rustc_hir::lang_items::LangItem;
221use rustc_hir::limit::Limit;
222use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
223use rustc_middle::mir::interpret::{AllocId, ErrorHandled, GlobalAlloc, Scalar};
224use rustc_middle::mir::mono::{
225    CollectionMode, InstantiationMode, MonoItem, NormalizationErrorInMono,
226};
227use rustc_middle::mir::visit::Visitor as MirVisitor;
228use rustc_middle::mir::{self, Body, Location, MentionedItem, traversal};
229use rustc_middle::query::TyCtxtAt;
230use rustc_middle::ty::adjustment::{CustomCoerceUnsized, PointerCoercion};
231use rustc_middle::ty::layout::ValidityRequirement;
232use rustc_middle::ty::{
233    self, GenericArgs, GenericParamDefKind, Instance, InstanceKind, Ty, TyCtxt, TypeFoldable,
234    TypeVisitable, TypeVisitableExt, TypeVisitor, VtblEntry,
235};
236use rustc_middle::util::Providers;
237use rustc_middle::{bug, span_bug};
238use rustc_session::config::{DebugInfo, EntryFnType};
239use rustc_span::source_map::{Spanned, dummy_spanned, respan};
240use rustc_span::{DUMMY_SP, Span};
241use tracing::{debug, instrument, trace};
242
243use crate::collector::autodiff::collect_autodiff_fn;
244use crate::errors::{
245    self, EncounteredErrorWhileInstantiating, EncounteredErrorWhileInstantiatingGlobalAsm,
246    NoOptimizedMir, RecursionLimit,
247};
248
249#[derive(PartialEq)]
250pub(crate) enum MonoItemCollectionStrategy {
251    Eager,
252    Lazy,
253}
254
255/// The state that is shared across the concurrent threads that are doing collection.
256struct SharedState<'tcx> {
257    /// Items that have been or are currently being recursively collected.
258    visited: MTLock<UnordSet<MonoItem<'tcx>>>,
259    /// Items that have been or are currently being recursively treated as "mentioned", i.e., their
260    /// consts are evaluated but nothing is added to the collection.
261    mentioned: MTLock<UnordSet<MonoItem<'tcx>>>,
262    /// Which items are being used where, for better errors.
263    usage_map: MTLock<UsageMap<'tcx>>,
264}
265
266pub(crate) struct UsageMap<'tcx> {
267    // Maps every mono item to the mono items used by it.
268    pub used_map: UnordMap<MonoItem<'tcx>, Vec<MonoItem<'tcx>>>,
269
270    // Maps every mono item to the mono items that use it.
271    user_map: UnordMap<MonoItem<'tcx>, Vec<MonoItem<'tcx>>>,
272}
273
274impl<'tcx> UsageMap<'tcx> {
275    fn new() -> UsageMap<'tcx> {
276        UsageMap { used_map: Default::default(), user_map: Default::default() }
277    }
278
279    fn record_used<'a>(&mut self, user_item: MonoItem<'tcx>, used_items: &'a MonoItems<'tcx>)
280    where
281        'tcx: 'a,
282    {
283        for used_item in used_items.items() {
284            self.user_map.entry(used_item).or_default().push(user_item);
285        }
286
287        assert!(self.used_map.insert(user_item, used_items.items().collect()).is_none());
288    }
289
290    pub(crate) fn get_user_items(&self, item: MonoItem<'tcx>) -> &[MonoItem<'tcx>] {
291        self.user_map.get(&item).map(|items| items.as_slice()).unwrap_or(&[])
292    }
293
294    /// Internally iterate over all inlined items used by `item`.
295    pub(crate) fn for_each_inlined_used_item<F>(
296        &self,
297        tcx: TyCtxt<'tcx>,
298        item: MonoItem<'tcx>,
299        mut f: F,
300    ) where
301        F: FnMut(MonoItem<'tcx>),
302    {
303        let used_items = self.used_map.get(&item).unwrap();
304        for used_item in used_items.iter() {
305            let is_inlined = used_item.instantiation_mode(tcx) == InstantiationMode::LocalCopy;
306            if is_inlined {
307                f(*used_item);
308            }
309        }
310    }
311}
312
313struct MonoItems<'tcx> {
314    // We want a set of MonoItem + Span where trying to re-insert a MonoItem with a different Span
315    // is ignored. Map does that, but it looks odd.
316    items: FxIndexMap<MonoItem<'tcx>, Span>,
317}
318
319impl<'tcx> MonoItems<'tcx> {
320    fn new() -> Self {
321        Self { items: FxIndexMap::default() }
322    }
323
324    fn is_empty(&self) -> bool {
325        self.items.is_empty()
326    }
327
328    fn push(&mut self, item: Spanned<MonoItem<'tcx>>) {
329        // Insert only if the entry does not exist. A normal insert would stomp the first span that
330        // got inserted.
331        self.items.entry(item.node).or_insert(item.span);
332    }
333
334    fn items(&self) -> impl Iterator<Item = MonoItem<'tcx>> {
335        self.items.keys().cloned()
336    }
337}
338
339impl<'tcx> IntoIterator for MonoItems<'tcx> {
340    type Item = Spanned<MonoItem<'tcx>>;
341    type IntoIter = impl Iterator<Item = Spanned<MonoItem<'tcx>>>;
342
343    fn into_iter(self) -> Self::IntoIter {
344        self.items.into_iter().map(|(item, span)| respan(span, item))
345    }
346}
347
348impl<'tcx> Extend<Spanned<MonoItem<'tcx>>> for MonoItems<'tcx> {
349    fn extend<I>(&mut self, iter: I)
350    where
351        I: IntoIterator<Item = Spanned<MonoItem<'tcx>>>,
352    {
353        for item in iter {
354            self.push(item)
355        }
356    }
357}
358
359fn collect_items_root<'tcx>(
360    tcx: TyCtxt<'tcx>,
361    starting_item: Spanned<MonoItem<'tcx>>,
362    state: &SharedState<'tcx>,
363    recursion_limit: Limit,
364) {
365    if !state.visited.lock_mut().insert(starting_item.node) {
366        // We've been here already, no need to search again.
367        return;
368    }
369    let mut recursion_depths = DefIdMap::default();
370    collect_items_rec(
371        tcx,
372        starting_item,
373        state,
374        &mut recursion_depths,
375        recursion_limit,
376        CollectionMode::UsedItems,
377    );
378}
379
380/// Collect all monomorphized items reachable from `starting_point`, and emit a note diagnostic if a
381/// post-monomorphization error is encountered during a collection step.
382///
383/// `mode` determined whether we are scanning for [used items][CollectionMode::UsedItems]
384/// or [mentioned items][CollectionMode::MentionedItems].
385#[instrument(skip(tcx, state, recursion_depths, recursion_limit), level = "debug")]
386fn collect_items_rec<'tcx>(
387    tcx: TyCtxt<'tcx>,
388    starting_item: Spanned<MonoItem<'tcx>>,
389    state: &SharedState<'tcx>,
390    recursion_depths: &mut DefIdMap<usize>,
391    recursion_limit: Limit,
392    mode: CollectionMode,
393) {
394    let mut used_items = MonoItems::new();
395    let mut mentioned_items = MonoItems::new();
396    let recursion_depth_reset;
397
398    // Post-monomorphization errors MVP
399    //
400    // We can encounter errors while monomorphizing an item, but we don't have a good way of
401    // showing a complete stack of spans ultimately leading to collecting the erroneous one yet.
402    // (It's also currently unclear exactly which diagnostics and information would be interesting
403    // to report in such cases)
404    //
405    // This leads to suboptimal error reporting: a post-monomorphization error (PME) will be
406    // shown with just a spanned piece of code causing the error, without information on where
407    // it was called from. This is especially obscure if the erroneous mono item is in a
408    // dependency. See for example issue #85155, where, before minimization, a PME happened two
409    // crates downstream from libcore's stdarch, without a way to know which dependency was the
410    // cause.
411    //
412    // If such an error occurs in the current crate, its span will be enough to locate the
413    // source. If the cause is in another crate, the goal here is to quickly locate which mono
414    // item in the current crate is ultimately responsible for causing the error.
415    //
416    // To give at least _some_ context to the user: while collecting mono items, we check the
417    // error count. If it has changed, a PME occurred, and we trigger some diagnostics about the
418    // current step of mono items collection.
419    //
420    // FIXME: don't rely on global state, instead bubble up errors. Note: this is very hard to do.
421    let error_count = tcx.dcx().err_count();
422
423    // In `mentioned_items` we collect items that were mentioned in this MIR but possibly do not
424    // need to be monomorphized. This is done to ensure that optimizing away function calls does not
425    // hide const-eval errors that those calls would otherwise have triggered.
426    match starting_item.node {
427        MonoItem::Static(def_id) => {
428            recursion_depth_reset = None;
429
430            // Statics always get evaluated (which is possible because they can't be generic), so for
431            // `MentionedItems` collection there's nothing to do here.
432            if mode == CollectionMode::UsedItems {
433                let instance = Instance::mono(tcx, def_id);
434
435                // Sanity check whether this ended up being collected accidentally
436                debug_assert!(tcx.should_codegen_locally(instance));
437
438                let DefKind::Static { nested, .. } = tcx.def_kind(def_id) else { bug!() };
439                // Nested statics have no type.
440                if !nested {
441                    let ty = instance.ty(tcx, ty::TypingEnv::fully_monomorphized());
442                    visit_drop_use(tcx, ty, true, starting_item.span, &mut used_items);
443                }
444
445                if let Ok(alloc) = tcx.eval_static_initializer(def_id) {
446                    for &prov in alloc.inner().provenance().ptrs().values() {
447                        collect_alloc(tcx, prov.alloc_id(), &mut used_items);
448                    }
449                }
450
451                if tcx.needs_thread_local_shim(def_id) {
452                    used_items.push(respan(
453                        starting_item.span,
454                        MonoItem::Fn(Instance {
455                            def: InstanceKind::ThreadLocalShim(def_id),
456                            args: GenericArgs::empty(),
457                        }),
458                    ));
459                }
460            }
461
462            // mentioned_items stays empty since there's no codegen for statics. statics don't get
463            // optimized, and if they did then the const-eval interpreter would have to worry about
464            // mentioned_items.
465        }
466        MonoItem::Fn(instance) => {
467            // Sanity check whether this ended up being collected accidentally
468            debug_assert!(tcx.should_codegen_locally(instance));
469
470            // Keep track of the monomorphization recursion depth
471            recursion_depth_reset = Some(check_recursion_limit(
472                tcx,
473                instance,
474                starting_item.span,
475                recursion_depths,
476                recursion_limit,
477            ));
478
479            rustc_data_structures::stack::ensure_sufficient_stack(|| {
480                let Ok((used, mentioned)) = tcx.items_of_instance((instance, mode)) else {
481                    // Normalization errors here are usually due to trait solving overflow.
482                    // FIXME: I assume that there are few type errors at post-analysis stage, but not
483                    // entirely sure.
484                    // We have to emit the error outside of `items_of_instance` to access the
485                    // span of the `starting_item`.
486                    let def_id = instance.def_id();
487                    let def_span = tcx.def_span(def_id);
488                    let def_path_str = tcx.def_path_str(def_id);
489                    tcx.dcx().emit_fatal(RecursionLimit {
490                        span: starting_item.span,
491                        instance,
492                        def_span,
493                        def_path_str,
494                    });
495                };
496                used_items.extend(used.into_iter().copied());
497                mentioned_items.extend(mentioned.into_iter().copied());
498            });
499        }
500        MonoItem::GlobalAsm(item_id) => {
501            assert!(
502                mode == CollectionMode::UsedItems,
503                "should never encounter global_asm when collecting mentioned items"
504            );
505            recursion_depth_reset = None;
506
507            let item = tcx.hir_item(item_id);
508            if let hir::ItemKind::GlobalAsm { asm, .. } = item.kind {
509                for (op, op_sp) in asm.operands {
510                    match *op {
511                        hir::InlineAsmOperand::Const { .. } => {
512                            // Only constants which resolve to a plain integer
513                            // are supported. Therefore the value should not
514                            // depend on any other items.
515                        }
516                        hir::InlineAsmOperand::SymFn { expr } => {
517                            let fn_ty = tcx.typeck(item_id.owner_id).expr_ty(expr);
518                            visit_fn_use(tcx, fn_ty, false, *op_sp, &mut used_items);
519                        }
520                        hir::InlineAsmOperand::SymStatic { path: _, def_id } => {
521                            let instance = Instance::mono(tcx, def_id);
522                            if tcx.should_codegen_locally(instance) {
523                                trace!("collecting static {:?}", def_id);
524                                used_items.push(dummy_spanned(MonoItem::Static(def_id)));
525                            }
526                        }
527                        hir::InlineAsmOperand::In { .. }
528                        | hir::InlineAsmOperand::Out { .. }
529                        | hir::InlineAsmOperand::InOut { .. }
530                        | hir::InlineAsmOperand::SplitInOut { .. }
531                        | hir::InlineAsmOperand::Label { .. } => {
532                            span_bug!(*op_sp, "invalid operand type for global_asm!")
533                        }
534                    }
535                }
536            } else {
537                span_bug!(item.span, "Mismatch between hir::Item type and MonoItem type")
538            }
539
540            // mention_items stays empty as nothing gets optimized here.
541        }
542    };
543
544    // Check for PMEs and emit a diagnostic if one happened. To try to show relevant edges of the
545    // mono item graph.
546    if tcx.dcx().err_count() > error_count
547        && starting_item.node.is_generic_fn()
548        && starting_item.node.is_user_defined()
549    {
550        match starting_item.node {
551            MonoItem::Fn(instance) => tcx.dcx().emit_note(EncounteredErrorWhileInstantiating {
552                span: starting_item.span,
553                kind: "fn",
554                instance,
555            }),
556            MonoItem::Static(def_id) => tcx.dcx().emit_note(EncounteredErrorWhileInstantiating {
557                span: starting_item.span,
558                kind: "static",
559                instance: Instance::new_raw(def_id, GenericArgs::empty()),
560            }),
561            MonoItem::GlobalAsm(_) => {
562                tcx.dcx().emit_note(EncounteredErrorWhileInstantiatingGlobalAsm {
563                    span: starting_item.span,
564                })
565            }
566        }
567    }
568    // Only updating `usage_map` for used items as otherwise we may be inserting the same item
569    // multiple times (if it is first 'mentioned' and then later actually used), and the usage map
570    // logic does not like that.
571    // This is part of the output of collection and hence only relevant for "used" items.
572    // ("Mentioned" items are only considered internally during collection.)
573    if mode == CollectionMode::UsedItems {
574        state.usage_map.lock_mut().record_used(starting_item.node, &used_items);
575    }
576
577    {
578        let mut visited = OnceCell::default();
579        if mode == CollectionMode::UsedItems {
580            used_items
581                .items
582                .retain(|k, _| visited.get_mut_or_init(|| state.visited.lock_mut()).insert(*k));
583        }
584
585        let mut mentioned = OnceCell::default();
586        mentioned_items.items.retain(|k, _| {
587            !visited.get_or_init(|| state.visited.lock()).contains(k)
588                && mentioned.get_mut_or_init(|| state.mentioned.lock_mut()).insert(*k)
589        });
590    }
591    if mode == CollectionMode::MentionedItems {
592        assert!(used_items.is_empty(), "'mentioned' collection should never encounter used items");
593    } else {
594        for used_item in used_items {
595            collect_items_rec(
596                tcx,
597                used_item,
598                state,
599                recursion_depths,
600                recursion_limit,
601                CollectionMode::UsedItems,
602            );
603        }
604    }
605
606    // Walk over mentioned items *after* used items, so that if an item is both mentioned and used then
607    // the loop above has fully collected it, so this loop will skip it.
608    for mentioned_item in mentioned_items {
609        collect_items_rec(
610            tcx,
611            mentioned_item,
612            state,
613            recursion_depths,
614            recursion_limit,
615            CollectionMode::MentionedItems,
616        );
617    }
618
619    if let Some((def_id, depth)) = recursion_depth_reset {
620        recursion_depths.insert(def_id, depth);
621    }
622}
623
624// Check whether we can normalize every type in the instantiated MIR body.
625fn check_normalization_error<'tcx>(
626    tcx: TyCtxt<'tcx>,
627    instance: Instance<'tcx>,
628    body: &Body<'tcx>,
629) -> Result<(), NormalizationErrorInMono> {
630    struct NormalizationChecker<'tcx> {
631        tcx: TyCtxt<'tcx>,
632        instance: Instance<'tcx>,
633    }
634    impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for NormalizationChecker<'tcx> {
635        type Result = ControlFlow<()>;
636
637        fn visit_ty(&mut self, t: Ty<'tcx>) -> Self::Result {
638            match self.instance.try_instantiate_mir_and_normalize_erasing_regions(
639                self.tcx,
640                ty::TypingEnv::fully_monomorphized(),
641                ty::EarlyBinder::bind(t),
642            ) {
643                Ok(_) => ControlFlow::Continue(()),
644                Err(_) => ControlFlow::Break(()),
645            }
646        }
647    }
648
649    let mut checker = NormalizationChecker { tcx, instance };
650    if body.visit_with(&mut checker).is_break() { Err(NormalizationErrorInMono) } else { Ok(()) }
651}
652
653fn check_recursion_limit<'tcx>(
654    tcx: TyCtxt<'tcx>,
655    instance: Instance<'tcx>,
656    span: Span,
657    recursion_depths: &mut DefIdMap<usize>,
658    recursion_limit: Limit,
659) -> (DefId, usize) {
660    let def_id = instance.def_id();
661    let recursion_depth = recursion_depths.get(&def_id).cloned().unwrap_or(0);
662    debug!(" => recursion depth={}", recursion_depth);
663
664    let adjusted_recursion_depth = if tcx.is_lang_item(def_id, LangItem::DropInPlace) {
665        // HACK: drop_in_place creates tight monomorphization loops. Give
666        // it more margin.
667        recursion_depth / 4
668    } else {
669        recursion_depth
670    };
671
672    // Code that needs to instantiate the same function recursively
673    // more than the recursion limit is assumed to be causing an
674    // infinite expansion.
675    if !recursion_limit.value_within_limit(adjusted_recursion_depth) {
676        let def_span = tcx.def_span(def_id);
677        let def_path_str = tcx.def_path_str(def_id);
678        tcx.dcx().emit_fatal(RecursionLimit { span, instance, def_span, def_path_str });
679    }
680
681    recursion_depths.insert(def_id, recursion_depth + 1);
682
683    (def_id, recursion_depth)
684}
685
686struct MirUsedCollector<'a, 'tcx> {
687    tcx: TyCtxt<'tcx>,
688    body: &'a mir::Body<'tcx>,
689    used_items: &'a mut MonoItems<'tcx>,
690    /// See the comment in `collect_items_of_instance` for the purpose of this set.
691    /// Note that this contains *not-monomorphized* items!
692    used_mentioned_items: &'a mut UnordSet<MentionedItem<'tcx>>,
693    instance: Instance<'tcx>,
694}
695
696impl<'a, 'tcx> MirUsedCollector<'a, 'tcx> {
697    fn monomorphize<T>(&self, value: T) -> T
698    where
699        T: TypeFoldable<TyCtxt<'tcx>>,
700    {
701        trace!("monomorphize: self.instance={:?}", self.instance);
702        self.instance.instantiate_mir_and_normalize_erasing_regions(
703            self.tcx,
704            ty::TypingEnv::fully_monomorphized(),
705            ty::EarlyBinder::bind(value),
706        )
707    }
708
709    /// Evaluates a *not yet monomorphized* constant.
710    fn eval_constant(&mut self, constant: &mir::ConstOperand<'tcx>) -> Option<mir::ConstValue> {
711        let const_ = self.monomorphize(constant.const_);
712        // Evaluate the constant. This makes const eval failure a collection-time error (rather than
713        // a codegen-time error). rustc stops after collection if there was an error, so this
714        // ensures codegen never has to worry about failing consts.
715        // (codegen relies on this and ICEs will happen if this is violated.)
716        match const_.eval(self.tcx, ty::TypingEnv::fully_monomorphized(), constant.span) {
717            Ok(v) => Some(v),
718            Err(ErrorHandled::TooGeneric(..)) => span_bug!(
719                constant.span,
720                "collection encountered polymorphic constant: {:?}",
721                const_
722            ),
723            Err(err @ ErrorHandled::Reported(..)) => {
724                err.emit_note(self.tcx);
725                return None;
726            }
727        }
728    }
729}
730
731impl<'a, 'tcx> MirVisitor<'tcx> for MirUsedCollector<'a, 'tcx> {
732    fn visit_rvalue(&mut self, rvalue: &mir::Rvalue<'tcx>, location: Location) {
733        debug!("visiting rvalue {:?}", *rvalue);
734
735        let span = self.body.source_info(location).span;
736
737        match *rvalue {
738            // When doing an cast from a regular pointer to a wide pointer, we
739            // have to instantiate all methods of the trait being cast to, so we
740            // can build the appropriate vtable.
741            mir::Rvalue::Cast(
742                mir::CastKind::PointerCoercion(PointerCoercion::Unsize, _),
743                ref operand,
744                target_ty,
745            ) => {
746                let source_ty = operand.ty(self.body, self.tcx);
747                // *Before* monomorphizing, record that we already handled this mention.
748                self.used_mentioned_items
749                    .insert(MentionedItem::UnsizeCast { source_ty, target_ty });
750                let target_ty = self.monomorphize(target_ty);
751                let source_ty = self.monomorphize(source_ty);
752                let (source_ty, target_ty) =
753                    find_tails_for_unsizing(self.tcx.at(span), source_ty, target_ty);
754                // This could also be a different Unsize instruction, like
755                // from a fixed sized array to a slice. But we are only
756                // interested in things that produce a vtable.
757                if target_ty.is_trait() && !source_ty.is_trait() {
758                    create_mono_items_for_vtable_methods(
759                        self.tcx,
760                        target_ty,
761                        source_ty,
762                        span,
763                        self.used_items,
764                    );
765                }
766            }
767            mir::Rvalue::Cast(
768                mir::CastKind::PointerCoercion(PointerCoercion::ReifyFnPointer, _),
769                ref operand,
770                _,
771            ) => {
772                let fn_ty = operand.ty(self.body, self.tcx);
773                // *Before* monomorphizing, record that we already handled this mention.
774                self.used_mentioned_items.insert(MentionedItem::Fn(fn_ty));
775                let fn_ty = self.monomorphize(fn_ty);
776                visit_fn_use(self.tcx, fn_ty, false, span, self.used_items);
777            }
778            mir::Rvalue::Cast(
779                mir::CastKind::PointerCoercion(PointerCoercion::ClosureFnPointer(_), _),
780                ref operand,
781                _,
782            ) => {
783                let source_ty = operand.ty(self.body, self.tcx);
784                // *Before* monomorphizing, record that we already handled this mention.
785                self.used_mentioned_items.insert(MentionedItem::Closure(source_ty));
786                let source_ty = self.monomorphize(source_ty);
787                if let ty::Closure(def_id, args) = *source_ty.kind() {
788                    let instance =
789                        Instance::resolve_closure(self.tcx, def_id, args, ty::ClosureKind::FnOnce);
790                    if self.tcx.should_codegen_locally(instance) {
791                        self.used_items.push(create_fn_mono_item(self.tcx, instance, span));
792                    }
793                } else {
794                    bug!()
795                }
796            }
797            mir::Rvalue::ThreadLocalRef(def_id) => {
798                assert!(self.tcx.is_thread_local_static(def_id));
799                let instance = Instance::mono(self.tcx, def_id);
800                if self.tcx.should_codegen_locally(instance) {
801                    trace!("collecting thread-local static {:?}", def_id);
802                    self.used_items.push(respan(span, MonoItem::Static(def_id)));
803                }
804            }
805            _ => { /* not interesting */ }
806        }
807
808        self.super_rvalue(rvalue, location);
809    }
810
811    /// This does not walk the MIR of the constant as that is not needed for codegen, all we need is
812    /// to ensure that the constant evaluates successfully and walk the result.
813    #[instrument(skip(self), level = "debug")]
814    fn visit_const_operand(&mut self, constant: &mir::ConstOperand<'tcx>, _location: Location) {
815        // No `super_constant` as we don't care about `visit_ty`/`visit_ty_const`.
816        let Some(val) = self.eval_constant(constant) else { return };
817        collect_const_value(self.tcx, val, self.used_items);
818    }
819
820    fn visit_terminator(&mut self, terminator: &mir::Terminator<'tcx>, location: Location) {
821        debug!("visiting terminator {:?} @ {:?}", terminator, location);
822        let source = self.body.source_info(location).span;
823
824        let tcx = self.tcx;
825        let push_mono_lang_item = |this: &mut Self, lang_item: LangItem| {
826            let instance = Instance::mono(tcx, tcx.require_lang_item(lang_item, source));
827            if tcx.should_codegen_locally(instance) {
828                this.used_items.push(create_fn_mono_item(tcx, instance, source));
829            }
830        };
831
832        match terminator.kind {
833            mir::TerminatorKind::Call { ref func, .. }
834            | mir::TerminatorKind::TailCall { ref func, .. } => {
835                let callee_ty = func.ty(self.body, tcx);
836                // *Before* monomorphizing, record that we already handled this mention.
837                self.used_mentioned_items.insert(MentionedItem::Fn(callee_ty));
838                let callee_ty = self.monomorphize(callee_ty);
839
840                // HACK(explicit_tail_calls): collect tail calls to `#[track_caller]` functions as indirect,
841                // because we later call them as such, to prevent issues with ABI incompatibility.
842                // Ideally we'd replace such tail calls with normal call + return, but this requires
843                // post-mono MIR optimizations, which we don't yet have.
844                let force_indirect_call =
845                    if matches!(terminator.kind, mir::TerminatorKind::TailCall { .. })
846                        && let &ty::FnDef(def_id, args) = callee_ty.kind()
847                        && let instance = ty::Instance::expect_resolve(
848                            self.tcx,
849                            ty::TypingEnv::fully_monomorphized(),
850                            def_id,
851                            args,
852                            source,
853                        )
854                        && instance.def.requires_caller_location(self.tcx)
855                    {
856                        true
857                    } else {
858                        false
859                    };
860
861                visit_fn_use(
862                    self.tcx,
863                    callee_ty,
864                    !force_indirect_call,
865                    source,
866                    &mut self.used_items,
867                )
868            }
869            mir::TerminatorKind::Drop { ref place, .. } => {
870                let ty = place.ty(self.body, self.tcx).ty;
871                // *Before* monomorphizing, record that we already handled this mention.
872                self.used_mentioned_items.insert(MentionedItem::Drop(ty));
873                let ty = self.monomorphize(ty);
874                visit_drop_use(self.tcx, ty, true, source, self.used_items);
875            }
876            mir::TerminatorKind::InlineAsm { ref operands, .. } => {
877                for op in operands {
878                    match *op {
879                        mir::InlineAsmOperand::SymFn { ref value } => {
880                            let fn_ty = value.const_.ty();
881                            // *Before* monomorphizing, record that we already handled this mention.
882                            self.used_mentioned_items.insert(MentionedItem::Fn(fn_ty));
883                            let fn_ty = self.monomorphize(fn_ty);
884                            visit_fn_use(self.tcx, fn_ty, false, source, self.used_items);
885                        }
886                        mir::InlineAsmOperand::SymStatic { def_id } => {
887                            let instance = Instance::mono(self.tcx, def_id);
888                            if self.tcx.should_codegen_locally(instance) {
889                                trace!("collecting asm sym static {:?}", def_id);
890                                self.used_items.push(respan(source, MonoItem::Static(def_id)));
891                            }
892                        }
893                        _ => {}
894                    }
895                }
896            }
897            mir::TerminatorKind::Assert { ref msg, .. } => match &**msg {
898                mir::AssertKind::BoundsCheck { .. } => {
899                    push_mono_lang_item(self, LangItem::PanicBoundsCheck);
900                }
901                mir::AssertKind::MisalignedPointerDereference { .. } => {
902                    push_mono_lang_item(self, LangItem::PanicMisalignedPointerDereference);
903                }
904                mir::AssertKind::NullPointerDereference => {
905                    push_mono_lang_item(self, LangItem::PanicNullPointerDereference);
906                }
907                mir::AssertKind::InvalidEnumConstruction(_) => {
908                    push_mono_lang_item(self, LangItem::PanicInvalidEnumConstruction);
909                }
910                _ => {
911                    push_mono_lang_item(self, msg.panic_function());
912                }
913            },
914            mir::TerminatorKind::UnwindTerminate(reason) => {
915                push_mono_lang_item(self, reason.lang_item());
916            }
917            mir::TerminatorKind::Goto { .. }
918            | mir::TerminatorKind::SwitchInt { .. }
919            | mir::TerminatorKind::UnwindResume
920            | mir::TerminatorKind::Return
921            | mir::TerminatorKind::Unreachable => {}
922            mir::TerminatorKind::CoroutineDrop
923            | mir::TerminatorKind::Yield { .. }
924            | mir::TerminatorKind::FalseEdge { .. }
925            | mir::TerminatorKind::FalseUnwind { .. } => bug!(),
926        }
927
928        if let Some(mir::UnwindAction::Terminate(reason)) = terminator.unwind() {
929            push_mono_lang_item(self, reason.lang_item());
930        }
931
932        self.super_terminator(terminator, location);
933    }
934}
935
936fn visit_drop_use<'tcx>(
937    tcx: TyCtxt<'tcx>,
938    ty: Ty<'tcx>,
939    is_direct_call: bool,
940    source: Span,
941    output: &mut MonoItems<'tcx>,
942) {
943    let instance = Instance::resolve_drop_in_place(tcx, ty);
944    visit_instance_use(tcx, instance, is_direct_call, source, output);
945}
946
947/// For every call of this function in the visitor, make sure there is a matching call in the
948/// `mentioned_items` pass!
949fn visit_fn_use<'tcx>(
950    tcx: TyCtxt<'tcx>,
951    ty: Ty<'tcx>,
952    is_direct_call: bool,
953    source: Span,
954    output: &mut MonoItems<'tcx>,
955) {
956    if let ty::FnDef(def_id, args) = *ty.kind() {
957        let instance = if is_direct_call {
958            ty::Instance::expect_resolve(
959                tcx,
960                ty::TypingEnv::fully_monomorphized(),
961                def_id,
962                args,
963                source,
964            )
965        } else {
966            match ty::Instance::resolve_for_fn_ptr(
967                tcx,
968                ty::TypingEnv::fully_monomorphized(),
969                def_id,
970                args,
971            ) {
972                Some(instance) => instance,
973                _ => bug!("failed to resolve instance for {ty}"),
974            }
975        };
976        visit_instance_use(tcx, instance, is_direct_call, source, output);
977    }
978}
979
980fn visit_instance_use<'tcx>(
981    tcx: TyCtxt<'tcx>,
982    instance: ty::Instance<'tcx>,
983    is_direct_call: bool,
984    source: Span,
985    output: &mut MonoItems<'tcx>,
986) {
987    debug!("visit_item_use({:?}, is_direct_call={:?})", instance, is_direct_call);
988    if !tcx.should_codegen_locally(instance) {
989        return;
990    }
991    if let Some(intrinsic) = tcx.intrinsic(instance.def_id()) {
992        collect_autodiff_fn(tcx, instance, intrinsic, output);
993
994        if let Some(_requirement) = ValidityRequirement::from_intrinsic(intrinsic.name) {
995            // The intrinsics assert_inhabited, assert_zero_valid, and assert_mem_uninitialized_valid will
996            // be lowered in codegen to nothing or a call to panic_nounwind. So if we encounter any
997            // of those intrinsics, we need to include a mono item for panic_nounwind, else we may try to
998            // codegen a call to that function without generating code for the function itself.
999            let def_id = tcx.require_lang_item(LangItem::PanicNounwind, source);
1000            let panic_instance = Instance::mono(tcx, def_id);
1001            if tcx.should_codegen_locally(panic_instance) {
1002                output.push(create_fn_mono_item(tcx, panic_instance, source));
1003            }
1004        } else if !intrinsic.must_be_overridden {
1005            // Codegen the fallback body of intrinsics with fallback bodies.
1006            // We explicitly skip this otherwise to ensure we get a linker error
1007            // if anyone tries to call this intrinsic and the codegen backend did not
1008            // override the implementation.
1009            let instance = ty::Instance::new_raw(instance.def_id(), instance.args);
1010            if tcx.should_codegen_locally(instance) {
1011                output.push(create_fn_mono_item(tcx, instance, source));
1012            }
1013        }
1014    }
1015
1016    match instance.def {
1017        ty::InstanceKind::Virtual(..) | ty::InstanceKind::Intrinsic(_) => {
1018            if !is_direct_call {
1019                bug!("{:?} being reified", instance);
1020            }
1021        }
1022        ty::InstanceKind::ThreadLocalShim(..) => {
1023            bug!("{:?} being reified", instance);
1024        }
1025        ty::InstanceKind::DropGlue(_, None) => {
1026            // Don't need to emit noop drop glue if we are calling directly.
1027            //
1028            // Note that we also optimize away the call to visit_instance_use in vtable construction
1029            // (see create_mono_items_for_vtable_methods).
1030            if !is_direct_call {
1031                output.push(create_fn_mono_item(tcx, instance, source));
1032            }
1033        }
1034        ty::InstanceKind::DropGlue(_, Some(_))
1035        | ty::InstanceKind::FutureDropPollShim(..)
1036        | ty::InstanceKind::AsyncDropGlue(_, _)
1037        | ty::InstanceKind::AsyncDropGlueCtorShim(_, _)
1038        | ty::InstanceKind::VTableShim(..)
1039        | ty::InstanceKind::ReifyShim(..)
1040        | ty::InstanceKind::ClosureOnceShim { .. }
1041        | ty::InstanceKind::ConstructCoroutineInClosureShim { .. }
1042        | ty::InstanceKind::Item(..)
1043        | ty::InstanceKind::FnPtrShim(..)
1044        | ty::InstanceKind::CloneShim(..)
1045        | ty::InstanceKind::FnPtrAddrShim(..) => {
1046            output.push(create_fn_mono_item(tcx, instance, source));
1047        }
1048    }
1049}
1050
1051/// Returns `true` if we should codegen an instance in the local crate, or returns `false` if we
1052/// can just link to the upstream crate and therefore don't need a mono item.
1053fn should_codegen_locally<'tcx>(tcx: TyCtxt<'tcx>, instance: Instance<'tcx>) -> bool {
1054    let Some(def_id) = instance.def.def_id_if_not_guaranteed_local_codegen() else {
1055        return true;
1056    };
1057
1058    if tcx.is_foreign_item(def_id) {
1059        // Foreign items are always linked against, there's no way of instantiating them.
1060        return false;
1061    }
1062
1063    if tcx.def_kind(def_id).has_codegen_attrs()
1064        && matches!(tcx.codegen_fn_attrs(def_id).inline, InlineAttr::Force { .. })
1065    {
1066        // `#[rustc_force_inline]` items should never be codegened. This should be caught by
1067        // the MIR validator.
1068        tcx.dcx().delayed_bug("attempt to codegen `#[rustc_force_inline]` item");
1069    }
1070
1071    if def_id.is_local() {
1072        // Local items cannot be referred to locally without monomorphizing them locally.
1073        return true;
1074    }
1075
1076    if tcx.is_reachable_non_generic(def_id) || instance.upstream_monomorphization(tcx).is_some() {
1077        // We can link to the item in question, no instance needed in this crate.
1078        return false;
1079    }
1080
1081    if let DefKind::Static { .. } = tcx.def_kind(def_id) {
1082        // We cannot monomorphize statics from upstream crates.
1083        return false;
1084    }
1085
1086    if !tcx.is_mir_available(def_id) {
1087        tcx.dcx().emit_fatal(NoOptimizedMir {
1088            span: tcx.def_span(def_id),
1089            crate_name: tcx.crate_name(def_id.krate),
1090            instance: instance.to_string(),
1091        });
1092    }
1093
1094    true
1095}
1096
1097/// For a given pair of source and target type that occur in an unsizing coercion,
1098/// this function finds the pair of types that determines the vtable linking
1099/// them.
1100///
1101/// For example, the source type might be `&SomeStruct` and the target type
1102/// might be `&dyn SomeTrait` in a cast like:
1103///
1104/// ```rust,ignore (not real code)
1105/// let src: &SomeStruct = ...;
1106/// let target = src as &dyn SomeTrait;
1107/// ```
1108///
1109/// Then the output of this function would be (SomeStruct, SomeTrait) since for
1110/// constructing the `target` wide-pointer we need the vtable for that pair.
1111///
1112/// Things can get more complicated though because there's also the case where
1113/// the unsized type occurs as a field:
1114///
1115/// ```rust
1116/// struct ComplexStruct<T: ?Sized> {
1117///    a: u32,
1118///    b: f64,
1119///    c: T
1120/// }
1121/// ```
1122///
1123/// In this case, if `T` is sized, `&ComplexStruct<T>` is a thin pointer. If `T`
1124/// is unsized, `&SomeStruct` is a wide pointer, and the vtable it points to is
1125/// for the pair of `T` (which is a trait) and the concrete type that `T` was
1126/// originally coerced from:
1127///
1128/// ```rust,ignore (not real code)
1129/// let src: &ComplexStruct<SomeStruct> = ...;
1130/// let target = src as &ComplexStruct<dyn SomeTrait>;
1131/// ```
1132///
1133/// Again, we want this `find_vtable_types_for_unsizing()` to provide the pair
1134/// `(SomeStruct, SomeTrait)`.
1135///
1136/// Finally, there is also the case of custom unsizing coercions, e.g., for
1137/// smart pointers such as `Rc` and `Arc`.
1138fn find_tails_for_unsizing<'tcx>(
1139    tcx: TyCtxtAt<'tcx>,
1140    source_ty: Ty<'tcx>,
1141    target_ty: Ty<'tcx>,
1142) -> (Ty<'tcx>, Ty<'tcx>) {
1143    let typing_env = ty::TypingEnv::fully_monomorphized();
1144    debug_assert!(!source_ty.has_param(), "{source_ty} should be fully monomorphic");
1145    debug_assert!(!target_ty.has_param(), "{target_ty} should be fully monomorphic");
1146
1147    match (source_ty.kind(), target_ty.kind()) {
1148        (&ty::Pat(source, _), &ty::Pat(target, _)) => find_tails_for_unsizing(tcx, source, target),
1149        (
1150            &ty::Ref(_, source_pointee, _),
1151            &ty::Ref(_, target_pointee, _) | &ty::RawPtr(target_pointee, _),
1152        )
1153        | (&ty::RawPtr(source_pointee, _), &ty::RawPtr(target_pointee, _)) => {
1154            tcx.struct_lockstep_tails_for_codegen(source_pointee, target_pointee, typing_env)
1155        }
1156
1157        // `Box<T>` could go through the ADT code below, b/c it'll unpeel to `Unique<T>`,
1158        // and eventually bottom out in a raw ref, but we can micro-optimize it here.
1159        (_, _)
1160            if let Some(source_boxed) = source_ty.boxed_ty()
1161                && let Some(target_boxed) = target_ty.boxed_ty() =>
1162        {
1163            tcx.struct_lockstep_tails_for_codegen(source_boxed, target_boxed, typing_env)
1164        }
1165
1166        (&ty::Adt(source_adt_def, source_args), &ty::Adt(target_adt_def, target_args)) => {
1167            assert_eq!(source_adt_def, target_adt_def);
1168            let CustomCoerceUnsized::Struct(coerce_index) =
1169                match crate::custom_coerce_unsize_info(tcx, source_ty, target_ty) {
1170                    Ok(ccu) => ccu,
1171                    Err(e) => {
1172                        let e = Ty::new_error(tcx.tcx, e);
1173                        return (e, e);
1174                    }
1175                };
1176            let coerce_field = &source_adt_def.non_enum_variant().fields[coerce_index];
1177            // We're getting a possibly unnormalized type, so normalize it.
1178            let source_field =
1179                tcx.normalize_erasing_regions(typing_env, coerce_field.ty(*tcx, source_args));
1180            let target_field =
1181                tcx.normalize_erasing_regions(typing_env, coerce_field.ty(*tcx, target_args));
1182            find_tails_for_unsizing(tcx, source_field, target_field)
1183        }
1184
1185        _ => bug!(
1186            "find_vtable_types_for_unsizing: invalid coercion {:?} -> {:?}",
1187            source_ty,
1188            target_ty
1189        ),
1190    }
1191}
1192
1193#[instrument(skip(tcx), level = "debug", ret)]
1194fn create_fn_mono_item<'tcx>(
1195    tcx: TyCtxt<'tcx>,
1196    instance: Instance<'tcx>,
1197    source: Span,
1198) -> Spanned<MonoItem<'tcx>> {
1199    let def_id = instance.def_id();
1200    if tcx.sess.opts.unstable_opts.profile_closures
1201        && def_id.is_local()
1202        && tcx.is_closure_like(def_id)
1203    {
1204        crate::util::dump_closure_profile(tcx, instance);
1205    }
1206
1207    respan(source, MonoItem::Fn(instance))
1208}
1209
1210/// Creates a `MonoItem` for each method that is referenced by the vtable for
1211/// the given trait/impl pair.
1212fn create_mono_items_for_vtable_methods<'tcx>(
1213    tcx: TyCtxt<'tcx>,
1214    trait_ty: Ty<'tcx>,
1215    impl_ty: Ty<'tcx>,
1216    source: Span,
1217    output: &mut MonoItems<'tcx>,
1218) {
1219    assert!(!trait_ty.has_escaping_bound_vars() && !impl_ty.has_escaping_bound_vars());
1220
1221    let ty::Dynamic(trait_ty, ..) = trait_ty.kind() else {
1222        bug!("create_mono_items_for_vtable_methods: {trait_ty:?} not a trait type");
1223    };
1224    if let Some(principal) = trait_ty.principal() {
1225        let trait_ref =
1226            tcx.instantiate_bound_regions_with_erased(principal.with_self_ty(tcx, impl_ty));
1227        assert!(!trait_ref.has_escaping_bound_vars());
1228
1229        // Walk all methods of the trait, including those of its supertraits
1230        let entries = tcx.vtable_entries(trait_ref);
1231        debug!(?entries);
1232        let methods = entries
1233            .iter()
1234            .filter_map(|entry| match entry {
1235                VtblEntry::MetadataDropInPlace
1236                | VtblEntry::MetadataSize
1237                | VtblEntry::MetadataAlign
1238                | VtblEntry::Vacant => None,
1239                VtblEntry::TraitVPtr(_) => {
1240                    // all super trait items already covered, so skip them.
1241                    None
1242                }
1243                VtblEntry::Method(instance) => {
1244                    Some(*instance).filter(|instance| tcx.should_codegen_locally(*instance))
1245                }
1246            })
1247            .map(|item| create_fn_mono_item(tcx, item, source));
1248        output.extend(methods);
1249    }
1250
1251    // Also add the destructor, if it's necessary.
1252    //
1253    // This matches the check in vtable_allocation_provider in middle/ty/vtable.rs,
1254    // if we don't need drop we're not adding an actual pointer to the vtable.
1255    if impl_ty.needs_drop(tcx, ty::TypingEnv::fully_monomorphized()) {
1256        visit_drop_use(tcx, impl_ty, false, source, output);
1257    }
1258}
1259
1260/// Scans the CTFE alloc in order to find function pointers and statics that must be monomorphized.
1261fn collect_alloc<'tcx>(tcx: TyCtxt<'tcx>, alloc_id: AllocId, output: &mut MonoItems<'tcx>) {
1262    match tcx.global_alloc(alloc_id) {
1263        GlobalAlloc::Static(def_id) => {
1264            assert!(!tcx.is_thread_local_static(def_id));
1265            let instance = Instance::mono(tcx, def_id);
1266            if tcx.should_codegen_locally(instance) {
1267                trace!("collecting static {:?}", def_id);
1268                output.push(dummy_spanned(MonoItem::Static(def_id)));
1269            }
1270        }
1271        GlobalAlloc::Memory(alloc) => {
1272            trace!("collecting {:?} with {:#?}", alloc_id, alloc);
1273            let ptrs = alloc.inner().provenance().ptrs();
1274            // avoid `ensure_sufficient_stack` in the common case of "no pointers"
1275            if !ptrs.is_empty() {
1276                rustc_data_structures::stack::ensure_sufficient_stack(move || {
1277                    for &prov in ptrs.values() {
1278                        collect_alloc(tcx, prov.alloc_id(), output);
1279                    }
1280                });
1281            }
1282        }
1283        GlobalAlloc::Function { instance, .. } => {
1284            if tcx.should_codegen_locally(instance) {
1285                trace!("collecting {:?} with {:#?}", alloc_id, instance);
1286                output.push(create_fn_mono_item(tcx, instance, DUMMY_SP));
1287            }
1288        }
1289        GlobalAlloc::VTable(ty, dyn_ty) => {
1290            let alloc_id = tcx.vtable_allocation((
1291                ty,
1292                dyn_ty
1293                    .principal()
1294                    .map(|principal| tcx.instantiate_bound_regions_with_erased(principal)),
1295            ));
1296            collect_alloc(tcx, alloc_id, output)
1297        }
1298        GlobalAlloc::TypeId { .. } => {}
1299    }
1300}
1301
1302/// Scans the MIR in order to find function calls, closures, and drop-glue.
1303///
1304/// Anything that's found is added to `output`. Furthermore the "mentioned items" of the MIR are returned.
1305#[instrument(skip(tcx), level = "debug")]
1306fn collect_items_of_instance<'tcx>(
1307    tcx: TyCtxt<'tcx>,
1308    instance: Instance<'tcx>,
1309    mode: CollectionMode,
1310) -> Result<(MonoItems<'tcx>, MonoItems<'tcx>), NormalizationErrorInMono> {
1311    // This item is getting monomorphized, do mono-time checks.
1312    let body = tcx.instance_mir(instance.def);
1313    // Plenty of code paths later assume that everything can be normalized. So we have to check
1314    // normalization first.
1315    // We choose to emit the error outside to provide helpful diagnostics.
1316    check_normalization_error(tcx, instance, body)?;
1317    tcx.ensure_ok().check_mono_item(instance);
1318
1319    // Naively, in "used" collection mode, all functions get added to *both* `used_items` and
1320    // `mentioned_items`. Mentioned items processing will then notice that they have already been
1321    // visited, but at that point each mentioned item has been monomorphized, added to the
1322    // `mentioned_items` worklist, and checked in the global set of visited items. To remove that
1323    // overhead, we have a special optimization that avoids adding items to `mentioned_items` when
1324    // they are already added in `used_items`. We could just scan `used_items`, but that's a linear
1325    // scan and not very efficient. Furthermore we can only do that *after* monomorphizing the
1326    // mentioned item. So instead we collect all pre-monomorphized `MentionedItem` that were already
1327    // added to `used_items` in a hash set, which can efficiently query in the
1328    // `body.mentioned_items` loop below without even having to monomorphize the item.
1329    let mut used_items = MonoItems::new();
1330    let mut mentioned_items = MonoItems::new();
1331    let mut used_mentioned_items = Default::default();
1332    let mut collector = MirUsedCollector {
1333        tcx,
1334        body,
1335        used_items: &mut used_items,
1336        used_mentioned_items: &mut used_mentioned_items,
1337        instance,
1338    };
1339
1340    if mode == CollectionMode::UsedItems {
1341        if tcx.sess.opts.debuginfo == DebugInfo::Full {
1342            for var_debug_info in &body.var_debug_info {
1343                collector.visit_var_debug_info(var_debug_info);
1344            }
1345        }
1346        for (bb, data) in traversal::mono_reachable(body, tcx, instance) {
1347            collector.visit_basic_block_data(bb, data)
1348        }
1349    }
1350
1351    // Always visit all `required_consts`, so that we evaluate them and abort compilation if any of
1352    // them errors.
1353    for const_op in body.required_consts() {
1354        if let Some(val) = collector.eval_constant(const_op) {
1355            collect_const_value(tcx, val, &mut mentioned_items);
1356        }
1357    }
1358
1359    // Always gather mentioned items. We try to avoid processing items that we have already added to
1360    // `used_items` above.
1361    for item in body.mentioned_items() {
1362        if !collector.used_mentioned_items.contains(&item.node) {
1363            let item_mono = collector.monomorphize(item.node);
1364            visit_mentioned_item(tcx, &item_mono, item.span, &mut mentioned_items);
1365        }
1366    }
1367
1368    Ok((used_items, mentioned_items))
1369}
1370
1371fn items_of_instance<'tcx>(
1372    tcx: TyCtxt<'tcx>,
1373    (instance, mode): (Instance<'tcx>, CollectionMode),
1374) -> Result<
1375    (&'tcx [Spanned<MonoItem<'tcx>>], &'tcx [Spanned<MonoItem<'tcx>>]),
1376    NormalizationErrorInMono,
1377> {
1378    let (used_items, mentioned_items) = collect_items_of_instance(tcx, instance, mode)?;
1379
1380    let used_items = tcx.arena.alloc_from_iter(used_items);
1381    let mentioned_items = tcx.arena.alloc_from_iter(mentioned_items);
1382
1383    Ok((used_items, mentioned_items))
1384}
1385
1386/// `item` must be already monomorphized.
1387#[instrument(skip(tcx, span, output), level = "debug")]
1388fn visit_mentioned_item<'tcx>(
1389    tcx: TyCtxt<'tcx>,
1390    item: &MentionedItem<'tcx>,
1391    span: Span,
1392    output: &mut MonoItems<'tcx>,
1393) {
1394    match *item {
1395        MentionedItem::Fn(ty) => {
1396            if let ty::FnDef(def_id, args) = *ty.kind() {
1397                let instance = Instance::expect_resolve(
1398                    tcx,
1399                    ty::TypingEnv::fully_monomorphized(),
1400                    def_id,
1401                    args,
1402                    span,
1403                );
1404                // `visit_instance_use` was written for "used" item collection but works just as well
1405                // for "mentioned" item collection.
1406                // We can set `is_direct_call`; that just means we'll skip a bunch of shims that anyway
1407                // can't have their own failing constants.
1408                visit_instance_use(tcx, instance, /*is_direct_call*/ true, span, output);
1409            }
1410        }
1411        MentionedItem::Drop(ty) => {
1412            visit_drop_use(tcx, ty, /*is_direct_call*/ true, span, output);
1413        }
1414        MentionedItem::UnsizeCast { source_ty, target_ty } => {
1415            let (source_ty, target_ty) =
1416                find_tails_for_unsizing(tcx.at(span), source_ty, target_ty);
1417            // This could also be a different Unsize instruction, like
1418            // from a fixed sized array to a slice. But we are only
1419            // interested in things that produce a vtable.
1420            if target_ty.is_trait() && !source_ty.is_trait() {
1421                create_mono_items_for_vtable_methods(tcx, target_ty, source_ty, span, output);
1422            }
1423        }
1424        MentionedItem::Closure(source_ty) => {
1425            if let ty::Closure(def_id, args) = *source_ty.kind() {
1426                let instance =
1427                    Instance::resolve_closure(tcx, def_id, args, ty::ClosureKind::FnOnce);
1428                if tcx.should_codegen_locally(instance) {
1429                    output.push(create_fn_mono_item(tcx, instance, span));
1430                }
1431            } else {
1432                bug!()
1433            }
1434        }
1435    }
1436}
1437
1438#[instrument(skip(tcx, output), level = "debug")]
1439fn collect_const_value<'tcx>(
1440    tcx: TyCtxt<'tcx>,
1441    value: mir::ConstValue,
1442    output: &mut MonoItems<'tcx>,
1443) {
1444    match value {
1445        mir::ConstValue::Scalar(Scalar::Ptr(ptr, _size)) => {
1446            collect_alloc(tcx, ptr.provenance.alloc_id(), output)
1447        }
1448        mir::ConstValue::Indirect { alloc_id, .. }
1449        | mir::ConstValue::Slice { alloc_id, meta: _ } => collect_alloc(tcx, alloc_id, output),
1450        _ => {}
1451    }
1452}
1453
1454//=-----------------------------------------------------------------------------
1455// Root Collection
1456//=-----------------------------------------------------------------------------
1457
1458// Find all non-generic items by walking the HIR. These items serve as roots to
1459// start monomorphizing from.
1460#[instrument(skip(tcx, mode), level = "debug")]
1461fn collect_roots(tcx: TyCtxt<'_>, mode: MonoItemCollectionStrategy) -> Vec<MonoItem<'_>> {
1462    debug!("collecting roots");
1463    let mut roots = MonoItems::new();
1464
1465    {
1466        let entry_fn = tcx.entry_fn(());
1467
1468        debug!("collect_roots: entry_fn = {:?}", entry_fn);
1469
1470        let mut collector = RootCollector { tcx, strategy: mode, entry_fn, output: &mut roots };
1471
1472        let crate_items = tcx.hir_crate_items(());
1473
1474        for id in crate_items.free_items() {
1475            collector.process_item(id);
1476        }
1477
1478        for id in crate_items.impl_items() {
1479            collector.process_impl_item(id);
1480        }
1481
1482        for id in crate_items.nested_bodies() {
1483            collector.process_nested_body(id);
1484        }
1485
1486        collector.push_extra_entry_roots();
1487    }
1488
1489    // We can only codegen items that are instantiable - items all of
1490    // whose predicates hold. Luckily, items that aren't instantiable
1491    // can't actually be used, so we can just skip codegenning them.
1492    roots
1493        .into_iter()
1494        .filter_map(|Spanned { node: mono_item, .. }| {
1495            mono_item.is_instantiable(tcx).then_some(mono_item)
1496        })
1497        .collect()
1498}
1499
1500struct RootCollector<'a, 'tcx> {
1501    tcx: TyCtxt<'tcx>,
1502    strategy: MonoItemCollectionStrategy,
1503    output: &'a mut MonoItems<'tcx>,
1504    entry_fn: Option<(DefId, EntryFnType)>,
1505}
1506
1507impl<'v> RootCollector<'_, 'v> {
1508    fn process_item(&mut self, id: hir::ItemId) {
1509        match self.tcx.def_kind(id.owner_id) {
1510            DefKind::Enum | DefKind::Struct | DefKind::Union => {
1511                if self.strategy == MonoItemCollectionStrategy::Eager
1512                    && !self.tcx.generics_of(id.owner_id).requires_monomorphization(self.tcx)
1513                {
1514                    debug!("RootCollector: ADT drop-glue for `{id:?}`",);
1515                    let id_args =
1516                        ty::GenericArgs::for_item(self.tcx, id.owner_id.to_def_id(), |param, _| {
1517                            match param.kind {
1518                                GenericParamDefKind::Lifetime => {
1519                                    self.tcx.lifetimes.re_erased.into()
1520                                }
1521                                GenericParamDefKind::Type { .. }
1522                                | GenericParamDefKind::Const { .. } => {
1523                                    unreachable!(
1524                                        "`own_requires_monomorphization` check means that \
1525                                we should have no type/const params"
1526                                    )
1527                                }
1528                            }
1529                        });
1530
1531                    // This type is impossible to instantiate, so we should not try to
1532                    // generate a `drop_in_place` instance for it.
1533                    if self.tcx.instantiate_and_check_impossible_predicates((
1534                        id.owner_id.to_def_id(),
1535                        id_args,
1536                    )) {
1537                        return;
1538                    }
1539
1540                    let ty =
1541                        self.tcx.type_of(id.owner_id.to_def_id()).instantiate(self.tcx, id_args);
1542                    assert!(!ty.has_non_region_param());
1543                    visit_drop_use(self.tcx, ty, true, DUMMY_SP, self.output);
1544                }
1545            }
1546            DefKind::GlobalAsm => {
1547                debug!(
1548                    "RootCollector: ItemKind::GlobalAsm({})",
1549                    self.tcx.def_path_str(id.owner_id)
1550                );
1551                self.output.push(dummy_spanned(MonoItem::GlobalAsm(id)));
1552            }
1553            DefKind::Static { .. } => {
1554                let def_id = id.owner_id.to_def_id();
1555                debug!("RootCollector: ItemKind::Static({})", self.tcx.def_path_str(def_id));
1556                self.output.push(dummy_spanned(MonoItem::Static(def_id)));
1557            }
1558            DefKind::Const => {
1559                // Const items only generate mono items if they are actually used somewhere.
1560                // Just declaring them is insufficient.
1561
1562                // If we're collecting items eagerly, then recurse into all constants.
1563                // Otherwise the value is only collected when explicitly mentioned in other items.
1564                if self.strategy == MonoItemCollectionStrategy::Eager {
1565                    if !self.tcx.generics_of(id.owner_id).own_requires_monomorphization()
1566                        && let Ok(val) = self.tcx.const_eval_poly(id.owner_id.to_def_id())
1567                    {
1568                        collect_const_value(self.tcx, val, self.output);
1569                    }
1570                }
1571            }
1572            DefKind::Impl { of_trait: true } => {
1573                if self.strategy == MonoItemCollectionStrategy::Eager {
1574                    create_mono_items_for_default_impls(self.tcx, id, self.output);
1575                }
1576            }
1577            DefKind::Fn => {
1578                self.push_if_root(id.owner_id.def_id);
1579            }
1580            _ => {}
1581        }
1582    }
1583
1584    fn process_impl_item(&mut self, id: hir::ImplItemId) {
1585        if matches!(self.tcx.def_kind(id.owner_id), DefKind::AssocFn) {
1586            self.push_if_root(id.owner_id.def_id);
1587        }
1588    }
1589
1590    fn process_nested_body(&mut self, def_id: LocalDefId) {
1591        match self.tcx.def_kind(def_id) {
1592            DefKind::Closure => {
1593                // for 'pub async fn foo(..)' also trying to monomorphize foo::{closure}
1594                let is_pub_fn_coroutine =
1595                    match *self.tcx.type_of(def_id).instantiate_identity().kind() {
1596                        ty::Coroutine(cor_id, _args) => {
1597                            let tcx = self.tcx;
1598                            let parent_id = tcx.parent(cor_id);
1599                            tcx.def_kind(parent_id) == DefKind::Fn
1600                                && tcx.asyncness(parent_id).is_async()
1601                                && tcx.visibility(parent_id).is_public()
1602                        }
1603                        ty::Closure(..) | ty::CoroutineClosure(..) => false,
1604                        _ => unreachable!(),
1605                    };
1606                if (self.strategy == MonoItemCollectionStrategy::Eager || is_pub_fn_coroutine)
1607                    && !self
1608                        .tcx
1609                        .generics_of(self.tcx.typeck_root_def_id(def_id.to_def_id()))
1610                        .requires_monomorphization(self.tcx)
1611                {
1612                    let instance = match *self.tcx.type_of(def_id).instantiate_identity().kind() {
1613                        ty::Closure(def_id, args)
1614                        | ty::Coroutine(def_id, args)
1615                        | ty::CoroutineClosure(def_id, args) => {
1616                            Instance::new_raw(def_id, self.tcx.erase_and_anonymize_regions(args))
1617                        }
1618                        _ => unreachable!(),
1619                    };
1620                    let Ok(instance) = self.tcx.try_normalize_erasing_regions(
1621                        ty::TypingEnv::fully_monomorphized(),
1622                        instance,
1623                    ) else {
1624                        // Don't ICE on an impossible-to-normalize closure.
1625                        return;
1626                    };
1627                    let mono_item = create_fn_mono_item(self.tcx, instance, DUMMY_SP);
1628                    if mono_item.node.is_instantiable(self.tcx) {
1629                        self.output.push(mono_item);
1630                    }
1631                }
1632            }
1633            _ => {}
1634        }
1635    }
1636
1637    fn is_root(&self, def_id: LocalDefId) -> bool {
1638        !self.tcx.generics_of(def_id).requires_monomorphization(self.tcx)
1639            && match self.strategy {
1640                MonoItemCollectionStrategy::Eager => {
1641                    !matches!(self.tcx.codegen_fn_attrs(def_id).inline, InlineAttr::Force { .. })
1642                }
1643                MonoItemCollectionStrategy::Lazy => {
1644                    self.entry_fn.and_then(|(id, _)| id.as_local()) == Some(def_id)
1645                        || self.tcx.is_reachable_non_generic(def_id)
1646                        || self
1647                            .tcx
1648                            .codegen_fn_attrs(def_id)
1649                            .flags
1650                            .contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL)
1651                }
1652            }
1653    }
1654
1655    /// If `def_id` represents a root, pushes it onto the list of
1656    /// outputs. (Note that all roots must be monomorphic.)
1657    #[instrument(skip(self), level = "debug")]
1658    fn push_if_root(&mut self, def_id: LocalDefId) {
1659        if self.is_root(def_id) {
1660            debug!("found root");
1661
1662            let instance = Instance::mono(self.tcx, def_id.to_def_id());
1663            self.output.push(create_fn_mono_item(self.tcx, instance, DUMMY_SP));
1664        }
1665    }
1666
1667    /// As a special case, when/if we encounter the
1668    /// `main()` function, we also have to generate a
1669    /// monomorphized copy of the start lang item based on
1670    /// the return type of `main`. This is not needed when
1671    /// the user writes their own `start` manually.
1672    fn push_extra_entry_roots(&mut self) {
1673        let Some((main_def_id, EntryFnType::Main { .. })) = self.entry_fn else {
1674            return;
1675        };
1676
1677        let main_instance = Instance::mono(self.tcx, main_def_id);
1678        if self.tcx.should_codegen_locally(main_instance) {
1679            self.output.push(create_fn_mono_item(
1680                self.tcx,
1681                main_instance,
1682                self.tcx.def_span(main_def_id),
1683            ));
1684        }
1685
1686        let Some(start_def_id) = self.tcx.lang_items().start_fn() else {
1687            self.tcx.dcx().emit_fatal(errors::StartNotFound);
1688        };
1689        let main_ret_ty = self.tcx.fn_sig(main_def_id).no_bound_vars().unwrap().output();
1690
1691        // Given that `main()` has no arguments,
1692        // then its return type cannot have
1693        // late-bound regions, since late-bound
1694        // regions must appear in the argument
1695        // listing.
1696        let main_ret_ty = self.tcx.normalize_erasing_regions(
1697            ty::TypingEnv::fully_monomorphized(),
1698            main_ret_ty.no_bound_vars().unwrap(),
1699        );
1700
1701        let start_instance = Instance::expect_resolve(
1702            self.tcx,
1703            ty::TypingEnv::fully_monomorphized(),
1704            start_def_id,
1705            self.tcx.mk_args(&[main_ret_ty.into()]),
1706            DUMMY_SP,
1707        );
1708
1709        self.output.push(create_fn_mono_item(self.tcx, start_instance, DUMMY_SP));
1710    }
1711}
1712
1713#[instrument(level = "debug", skip(tcx, output))]
1714fn create_mono_items_for_default_impls<'tcx>(
1715    tcx: TyCtxt<'tcx>,
1716    item: hir::ItemId,
1717    output: &mut MonoItems<'tcx>,
1718) {
1719    let impl_ = tcx.impl_trait_header(item.owner_id);
1720
1721    if matches!(impl_.polarity, ty::ImplPolarity::Negative) {
1722        return;
1723    }
1724
1725    if tcx.generics_of(item.owner_id).own_requires_monomorphization() {
1726        return;
1727    }
1728
1729    // Lifetimes never affect trait selection, so we are allowed to eagerly
1730    // instantiate an instance of an impl method if the impl (and method,
1731    // which we check below) is only parameterized over lifetime. In that case,
1732    // we use the ReErased, which has no lifetime information associated with
1733    // it, to validate whether or not the impl is legal to instantiate at all.
1734    let only_region_params = |param: &ty::GenericParamDef, _: &_| match param.kind {
1735        GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(),
1736        GenericParamDefKind::Type { .. } | GenericParamDefKind::Const { .. } => {
1737            unreachable!(
1738                "`own_requires_monomorphization` check means that \
1739                we should have no type/const params"
1740            )
1741        }
1742    };
1743    let impl_args = GenericArgs::for_item(tcx, item.owner_id.to_def_id(), only_region_params);
1744    let trait_ref = impl_.trait_ref.instantiate(tcx, impl_args);
1745
1746    // Unlike 'lazy' monomorphization that begins by collecting items transitively
1747    // called by `main` or other global items, when eagerly monomorphizing impl
1748    // items, we never actually check that the predicates of this impl are satisfied
1749    // in a empty param env (i.e. with no assumptions).
1750    //
1751    // Even though this impl has no type or const generic parameters, because we don't
1752    // consider higher-ranked predicates such as `for<'a> &'a mut [u8]: Copy` to
1753    // be trivially false. We must now check that the impl has no impossible-to-satisfy
1754    // predicates.
1755    if tcx.instantiate_and_check_impossible_predicates((item.owner_id.to_def_id(), impl_args)) {
1756        return;
1757    }
1758
1759    let typing_env = ty::TypingEnv::fully_monomorphized();
1760    let trait_ref = tcx.normalize_erasing_regions(typing_env, trait_ref);
1761    let overridden_methods = tcx.impl_item_implementor_ids(item.owner_id);
1762    for method in tcx.provided_trait_methods(trait_ref.def_id) {
1763        if overridden_methods.contains_key(&method.def_id) {
1764            continue;
1765        }
1766
1767        if tcx.generics_of(method.def_id).own_requires_monomorphization() {
1768            continue;
1769        }
1770
1771        // As mentioned above, the method is legal to eagerly instantiate if it
1772        // only has lifetime generic parameters. This is validated by calling
1773        // `own_requires_monomorphization` on both the impl and method.
1774        let args = trait_ref.args.extend_to(tcx, method.def_id, only_region_params);
1775        let instance = ty::Instance::expect_resolve(tcx, typing_env, method.def_id, args, DUMMY_SP);
1776
1777        let mono_item = create_fn_mono_item(tcx, instance, DUMMY_SP);
1778        if mono_item.node.is_instantiable(tcx) && tcx.should_codegen_locally(instance) {
1779            output.push(mono_item);
1780        }
1781    }
1782}
1783
1784//=-----------------------------------------------------------------------------
1785// Top-level entry point, tying it all together
1786//=-----------------------------------------------------------------------------
1787
1788#[instrument(skip(tcx, strategy), level = "debug")]
1789pub(crate) fn collect_crate_mono_items<'tcx>(
1790    tcx: TyCtxt<'tcx>,
1791    strategy: MonoItemCollectionStrategy,
1792) -> (Vec<MonoItem<'tcx>>, UsageMap<'tcx>) {
1793    let _prof_timer = tcx.prof.generic_activity("monomorphization_collector");
1794
1795    let roots = tcx
1796        .sess
1797        .time("monomorphization_collector_root_collections", || collect_roots(tcx, strategy));
1798
1799    debug!("building mono item graph, beginning at roots");
1800
1801    let state = SharedState {
1802        visited: MTLock::new(UnordSet::default()),
1803        mentioned: MTLock::new(UnordSet::default()),
1804        usage_map: MTLock::new(UsageMap::new()),
1805    };
1806    let recursion_limit = tcx.recursion_limit();
1807
1808    tcx.sess.time("monomorphization_collector_graph_walk", || {
1809        par_for_each_in(roots, |root| {
1810            collect_items_root(tcx, dummy_spanned(*root), &state, recursion_limit);
1811        });
1812    });
1813
1814    // The set of MonoItems was created in an inherently indeterministic order because
1815    // of parallelism. We sort it here to ensure that the output is deterministic.
1816    let mono_items = tcx.with_stable_hashing_context(move |ref hcx| {
1817        state.visited.into_inner().into_sorted(hcx, true)
1818    });
1819
1820    (mono_items, state.usage_map.into_inner())
1821}
1822
1823pub(crate) fn provide(providers: &mut Providers) {
1824    providers.hooks.should_codegen_locally = should_codegen_locally;
1825    providers.items_of_instance = items_of_instance;
1826}