]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/mir/mono.rs
Rollup merge of #95368 - lopopolo:lopopolo/string-try-reserve-exact-doc-typo, r=Dylan-DPC
[rust.git] / compiler / rustc_middle / src / mir / mono.rs
1 use crate::dep_graph::{DepNode, WorkProduct, WorkProductId};
2 use crate::ty::{subst::InternalSubsts, Instance, InstanceDef, SymbolName, TyCtxt};
3 use rustc_attr::InlineAttr;
4 use rustc_data_structures::base_n;
5 use rustc_data_structures::fingerprint::Fingerprint;
6 use rustc_data_structures::fx::FxHashMap;
7 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
8 use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
9 use rustc_hir::ItemId;
10 use rustc_index::vec::Idx;
11 use rustc_query_system::ich::{NodeIdHashingMode, StableHashingContext};
12 use rustc_session::config::OptLevel;
13 use rustc_span::source_map::Span;
14 use rustc_span::symbol::Symbol;
15 use std::fmt;
16 use std::hash::Hash;
17
18 /// Describes how a monomorphization will be instantiated in object files.
19 #[derive(PartialEq)]
20 pub enum InstantiationMode {
21     /// There will be exactly one instance of the given MonoItem. It will have
22     /// external linkage so that it can be linked to from other codegen units.
23     GloballyShared {
24         /// In some compilation scenarios we may decide to take functions that
25         /// are typically `LocalCopy` and instead move them to `GloballyShared`
26         /// to avoid codegenning them a bunch of times. In this situation,
27         /// however, our local copy may conflict with other crates also
28         /// inlining the same function.
29         ///
30         /// This flag indicates that this situation is occurring, and informs
31         /// symbol name calculation that some extra mangling is needed to
32         /// avoid conflicts. Note that this may eventually go away entirely if
33         /// ThinLTO enables us to *always* have a globally shared instance of a
34         /// function within one crate's compilation.
35         may_conflict: bool,
36     },
37
38     /// Each codegen unit containing a reference to the given MonoItem will
39     /// have its own private copy of the function (with internal linkage).
40     LocalCopy,
41 }
42
43 #[derive(PartialEq, Eq, Clone, Copy, Debug, Hash)]
44 pub enum MonoItem<'tcx> {
45     Fn(Instance<'tcx>),
46     Static(DefId),
47     GlobalAsm(ItemId),
48 }
49
50 impl<'tcx> MonoItem<'tcx> {
51     /// Returns `true` if the mono item is user-defined (i.e. not compiler-generated, like shims).
52     pub fn is_user_defined(&self) -> bool {
53         match *self {
54             MonoItem::Fn(instance) => matches!(instance.def, InstanceDef::Item(..)),
55             MonoItem::Static(..) | MonoItem::GlobalAsm(..) => true,
56         }
57     }
58
59     pub fn size_estimate(&self, tcx: TyCtxt<'tcx>) -> usize {
60         match *self {
61             MonoItem::Fn(instance) => {
62                 // Estimate the size of a function based on how many statements
63                 // it contains.
64                 tcx.instance_def_size_estimate(instance.def)
65             }
66             // Conservatively estimate the size of a static declaration
67             // or assembly to be 1.
68             MonoItem::Static(_) | MonoItem::GlobalAsm(_) => 1,
69         }
70     }
71
72     pub fn is_generic_fn(&self) -> bool {
73         match *self {
74             MonoItem::Fn(ref instance) => instance.substs.non_erasable_generics().next().is_some(),
75             MonoItem::Static(..) | MonoItem::GlobalAsm(..) => false,
76         }
77     }
78
79     pub fn symbol_name(&self, tcx: TyCtxt<'tcx>) -> SymbolName<'tcx> {
80         match *self {
81             MonoItem::Fn(instance) => tcx.symbol_name(instance),
82             MonoItem::Static(def_id) => tcx.symbol_name(Instance::mono(tcx, def_id)),
83             MonoItem::GlobalAsm(item_id) => {
84                 SymbolName::new(tcx, &format!("global_asm_{:?}", item_id.def_id))
85             }
86         }
87     }
88
89     pub fn instantiation_mode(&self, tcx: TyCtxt<'tcx>) -> InstantiationMode {
90         let generate_cgu_internal_copies = tcx
91             .sess
92             .opts
93             .debugging_opts
94             .inline_in_all_cgus
95             .unwrap_or_else(|| tcx.sess.opts.optimize != OptLevel::No)
96             && !tcx.sess.link_dead_code();
97
98         match *self {
99             MonoItem::Fn(ref instance) => {
100                 let entry_def_id = tcx.entry_fn(()).map(|(id, _)| id);
101                 // If this function isn't inlined or otherwise has an extern
102                 // indicator, then we'll be creating a globally shared version.
103                 if tcx.codegen_fn_attrs(instance.def_id()).contains_extern_indicator()
104                     || !instance.def.generates_cgu_internal_copy(tcx)
105                     || Some(instance.def_id()) == entry_def_id
106                 {
107                     return InstantiationMode::GloballyShared { may_conflict: false };
108                 }
109
110                 // At this point we don't have explicit linkage and we're an
111                 // inlined function. If we're inlining into all CGUs then we'll
112                 // be creating a local copy per CGU.
113                 if generate_cgu_internal_copies {
114                     return InstantiationMode::LocalCopy;
115                 }
116
117                 // Finally, if this is `#[inline(always)]` we're sure to respect
118                 // that with an inline copy per CGU, but otherwise we'll be
119                 // creating one copy of this `#[inline]` function which may
120                 // conflict with upstream crates as it could be an exported
121                 // symbol.
122                 match tcx.codegen_fn_attrs(instance.def_id()).inline {
123                     InlineAttr::Always => InstantiationMode::LocalCopy,
124                     _ => InstantiationMode::GloballyShared { may_conflict: true },
125                 }
126             }
127             MonoItem::Static(..) | MonoItem::GlobalAsm(..) => {
128                 InstantiationMode::GloballyShared { may_conflict: false }
129             }
130         }
131     }
132
133     pub fn explicit_linkage(&self, tcx: TyCtxt<'tcx>) -> Option<Linkage> {
134         let def_id = match *self {
135             MonoItem::Fn(ref instance) => instance.def_id(),
136             MonoItem::Static(def_id) => def_id,
137             MonoItem::GlobalAsm(..) => return None,
138         };
139
140         let codegen_fn_attrs = tcx.codegen_fn_attrs(def_id);
141         codegen_fn_attrs.linkage
142     }
143
144     /// Returns `true` if this instance is instantiable - whether it has no unsatisfied
145     /// predicates.
146     ///
147     /// In order to codegen an item, all of its predicates must hold, because
148     /// otherwise the item does not make sense. Type-checking ensures that
149     /// the predicates of every item that is *used by* a valid item *do*
150     /// hold, so we can rely on that.
151     ///
152     /// However, we codegen collector roots (reachable items) and functions
153     /// in vtables when they are seen, even if they are not used, and so they
154     /// might not be instantiable. For example, a programmer can define this
155     /// public function:
156     ///
157     ///     pub fn foo<'a>(s: &'a mut ()) where &'a mut (): Clone {
158     ///         <&mut () as Clone>::clone(&s);
159     ///     }
160     ///
161     /// That function can't be codegened, because the method `<&mut () as Clone>::clone`
162     /// does not exist. Luckily for us, that function can't ever be used,
163     /// because that would require for `&'a mut (): Clone` to hold, so we
164     /// can just not emit any code, or even a linker reference for it.
165     ///
166     /// Similarly, if a vtable method has such a signature, and therefore can't
167     /// be used, we can just not emit it and have a placeholder (a null pointer,
168     /// which will never be accessed) in its place.
169     pub fn is_instantiable(&self, tcx: TyCtxt<'tcx>) -> bool {
170         debug!("is_instantiable({:?})", self);
171         let (def_id, substs) = match *self {
172             MonoItem::Fn(ref instance) => (instance.def_id(), instance.substs),
173             MonoItem::Static(def_id) => (def_id, InternalSubsts::empty()),
174             // global asm never has predicates
175             MonoItem::GlobalAsm(..) => return true,
176         };
177
178         !tcx.subst_and_check_impossible_predicates((def_id, &substs))
179     }
180
181     pub fn local_span(&self, tcx: TyCtxt<'tcx>) -> Option<Span> {
182         match *self {
183             MonoItem::Fn(Instance { def, .. }) => def.def_id().as_local(),
184             MonoItem::Static(def_id) => def_id.as_local(),
185             MonoItem::GlobalAsm(item_id) => Some(item_id.def_id),
186         }
187         .map(|def_id| tcx.def_span(def_id))
188     }
189
190     // Only used by rustc_codegen_cranelift
191     pub fn codegen_dep_node(&self, tcx: TyCtxt<'tcx>) -> DepNode {
192         crate::dep_graph::make_compile_mono_item(tcx, self)
193     }
194
195     /// Returns the item's `CrateNum`
196     pub fn krate(&self) -> CrateNum {
197         match self {
198             MonoItem::Fn(ref instance) => instance.def_id().krate,
199             MonoItem::Static(def_id) => def_id.krate,
200             MonoItem::GlobalAsm(..) => LOCAL_CRATE,
201         }
202     }
203 }
204
205 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for MonoItem<'tcx> {
206     fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
207         ::std::mem::discriminant(self).hash_stable(hcx, hasher);
208
209         match *self {
210             MonoItem::Fn(ref instance) => {
211                 instance.hash_stable(hcx, hasher);
212             }
213             MonoItem::Static(def_id) => {
214                 def_id.hash_stable(hcx, hasher);
215             }
216             MonoItem::GlobalAsm(item_id) => {
217                 hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
218                     item_id.hash_stable(hcx, hasher);
219                 })
220             }
221         }
222     }
223 }
224
225 impl<'tcx> fmt::Display for MonoItem<'tcx> {
226     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
227         match *self {
228             MonoItem::Fn(instance) => write!(f, "fn {}", instance),
229             MonoItem::Static(def_id) => {
230                 write!(f, "static {}", Instance::new(def_id, InternalSubsts::empty()))
231             }
232             MonoItem::GlobalAsm(..) => write!(f, "global_asm"),
233         }
234     }
235 }
236
237 #[derive(Debug)]
238 pub struct CodegenUnit<'tcx> {
239     /// A name for this CGU. Incremental compilation requires that
240     /// name be unique amongst **all** crates. Therefore, it should
241     /// contain something unique to this crate (e.g., a module path)
242     /// as well as the crate name and disambiguator.
243     name: Symbol,
244     items: FxHashMap<MonoItem<'tcx>, (Linkage, Visibility)>,
245     size_estimate: Option<usize>,
246     primary: bool,
247     /// True if this is CGU is used to hold code coverage information for dead code,
248     /// false otherwise.
249     is_code_coverage_dead_code_cgu: bool,
250 }
251
252 /// Specifies the linkage type for a `MonoItem`.
253 ///
254 /// See <https://llvm.org/docs/LangRef.html#linkage-types> for more details about these variants.
255 #[derive(Copy, Clone, PartialEq, Debug, TyEncodable, TyDecodable, HashStable)]
256 pub enum Linkage {
257     External,
258     AvailableExternally,
259     LinkOnceAny,
260     LinkOnceODR,
261     WeakAny,
262     WeakODR,
263     Appending,
264     Internal,
265     Private,
266     ExternalWeak,
267     Common,
268 }
269
270 #[derive(Copy, Clone, PartialEq, Debug, HashStable)]
271 pub enum Visibility {
272     Default,
273     Hidden,
274     Protected,
275 }
276
277 impl<'tcx> CodegenUnit<'tcx> {
278     #[inline]
279     pub fn new(name: Symbol) -> CodegenUnit<'tcx> {
280         CodegenUnit {
281             name,
282             items: Default::default(),
283             size_estimate: None,
284             primary: false,
285             is_code_coverage_dead_code_cgu: false,
286         }
287     }
288
289     pub fn name(&self) -> Symbol {
290         self.name
291     }
292
293     pub fn set_name(&mut self, name: Symbol) {
294         self.name = name;
295     }
296
297     pub fn is_primary(&self) -> bool {
298         self.primary
299     }
300
301     pub fn make_primary(&mut self) {
302         self.primary = true;
303     }
304
305     pub fn items(&self) -> &FxHashMap<MonoItem<'tcx>, (Linkage, Visibility)> {
306         &self.items
307     }
308
309     pub fn items_mut(&mut self) -> &mut FxHashMap<MonoItem<'tcx>, (Linkage, Visibility)> {
310         &mut self.items
311     }
312
313     pub fn is_code_coverage_dead_code_cgu(&self) -> bool {
314         self.is_code_coverage_dead_code_cgu
315     }
316
317     /// Marks this CGU as the one used to contain code coverage information for dead code.
318     pub fn make_code_coverage_dead_code_cgu(&mut self) {
319         self.is_code_coverage_dead_code_cgu = true;
320     }
321
322     pub fn mangle_name(human_readable_name: &str) -> String {
323         // We generate a 80 bit hash from the name. This should be enough to
324         // avoid collisions and is still reasonably short for filenames.
325         let mut hasher = StableHasher::new();
326         human_readable_name.hash(&mut hasher);
327         let hash: u128 = hasher.finish();
328         let hash = hash & ((1u128 << 80) - 1);
329         base_n::encode(hash, base_n::CASE_INSENSITIVE)
330     }
331
332     pub fn estimate_size(&mut self, tcx: TyCtxt<'tcx>) {
333         // Estimate the size of a codegen unit as (approximately) the number of MIR
334         // statements it corresponds to.
335         self.size_estimate = Some(self.items.keys().map(|mi| mi.size_estimate(tcx)).sum());
336     }
337
338     #[inline]
339     pub fn size_estimate(&self) -> usize {
340         // Should only be called if `estimate_size` has previously been called.
341         self.size_estimate.expect("estimate_size must be called before getting a size_estimate")
342     }
343
344     pub fn modify_size_estimate(&mut self, delta: usize) {
345         assert!(self.size_estimate.is_some());
346         if let Some(size_estimate) = self.size_estimate {
347             self.size_estimate = Some(size_estimate + delta);
348         }
349     }
350
351     pub fn contains_item(&self, item: &MonoItem<'tcx>) -> bool {
352         self.items().contains_key(item)
353     }
354
355     pub fn work_product_id(&self) -> WorkProductId {
356         WorkProductId::from_cgu_name(self.name().as_str())
357     }
358
359     pub fn work_product(&self, tcx: TyCtxt<'_>) -> WorkProduct {
360         let work_product_id = self.work_product_id();
361         tcx.dep_graph
362             .previous_work_product(&work_product_id)
363             .unwrap_or_else(|| panic!("Could not find work-product for CGU `{}`", self.name()))
364     }
365
366     pub fn items_in_deterministic_order(
367         &self,
368         tcx: TyCtxt<'tcx>,
369     ) -> Vec<(MonoItem<'tcx>, (Linkage, Visibility))> {
370         // The codegen tests rely on items being process in the same order as
371         // they appear in the file, so for local items, we sort by node_id first
372         #[derive(PartialEq, Eq, PartialOrd, Ord)]
373         pub struct ItemSortKey<'tcx>(Option<usize>, SymbolName<'tcx>);
374
375         fn item_sort_key<'tcx>(tcx: TyCtxt<'tcx>, item: MonoItem<'tcx>) -> ItemSortKey<'tcx> {
376             ItemSortKey(
377                 match item {
378                     MonoItem::Fn(ref instance) => {
379                         match instance.def {
380                             // We only want to take HirIds of user-defined
381                             // instances into account. The others don't matter for
382                             // the codegen tests and can even make item order
383                             // unstable.
384                             InstanceDef::Item(def) => def.did.as_local().map(Idx::index),
385                             InstanceDef::VtableShim(..)
386                             | InstanceDef::ReifyShim(..)
387                             | InstanceDef::Intrinsic(..)
388                             | InstanceDef::FnPtrShim(..)
389                             | InstanceDef::Virtual(..)
390                             | InstanceDef::ClosureOnceShim { .. }
391                             | InstanceDef::DropGlue(..)
392                             | InstanceDef::CloneShim(..) => None,
393                         }
394                     }
395                     MonoItem::Static(def_id) => def_id.as_local().map(Idx::index),
396                     MonoItem::GlobalAsm(item_id) => Some(item_id.def_id.index()),
397                 },
398                 item.symbol_name(tcx),
399             )
400         }
401
402         let mut items: Vec<_> = self.items().iter().map(|(&i, &l)| (i, l)).collect();
403         items.sort_by_cached_key(|&(i, _)| item_sort_key(tcx, i));
404         items
405     }
406
407     pub fn codegen_dep_node(&self, tcx: TyCtxt<'tcx>) -> DepNode {
408         crate::dep_graph::make_compile_codegen_unit(tcx, self.name())
409     }
410 }
411
412 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for CodegenUnit<'tcx> {
413     fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
414         let CodegenUnit {
415             ref items,
416             name,
417             // The size estimate is not relevant to the hash
418             size_estimate: _,
419             primary: _,
420             is_code_coverage_dead_code_cgu,
421         } = *self;
422
423         name.hash_stable(hcx, hasher);
424         is_code_coverage_dead_code_cgu.hash_stable(hcx, hasher);
425
426         let mut items: Vec<(Fingerprint, _)> = items
427             .iter()
428             .map(|(mono_item, &attrs)| {
429                 let mut hasher = StableHasher::new();
430                 mono_item.hash_stable(hcx, &mut hasher);
431                 let mono_item_fingerprint = hasher.finish();
432                 (mono_item_fingerprint, attrs)
433             })
434             .collect();
435
436         items.sort_unstable_by_key(|i| i.0);
437         items.hash_stable(hcx, hasher);
438     }
439 }
440
441 pub struct CodegenUnitNameBuilder<'tcx> {
442     tcx: TyCtxt<'tcx>,
443     cache: FxHashMap<CrateNum, String>,
444 }
445
446 impl<'tcx> CodegenUnitNameBuilder<'tcx> {
447     pub fn new(tcx: TyCtxt<'tcx>) -> Self {
448         CodegenUnitNameBuilder { tcx, cache: Default::default() }
449     }
450
451     /// CGU names should fulfill the following requirements:
452     /// - They should be able to act as a file name on any kind of file system
453     /// - They should not collide with other CGU names, even for different versions
454     ///   of the same crate.
455     ///
456     /// Consequently, we don't use special characters except for '.' and '-' and we
457     /// prefix each name with the crate-name and crate-disambiguator.
458     ///
459     /// This function will build CGU names of the form:
460     ///
461     /// ```
462     /// <crate-name>.<crate-disambiguator>[-in-<local-crate-id>](-<component>)*[.<special-suffix>]
463     /// <local-crate-id> = <local-crate-name>.<local-crate-disambiguator>
464     /// ```
465     ///
466     /// The '.' before `<special-suffix>` makes sure that names with a special
467     /// suffix can never collide with a name built out of regular Rust
468     /// identifiers (e.g., module paths).
469     pub fn build_cgu_name<I, C, S>(
470         &mut self,
471         cnum: CrateNum,
472         components: I,
473         special_suffix: Option<S>,
474     ) -> Symbol
475     where
476         I: IntoIterator<Item = C>,
477         C: fmt::Display,
478         S: fmt::Display,
479     {
480         let cgu_name = self.build_cgu_name_no_mangle(cnum, components, special_suffix);
481
482         if self.tcx.sess.opts.debugging_opts.human_readable_cgu_names {
483             cgu_name
484         } else {
485             Symbol::intern(&CodegenUnit::mangle_name(cgu_name.as_str()))
486         }
487     }
488
489     /// Same as `CodegenUnit::build_cgu_name()` but will never mangle the
490     /// resulting name.
491     pub fn build_cgu_name_no_mangle<I, C, S>(
492         &mut self,
493         cnum: CrateNum,
494         components: I,
495         special_suffix: Option<S>,
496     ) -> Symbol
497     where
498         I: IntoIterator<Item = C>,
499         C: fmt::Display,
500         S: fmt::Display,
501     {
502         use std::fmt::Write;
503
504         let mut cgu_name = String::with_capacity(64);
505
506         // Start out with the crate name and disambiguator
507         let tcx = self.tcx;
508         let crate_prefix = self.cache.entry(cnum).or_insert_with(|| {
509             // Whenever the cnum is not LOCAL_CRATE we also mix in the
510             // local crate's ID. Otherwise there can be collisions between CGUs
511             // instantiating stuff for upstream crates.
512             let local_crate_id = if cnum != LOCAL_CRATE {
513                 let local_stable_crate_id = tcx.sess.local_stable_crate_id();
514                 format!(
515                     "-in-{}.{:08x}",
516                     tcx.crate_name(LOCAL_CRATE),
517                     local_stable_crate_id.to_u64() as u32,
518                 )
519             } else {
520                 String::new()
521             };
522
523             let stable_crate_id = tcx.sess.local_stable_crate_id();
524             format!(
525                 "{}.{:08x}{}",
526                 tcx.crate_name(cnum),
527                 stable_crate_id.to_u64() as u32,
528                 local_crate_id,
529             )
530         });
531
532         write!(cgu_name, "{}", crate_prefix).unwrap();
533
534         // Add the components
535         for component in components {
536             write!(cgu_name, "-{}", component).unwrap();
537         }
538
539         if let Some(special_suffix) = special_suffix {
540             // We add a dot in here so it cannot clash with anything in a regular
541             // Rust identifier
542             write!(cgu_name, ".{}", special_suffix).unwrap();
543         }
544
545         Symbol::intern(&cgu_name)
546     }
547 }