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