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