rustc_middle/mir/
mono.rs

1use std::borrow::Cow;
2use std::fmt;
3use std::hash::Hash;
4
5use rustc_ast::expand::autodiff_attrs::AutoDiffItem;
6use rustc_attr_data_structures::InlineAttr;
7use rustc_data_structures::base_n::{BaseNString, CASE_INSENSITIVE, ToBaseN};
8use rustc_data_structures::fingerprint::Fingerprint;
9use rustc_data_structures::fx::FxIndexMap;
10use rustc_data_structures::stable_hasher::{HashStable, StableHasher, ToStableHashKey};
11use rustc_data_structures::unord::UnordMap;
12use rustc_hashes::Hash128;
13use rustc_hir::ItemId;
14use rustc_hir::def_id::{CrateNum, DefId, DefIdSet, LOCAL_CRATE};
15use rustc_index::Idx;
16use rustc_macros::{HashStable, TyDecodable, TyEncodable};
17use rustc_query_system::ich::StableHashingContext;
18use rustc_session::config::OptLevel;
19use rustc_span::{Span, Symbol};
20use rustc_target::spec::SymbolVisibility;
21use tracing::debug;
22
23use crate::dep_graph::{DepNode, WorkProduct, WorkProductId};
24use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags;
25use crate::ty::{self, GenericArgs, Instance, InstanceKind, SymbolName, Ty, TyCtxt};
26
27/// Describes how a monomorphization will be instantiated in object files.
28#[derive(PartialEq)]
29pub enum InstantiationMode {
30    /// There will be exactly one instance of the given MonoItem. It will have
31    /// external linkage so that it can be linked to from other codegen units.
32    GloballyShared {
33        /// In some compilation scenarios we may decide to take functions that
34        /// are typically `LocalCopy` and instead move them to `GloballyShared`
35        /// to avoid codegenning them a bunch of times. In this situation,
36        /// however, our local copy may conflict with other crates also
37        /// inlining the same function.
38        ///
39        /// This flag indicates that this situation is occurring, and informs
40        /// symbol name calculation that some extra mangling is needed to
41        /// avoid conflicts. Note that this may eventually go away entirely if
42        /// ThinLTO enables us to *always* have a globally shared instance of a
43        /// function within one crate's compilation.
44        may_conflict: bool,
45    },
46
47    /// Each codegen unit containing a reference to the given MonoItem will
48    /// have its own private copy of the function (with internal linkage).
49    LocalCopy,
50}
51
52#[derive(PartialEq, Eq, Clone, Copy, Debug, Hash, HashStable, TyEncodable, TyDecodable)]
53pub enum MonoItem<'tcx> {
54    Fn(Instance<'tcx>),
55    Static(DefId),
56    GlobalAsm(ItemId),
57}
58
59fn opt_incr_drop_glue_mode<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> InstantiationMode {
60    // Non-ADTs can't have a Drop impl. This case is mostly hit by closures whose captures require
61    // dropping.
62    let ty::Adt(adt_def, _) = ty.kind() else {
63        return InstantiationMode::LocalCopy;
64    };
65
66    // Types that don't have a direct Drop impl, but have fields that require dropping.
67    let Some(dtor) = adt_def.destructor(tcx) else {
68        // We use LocalCopy for drops of enums only; this code is inherited from
69        // https://github.com/rust-lang/rust/pull/67332 and the theory is that we get to optimize
70        // out code like drop_in_place(Option::None) before crate-local ThinLTO, which improves
71        // compile time. At the time of writing, simply removing this entire check does seem to
72        // regress incr-opt compile times. But it sure seems like a more sophisticated check could
73        // do better here.
74        if adt_def.is_enum() {
75            return InstantiationMode::LocalCopy;
76        } else {
77            return InstantiationMode::GloballyShared { may_conflict: true };
78        }
79    };
80
81    // We've gotten to a drop_in_place for a type that directly implements Drop.
82    // The drop glue is a wrapper for the Drop::drop impl, and we are an optimized build, so in an
83    // effort to coordinate with the mode that the actual impl will get, we make the glue also
84    // LocalCopy.
85    if tcx.cross_crate_inlinable(dtor.did) {
86        InstantiationMode::LocalCopy
87    } else {
88        InstantiationMode::GloballyShared { may_conflict: true }
89    }
90}
91
92impl<'tcx> MonoItem<'tcx> {
93    /// Returns `true` if the mono item is user-defined (i.e. not compiler-generated, like shims).
94    pub fn is_user_defined(&self) -> bool {
95        match *self {
96            MonoItem::Fn(instance) => matches!(instance.def, InstanceKind::Item(..)),
97            MonoItem::Static(..) | MonoItem::GlobalAsm(..) => true,
98        }
99    }
100
101    // Note: if you change how item size estimates work, you might need to
102    // change NON_INCR_MIN_CGU_SIZE as well.
103    pub fn size_estimate(&self, tcx: TyCtxt<'tcx>) -> usize {
104        match *self {
105            MonoItem::Fn(instance) => tcx.size_estimate(instance),
106            // Conservatively estimate the size of a static declaration or
107            // assembly item to be 1.
108            MonoItem::Static(_) | MonoItem::GlobalAsm(_) => 1,
109        }
110    }
111
112    pub fn is_generic_fn(&self) -> bool {
113        match self {
114            MonoItem::Fn(instance) => instance.args.non_erasable_generics().next().is_some(),
115            MonoItem::Static(..) | MonoItem::GlobalAsm(..) => false,
116        }
117    }
118
119    pub fn symbol_name(&self, tcx: TyCtxt<'tcx>) -> SymbolName<'tcx> {
120        match *self {
121            MonoItem::Fn(instance) => tcx.symbol_name(instance),
122            MonoItem::Static(def_id) => tcx.symbol_name(Instance::mono(tcx, def_id)),
123            MonoItem::GlobalAsm(item_id) => {
124                SymbolName::new(tcx, &format!("global_asm_{:?}", item_id.owner_id))
125            }
126        }
127    }
128
129    pub fn instantiation_mode(&self, tcx: TyCtxt<'tcx>) -> InstantiationMode {
130        // The case handling here is written in the same style as cross_crate_inlinable, we first
131        // handle the cases where we must use a particular instantiation mode, then cascade down
132        // through a sequence of heuristics.
133
134        // The first thing we do is detect MonoItems which we must instantiate exactly once in the
135        // whole program.
136
137        // Statics and global_asm! must be instantiated exactly once.
138        let instance = match *self {
139            MonoItem::Fn(instance) => instance,
140            MonoItem::Static(..) | MonoItem::GlobalAsm(..) => {
141                return InstantiationMode::GloballyShared { may_conflict: false };
142            }
143        };
144
145        // Similarly, the executable entrypoint must be instantiated exactly once.
146        if let Some((entry_def_id, _)) = tcx.entry_fn(()) {
147            if instance.def_id() == entry_def_id {
148                return InstantiationMode::GloballyShared { may_conflict: false };
149            }
150        }
151
152        // If the function is #[naked] or contains any other attribute that requires exactly-once
153        // instantiation:
154        // We emit an unused_attributes lint for this case, which should be kept in sync if possible.
155        let codegen_fn_attrs = tcx.codegen_fn_attrs(instance.def_id());
156        if codegen_fn_attrs.contains_extern_indicator()
157            || codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED)
158        {
159            return InstantiationMode::GloballyShared { may_conflict: false };
160        }
161
162        // This is technically a heuristic even though it's in the "not a heuristic" part of
163        // instantiation mode selection.
164        // It is surely possible to untangle this; the root problem is that the way we instantiate
165        // InstanceKind other than Item is very complicated.
166        //
167        // The fallback case is to give everything else GloballyShared at OptLevel::No and
168        // LocalCopy at all other opt levels. This is a good default, except for one specific build
169        // configuration: Optimized incremental builds.
170        // In the current compiler architecture there is a fundamental tension between
171        // optimizations (which want big CGUs with as many things LocalCopy as possible) and
172        // incrementality (which wants small CGUs with as many things GloballyShared as possible).
173        // The heuristics implemented here do better than a completely naive approach in the
174        // compiler benchmark suite, but there is no reason to believe they are optimal.
175        if let InstanceKind::DropGlue(_, Some(ty)) = instance.def {
176            if tcx.sess.opts.optimize == OptLevel::No {
177                return InstantiationMode::GloballyShared { may_conflict: false };
178            }
179            if tcx.sess.opts.incremental.is_none() {
180                return InstantiationMode::LocalCopy;
181            }
182            return opt_incr_drop_glue_mode(tcx, ty);
183        }
184
185        // We need to ensure that we do not decide the InstantiationMode of an exported symbol is
186        // LocalCopy. Since exported symbols are computed based on the output of
187        // cross_crate_inlinable, we are beholden to our previous decisions.
188        //
189        // Note that just like above, this check for requires_inline is technically a heuristic
190        // even though it's in the "not a heuristic" part of instantiation mode selection.
191        if !tcx.cross_crate_inlinable(instance.def_id()) && !instance.def.requires_inline(tcx) {
192            return InstantiationMode::GloballyShared { may_conflict: false };
193        }
194
195        // Beginning of heuristics. The handling of link-dead-code and inline(always) are QoL only,
196        // the compiler should not crash and linkage should work, but codegen may be undesirable.
197
198        // -Clink-dead-code was given an unfortunate name; the point of the flag is to assist
199        // coverage tools which rely on having every function in the program appear in the
200        // generated code. If we select LocalCopy, functions which are not used because they are
201        // missing test coverage will disappear from such coverage reports, defeating the point.
202        // Note that -Cinstrument-coverage does not require such assistance from us, only coverage
203        // tools implemented without compiler support ironically require a special compiler flag.
204        if tcx.sess.link_dead_code() {
205            return InstantiationMode::GloballyShared { may_conflict: true };
206        }
207
208        // To ensure that #[inline(always)] can be inlined as much as possible, especially in unoptimized
209        // builds, we always select LocalCopy.
210        if codegen_fn_attrs.inline.always() {
211            return InstantiationMode::LocalCopy;
212        }
213
214        // #[inline(never)] functions in general are poor candidates for inlining and thus since
215        // LocalCopy generally increases code size for the benefit of optimizations from inlining,
216        // we want to give them GloballyShared codegen.
217        // The slight problem is that generic functions need to always support cross-crate
218        // compilation, so all previous stages of the compiler are obligated to treat generic
219        // functions the same as those that unconditionally get LocalCopy codegen. It's only when
220        // we get here that we can at least not codegen a #[inline(never)] generic function in all
221        // of our CGUs.
222        if let InlineAttr::Never = tcx.codegen_fn_attrs(instance.def_id()).inline
223            && self.is_generic_fn()
224        {
225            return InstantiationMode::GloballyShared { may_conflict: true };
226        }
227
228        // The fallthrough case is to generate LocalCopy for all optimized builds, and
229        // GloballyShared with conflict prevention when optimizations are disabled.
230        match tcx.sess.opts.optimize {
231            OptLevel::No => InstantiationMode::GloballyShared { may_conflict: true },
232            _ => InstantiationMode::LocalCopy,
233        }
234    }
235
236    pub fn explicit_linkage(&self, tcx: TyCtxt<'tcx>) -> Option<Linkage> {
237        let def_id = match *self {
238            MonoItem::Fn(ref instance) => instance.def_id(),
239            MonoItem::Static(def_id) => def_id,
240            MonoItem::GlobalAsm(..) => return None,
241        };
242
243        let codegen_fn_attrs = tcx.codegen_fn_attrs(def_id);
244        codegen_fn_attrs.linkage
245    }
246
247    /// Returns `true` if this instance is instantiable - whether it has no unsatisfied
248    /// predicates.
249    ///
250    /// In order to codegen an item, all of its predicates must hold, because
251    /// otherwise the item does not make sense. Type-checking ensures that
252    /// the predicates of every item that is *used by* a valid item *do*
253    /// hold, so we can rely on that.
254    ///
255    /// However, we codegen collector roots (reachable items) and functions
256    /// in vtables when they are seen, even if they are not used, and so they
257    /// might not be instantiable. For example, a programmer can define this
258    /// public function:
259    ///
260    ///     pub fn foo<'a>(s: &'a mut ()) where &'a mut (): Clone {
261    ///         <&mut () as Clone>::clone(&s);
262    ///     }
263    ///
264    /// That function can't be codegened, because the method `<&mut () as Clone>::clone`
265    /// does not exist. Luckily for us, that function can't ever be used,
266    /// because that would require for `&'a mut (): Clone` to hold, so we
267    /// can just not emit any code, or even a linker reference for it.
268    ///
269    /// Similarly, if a vtable method has such a signature, and therefore can't
270    /// be used, we can just not emit it and have a placeholder (a null pointer,
271    /// which will never be accessed) in its place.
272    pub fn is_instantiable(&self, tcx: TyCtxt<'tcx>) -> bool {
273        debug!("is_instantiable({:?})", self);
274        let (def_id, args) = match *self {
275            MonoItem::Fn(ref instance) => (instance.def_id(), instance.args),
276            MonoItem::Static(def_id) => (def_id, GenericArgs::empty()),
277            // global asm never has predicates
278            MonoItem::GlobalAsm(..) => return true,
279        };
280
281        !tcx.instantiate_and_check_impossible_predicates((def_id, &args))
282    }
283
284    pub fn local_span(&self, tcx: TyCtxt<'tcx>) -> Option<Span> {
285        match *self {
286            MonoItem::Fn(Instance { def, .. }) => def.def_id().as_local(),
287            MonoItem::Static(def_id) => def_id.as_local(),
288            MonoItem::GlobalAsm(item_id) => Some(item_id.owner_id.def_id),
289        }
290        .map(|def_id| tcx.def_span(def_id))
291    }
292
293    // Only used by rustc_codegen_cranelift
294    pub fn codegen_dep_node(&self, tcx: TyCtxt<'tcx>) -> DepNode {
295        crate::dep_graph::make_compile_mono_item(tcx, self)
296    }
297
298    /// Returns the item's `CrateNum`
299    pub fn krate(&self) -> CrateNum {
300        match self {
301            MonoItem::Fn(instance) => instance.def_id().krate,
302            MonoItem::Static(def_id) => def_id.krate,
303            MonoItem::GlobalAsm(..) => LOCAL_CRATE,
304        }
305    }
306
307    /// Returns the item's `DefId`
308    pub fn def_id(&self) -> DefId {
309        match *self {
310            MonoItem::Fn(Instance { def, .. }) => def.def_id(),
311            MonoItem::Static(def_id) => def_id,
312            MonoItem::GlobalAsm(item_id) => item_id.owner_id.to_def_id(),
313        }
314    }
315}
316
317impl<'tcx> fmt::Display for MonoItem<'tcx> {
318    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
319        match *self {
320            MonoItem::Fn(instance) => write!(f, "fn {instance}"),
321            MonoItem::Static(def_id) => {
322                write!(f, "static {}", Instance::new_raw(def_id, GenericArgs::empty()))
323            }
324            MonoItem::GlobalAsm(..) => write!(f, "global_asm"),
325        }
326    }
327}
328
329impl ToStableHashKey<StableHashingContext<'_>> for MonoItem<'_> {
330    type KeyType = Fingerprint;
331
332    fn to_stable_hash_key(&self, hcx: &StableHashingContext<'_>) -> Self::KeyType {
333        let mut hasher = StableHasher::new();
334        self.hash_stable(&mut hcx.clone(), &mut hasher);
335        hasher.finish()
336    }
337}
338
339#[derive(Debug, HashStable, Copy, Clone)]
340pub struct MonoItemPartitions<'tcx> {
341    pub codegen_units: &'tcx [CodegenUnit<'tcx>],
342    pub all_mono_items: &'tcx DefIdSet,
343    pub autodiff_items: &'tcx [AutoDiffItem],
344}
345
346#[derive(Debug, HashStable)]
347pub struct CodegenUnit<'tcx> {
348    /// A name for this CGU. Incremental compilation requires that
349    /// name be unique amongst **all** crates. Therefore, it should
350    /// contain something unique to this crate (e.g., a module path)
351    /// as well as the crate name and disambiguator.
352    name: Symbol,
353    items: FxIndexMap<MonoItem<'tcx>, MonoItemData>,
354    size_estimate: usize,
355    primary: bool,
356    /// True if this is CGU is used to hold code coverage information for dead code,
357    /// false otherwise.
358    is_code_coverage_dead_code_cgu: bool,
359}
360
361/// Auxiliary info about a `MonoItem`.
362#[derive(Copy, Clone, PartialEq, Debug, HashStable)]
363pub struct MonoItemData {
364    /// A cached copy of the result of `MonoItem::instantiation_mode`, where
365    /// `GloballyShared` maps to `false` and `LocalCopy` maps to `true`.
366    pub inlined: bool,
367
368    pub linkage: Linkage,
369    pub visibility: Visibility,
370
371    /// A cached copy of the result of `MonoItem::size_estimate`.
372    pub size_estimate: usize,
373}
374
375/// Specifies the linkage type for a `MonoItem`.
376///
377/// See <https://llvm.org/docs/LangRef.html#linkage-types> for more details about these variants.
378#[derive(Copy, Clone, PartialEq, Debug, TyEncodable, TyDecodable, HashStable)]
379pub enum Linkage {
380    External,
381    AvailableExternally,
382    LinkOnceAny,
383    LinkOnceODR,
384    WeakAny,
385    WeakODR,
386    Internal,
387    ExternalWeak,
388    Common,
389}
390
391/// Specifies the symbol visibility with regards to dynamic linking.
392///
393/// Visibility doesn't have any effect when linkage is internal.
394///
395/// DSO means dynamic shared object, that is a dynamically linked executable or dylib.
396#[derive(Copy, Clone, PartialEq, Debug, HashStable)]
397pub enum Visibility {
398    /// Export the symbol from the DSO and apply overrides of the symbol by outside DSOs to within
399    /// the DSO if the object file format supports this.
400    Default,
401    /// Hide the symbol outside of the defining DSO even when external linkage is used to export it
402    /// from the object file.
403    Hidden,
404    /// Export the symbol from the DSO, but don't apply overrides of the symbol by outside DSOs to
405    /// within the DSO. Equivalent to default visibility with object file formats that don't support
406    /// overriding exported symbols by another DSO.
407    Protected,
408}
409
410impl From<SymbolVisibility> for Visibility {
411    fn from(value: SymbolVisibility) -> Self {
412        match value {
413            SymbolVisibility::Hidden => Visibility::Hidden,
414            SymbolVisibility::Protected => Visibility::Protected,
415            SymbolVisibility::Interposable => Visibility::Default,
416        }
417    }
418}
419
420impl<'tcx> CodegenUnit<'tcx> {
421    #[inline]
422    pub fn new(name: Symbol) -> CodegenUnit<'tcx> {
423        CodegenUnit {
424            name,
425            items: Default::default(),
426            size_estimate: 0,
427            primary: false,
428            is_code_coverage_dead_code_cgu: false,
429        }
430    }
431
432    pub fn name(&self) -> Symbol {
433        self.name
434    }
435
436    pub fn set_name(&mut self, name: Symbol) {
437        self.name = name;
438    }
439
440    pub fn is_primary(&self) -> bool {
441        self.primary
442    }
443
444    pub fn make_primary(&mut self) {
445        self.primary = true;
446    }
447
448    pub fn items(&self) -> &FxIndexMap<MonoItem<'tcx>, MonoItemData> {
449        &self.items
450    }
451
452    pub fn items_mut(&mut self) -> &mut FxIndexMap<MonoItem<'tcx>, MonoItemData> {
453        &mut self.items
454    }
455
456    pub fn is_code_coverage_dead_code_cgu(&self) -> bool {
457        self.is_code_coverage_dead_code_cgu
458    }
459
460    /// Marks this CGU as the one used to contain code coverage information for dead code.
461    pub fn make_code_coverage_dead_code_cgu(&mut self) {
462        self.is_code_coverage_dead_code_cgu = true;
463    }
464
465    pub fn mangle_name(human_readable_name: &str) -> BaseNString {
466        let mut hasher = StableHasher::new();
467        human_readable_name.hash(&mut hasher);
468        let hash: Hash128 = hasher.finish();
469        hash.as_u128().to_base_fixed_len(CASE_INSENSITIVE)
470    }
471
472    pub fn shorten_name(human_readable_name: &str) -> Cow<'_, str> {
473        // Set a limit a somewhat below the common platform limits for file names.
474        const MAX_CGU_NAME_LENGTH: usize = 200;
475        const TRUNCATED_NAME_PREFIX: &str = "-trunc-";
476        if human_readable_name.len() > MAX_CGU_NAME_LENGTH {
477            let mangled_name = Self::mangle_name(human_readable_name);
478            // Determine a safe byte offset to truncate the name to
479            let truncate_to = human_readable_name.floor_char_boundary(
480                MAX_CGU_NAME_LENGTH - TRUNCATED_NAME_PREFIX.len() - mangled_name.len(),
481            );
482            format!(
483                "{}{}{}",
484                &human_readable_name[..truncate_to],
485                TRUNCATED_NAME_PREFIX,
486                mangled_name
487            )
488            .into()
489        } else {
490            // If the name is short enough, we can just return it as is.
491            human_readable_name.into()
492        }
493    }
494
495    pub fn compute_size_estimate(&mut self) {
496        // The size of a codegen unit as the sum of the sizes of the items
497        // within it.
498        self.size_estimate = self.items.values().map(|data| data.size_estimate).sum();
499    }
500
501    /// Should only be called if [`compute_size_estimate`] has previously been called.
502    ///
503    /// [`compute_size_estimate`]: Self::compute_size_estimate
504    #[inline]
505    pub fn size_estimate(&self) -> usize {
506        // Items are never zero-sized, so if we have items the estimate must be
507        // non-zero, unless we forgot to call `compute_size_estimate` first.
508        assert!(self.items.is_empty() || self.size_estimate != 0);
509        self.size_estimate
510    }
511
512    pub fn contains_item(&self, item: &MonoItem<'tcx>) -> bool {
513        self.items().contains_key(item)
514    }
515
516    pub fn work_product_id(&self) -> WorkProductId {
517        WorkProductId::from_cgu_name(self.name().as_str())
518    }
519
520    pub fn previous_work_product(&self, tcx: TyCtxt<'_>) -> WorkProduct {
521        let work_product_id = self.work_product_id();
522        tcx.dep_graph
523            .previous_work_product(&work_product_id)
524            .unwrap_or_else(|| panic!("Could not find work-product for CGU `{}`", self.name()))
525    }
526
527    pub fn items_in_deterministic_order(
528        &self,
529        tcx: TyCtxt<'tcx>,
530    ) -> Vec<(MonoItem<'tcx>, MonoItemData)> {
531        // The codegen tests rely on items being process in the same order as
532        // they appear in the file, so for local items, we sort by node_id first
533        #[derive(PartialEq, Eq, PartialOrd, Ord)]
534        struct ItemSortKey<'tcx>(Option<usize>, SymbolName<'tcx>);
535
536        fn item_sort_key<'tcx>(tcx: TyCtxt<'tcx>, item: MonoItem<'tcx>) -> ItemSortKey<'tcx> {
537            ItemSortKey(
538                match item {
539                    MonoItem::Fn(ref instance) => {
540                        match instance.def {
541                            // We only want to take HirIds of user-defined
542                            // instances into account. The others don't matter for
543                            // the codegen tests and can even make item order
544                            // unstable.
545                            InstanceKind::Item(def) => def.as_local().map(Idx::index),
546                            InstanceKind::VTableShim(..)
547                            | InstanceKind::ReifyShim(..)
548                            | InstanceKind::Intrinsic(..)
549                            | InstanceKind::FnPtrShim(..)
550                            | InstanceKind::Virtual(..)
551                            | InstanceKind::ClosureOnceShim { .. }
552                            | InstanceKind::ConstructCoroutineInClosureShim { .. }
553                            | InstanceKind::DropGlue(..)
554                            | InstanceKind::CloneShim(..)
555                            | InstanceKind::ThreadLocalShim(..)
556                            | InstanceKind::FnPtrAddrShim(..)
557                            | InstanceKind::AsyncDropGlue(..)
558                            | InstanceKind::FutureDropPollShim(..)
559                            | InstanceKind::AsyncDropGlueCtorShim(..) => None,
560                        }
561                    }
562                    MonoItem::Static(def_id) => def_id.as_local().map(Idx::index),
563                    MonoItem::GlobalAsm(item_id) => Some(item_id.owner_id.def_id.index()),
564                },
565                item.symbol_name(tcx),
566            )
567        }
568
569        let mut items: Vec<_> = self.items().iter().map(|(&i, &data)| (i, data)).collect();
570        items.sort_by_cached_key(|&(i, _)| item_sort_key(tcx, i));
571        items
572    }
573
574    pub fn codegen_dep_node(&self, tcx: TyCtxt<'tcx>) -> DepNode {
575        crate::dep_graph::make_compile_codegen_unit(tcx, self.name())
576    }
577}
578
579impl ToStableHashKey<StableHashingContext<'_>> for CodegenUnit<'_> {
580    type KeyType = String;
581
582    fn to_stable_hash_key(&self, _: &StableHashingContext<'_>) -> Self::KeyType {
583        // Codegen unit names are conceptually required to be stable across
584        // compilation session so that object file names match up.
585        self.name.to_string()
586    }
587}
588
589pub struct CodegenUnitNameBuilder<'tcx> {
590    tcx: TyCtxt<'tcx>,
591    cache: UnordMap<CrateNum, String>,
592}
593
594impl<'tcx> CodegenUnitNameBuilder<'tcx> {
595    pub fn new(tcx: TyCtxt<'tcx>) -> Self {
596        CodegenUnitNameBuilder { tcx, cache: Default::default() }
597    }
598
599    /// CGU names should fulfill the following requirements:
600    /// - They should be able to act as a file name on any kind of file system
601    /// - They should not collide with other CGU names, even for different versions
602    ///   of the same crate.
603    ///
604    /// Consequently, we don't use special characters except for '.' and '-' and we
605    /// prefix each name with the crate-name and crate-disambiguator.
606    ///
607    /// This function will build CGU names of the form:
608    ///
609    /// ```text
610    /// <crate-name>.<crate-disambiguator>[-in-<local-crate-id>](-<component>)*[.<special-suffix>]
611    /// <local-crate-id> = <local-crate-name>.<local-crate-disambiguator>
612    /// ```
613    ///
614    /// The '.' before `<special-suffix>` makes sure that names with a special
615    /// suffix can never collide with a name built out of regular Rust
616    /// identifiers (e.g., module paths).
617    pub fn build_cgu_name<I, C, S>(
618        &mut self,
619        cnum: CrateNum,
620        components: I,
621        special_suffix: Option<S>,
622    ) -> Symbol
623    where
624        I: IntoIterator<Item = C>,
625        C: fmt::Display,
626        S: fmt::Display,
627    {
628        let cgu_name = self.build_cgu_name_no_mangle(cnum, components, special_suffix);
629
630        if self.tcx.sess.opts.unstable_opts.human_readable_cgu_names {
631            Symbol::intern(&CodegenUnit::shorten_name(cgu_name.as_str()))
632        } else {
633            Symbol::intern(&CodegenUnit::mangle_name(cgu_name.as_str()))
634        }
635    }
636
637    /// Same as `CodegenUnit::build_cgu_name()` but will never mangle the
638    /// resulting name.
639    pub fn build_cgu_name_no_mangle<I, C, S>(
640        &mut self,
641        cnum: CrateNum,
642        components: I,
643        special_suffix: Option<S>,
644    ) -> Symbol
645    where
646        I: IntoIterator<Item = C>,
647        C: fmt::Display,
648        S: fmt::Display,
649    {
650        use std::fmt::Write;
651
652        let mut cgu_name = String::with_capacity(64);
653
654        // Start out with the crate name and disambiguator
655        let tcx = self.tcx;
656        let crate_prefix = self.cache.entry(cnum).or_insert_with(|| {
657            // Whenever the cnum is not LOCAL_CRATE we also mix in the
658            // local crate's ID. Otherwise there can be collisions between CGUs
659            // instantiating stuff for upstream crates.
660            let local_crate_id = if cnum != LOCAL_CRATE {
661                let local_stable_crate_id = tcx.stable_crate_id(LOCAL_CRATE);
662                format!("-in-{}.{:08x}", tcx.crate_name(LOCAL_CRATE), local_stable_crate_id)
663            } else {
664                String::new()
665            };
666
667            let stable_crate_id = tcx.stable_crate_id(LOCAL_CRATE);
668            format!("{}.{:08x}{}", tcx.crate_name(cnum), stable_crate_id, local_crate_id)
669        });
670
671        write!(cgu_name, "{crate_prefix}").unwrap();
672
673        // Add the components
674        for component in components {
675            write!(cgu_name, "-{component}").unwrap();
676        }
677
678        if let Some(special_suffix) = special_suffix {
679            // We add a dot in here so it cannot clash with anything in a regular
680            // Rust identifier
681            write!(cgu_name, ".{special_suffix}").unwrap();
682        }
683
684        Symbol::intern(&cgu_name)
685    }
686}
687
688/// See module-level docs of `rustc_monomorphize::collector` on some context for "mentioned" items.
689#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
690pub enum CollectionMode {
691    /// Collect items that are used, i.e., actually needed for codegen.
692    ///
693    /// Which items are used can depend on optimization levels, as MIR optimizations can remove
694    /// uses.
695    UsedItems,
696    /// Collect items that are mentioned. The goal of this mode is that it is independent of
697    /// optimizations: the set of "mentioned" items is computed before optimizations are run.
698    ///
699    /// The exact contents of this set are *not* a stable guarantee. (For instance, it is currently
700    /// computed after drop-elaboration. If we ever do some optimizations even in debug builds, we
701    /// might decide to run them before computing mentioned items.) The key property of this set is
702    /// that it is optimization-independent.
703    MentionedItems,
704}