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