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