]> git.lizzy.rs Git - rust.git/blob - src/librustc/mir/mono.rs
Rollup merge of #66060 - traxys:test_65401, r=michaelwoerister
[rust.git] / src / librustc / mir / mono.rs
1 use crate::hir::def_id::{DefId, CrateNum, LOCAL_CRATE};
2 use crate::hir::HirId;
3 use syntax::symbol::Symbol;
4 use syntax::attr::InlineAttr;
5 use syntax::source_map::Span;
6 use crate::ty::{Instance, InstanceDef, TyCtxt, SymbolName, subst::InternalSubsts};
7 use crate::util::nodemap::FxHashMap;
8 use crate::ty::print::obsolete::DefPathBasedNames;
9 use crate::dep_graph::{WorkProductId, DepNode, WorkProduct, DepConstructor};
10 use rustc_data_structures::base_n;
11 use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
12 use crate::ich::{Fingerprint, StableHashingContext, NodeIdHashingMode};
13 use crate::session::config::OptLevel;
14 use std::fmt;
15 use std::hash::Hash;
16
17 /// Describes how a monomorphization will be instantiated in object files.
18 #[derive(PartialEq)]
19 pub enum InstantiationMode {
20     /// There will be exactly one instance of the given MonoItem. It will have
21     /// external linkage so that it can be linked to from other codegen units.
22     GloballyShared {
23         /// In some compilation scenarios we may decide to take functions that
24         /// are typically `LocalCopy` and instead move them to `GloballyShared`
25         /// to avoid codegenning them a bunch of times. In this situation,
26         /// however, our local copy may conflict with other crates also
27         /// inlining the same function.
28         ///
29         /// This flag indicates that this situation is occurring, and informs
30         /// symbol name calculation that some extra mangling is needed to
31         /// avoid conflicts. Note that this may eventually go away entirely if
32         /// ThinLTO enables us to *always* have a globally shared instance of a
33         /// function within one crate's compilation.
34         may_conflict: bool,
35     },
36
37     /// Each codegen unit containing a reference to the given MonoItem will
38     /// have its own private copy of the function (with internal linkage).
39     LocalCopy,
40 }
41
42 #[derive(PartialEq, Eq, Clone, Copy, Debug, Hash)]
43 pub enum MonoItem<'tcx> {
44     Fn(Instance<'tcx>),
45     Static(DefId),
46     GlobalAsm(HirId),
47 }
48
49 impl<'tcx> MonoItem<'tcx> {
50     pub fn size_estimate(&self, tcx: TyCtxt<'tcx>) -> usize {
51         match *self {
52             MonoItem::Fn(instance) => {
53                 // Estimate the size of a function based on how many statements
54                 // it contains.
55                 tcx.instance_def_size_estimate(instance.def)
56             },
57             // Conservatively estimate the size of a static declaration
58             // or assembly to be 1.
59             MonoItem::Static(_) |
60             MonoItem::GlobalAsm(_) => 1,
61         }
62     }
63
64     pub fn is_generic_fn(&self) -> bool {
65         match *self {
66             MonoItem::Fn(ref instance) => {
67                 instance.substs.non_erasable_generics().next().is_some()
68             }
69             MonoItem::Static(..) |
70             MonoItem::GlobalAsm(..) => false,
71         }
72     }
73
74     pub fn symbol_name(&self, tcx: TyCtxt<'tcx>) -> SymbolName {
75         match *self {
76             MonoItem::Fn(instance) => tcx.symbol_name(instance),
77             MonoItem::Static(def_id) => {
78                 tcx.symbol_name(Instance::mono(tcx, def_id))
79             }
80             MonoItem::GlobalAsm(hir_id) => {
81                 let def_id = tcx.hir().local_def_id(hir_id);
82                 SymbolName {
83                     name: Symbol::intern(&format!("global_asm_{:?}", def_id))
84                 }
85             }
86         }
87     }
88
89     pub fn instantiation_mode(&self, tcx: TyCtxt<'tcx>) -> InstantiationMode {
90         let inline_in_all_cgus =
91             tcx.sess.opts.debugging_opts.inline_in_all_cgus.unwrap_or_else(|| {
92                 tcx.sess.opts.optimize != OptLevel::No
93             }) && !tcx.sess.opts.cg.link_dead_code;
94
95         match *self {
96             MonoItem::Fn(ref instance) => {
97                 let entry_def_id = tcx.entry_fn(LOCAL_CRATE).map(|(id, _)| id);
98                 // If this function isn't inlined or otherwise has explicit
99                 // linkage, then we'll be creating a globally shared version.
100                 if self.explicit_linkage(tcx).is_some() ||
101                     !instance.def.requires_local(tcx) ||
102                     Some(instance.def_id()) == entry_def_id
103                 {
104                     return InstantiationMode::GloballyShared  { may_conflict: false }
105                 }
106
107                 // At this point we don't have explicit linkage and we're an
108                 // inlined function. If we're inlining into all CGUs then we'll
109                 // be creating a local copy per CGU
110                 if inline_in_all_cgus {
111                     return InstantiationMode::LocalCopy
112                 }
113
114                 // Finally, if this is `#[inline(always)]` we're sure to respect
115                 // that with an inline copy per CGU, but otherwise we'll be
116                 // creating one copy of this `#[inline]` function which may
117                 // conflict with upstream crates as it could be an exported
118                 // symbol.
119                 match tcx.codegen_fn_attrs(instance.def_id()).inline {
120                     InlineAttr::Always => InstantiationMode::LocalCopy,
121                     _ => {
122                         InstantiationMode::GloballyShared  { may_conflict: true }
123                     }
124                 }
125             }
126             MonoItem::Static(..) |
127             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.substitute_normalize_and_test_predicates((def_id, &substs))
179     }
180
181     pub fn to_string(&self, tcx: TyCtxt<'tcx>, debug: bool) -> String {
182         return match *self {
183             MonoItem::Fn(instance) => {
184                 to_string_internal(tcx, "fn ", instance, debug)
185             },
186             MonoItem::Static(def_id) => {
187                 let instance = Instance::new(def_id, tcx.intern_substs(&[]));
188                 to_string_internal(tcx, "static ", instance, debug)
189             },
190             MonoItem::GlobalAsm(..) => {
191                 "global_asm".to_string()
192             }
193         };
194
195         fn to_string_internal<'tcx>(
196             tcx: TyCtxt<'tcx>,
197             prefix: &str,
198             instance: Instance<'tcx>,
199             debug: bool,
200         ) -> String {
201             let mut result = String::with_capacity(32);
202             result.push_str(prefix);
203             let printer = DefPathBasedNames::new(tcx, false, false);
204             printer.push_instance_as_string(instance, &mut result, debug);
205             result
206         }
207     }
208
209     pub fn local_span(&self, tcx: TyCtxt<'tcx>) -> Option<Span> {
210         match *self {
211             MonoItem::Fn(Instance { def, .. }) => {
212                 tcx.hir().as_local_hir_id(def.def_id())
213             }
214             MonoItem::Static(def_id) => {
215                 tcx.hir().as_local_hir_id(def_id)
216             }
217             MonoItem::GlobalAsm(hir_id) => {
218                 Some(hir_id)
219             }
220         }.map(|hir_id| tcx.hir().span(hir_id))
221     }
222 }
223
224 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for MonoItem<'tcx> {
225     fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
226         ::std::mem::discriminant(self).hash_stable(hcx, hasher);
227
228         match *self {
229             MonoItem::Fn(ref instance) => {
230                 instance.hash_stable(hcx, hasher);
231             }
232             MonoItem::Static(def_id) => {
233                 def_id.hash_stable(hcx, hasher);
234             }
235             MonoItem::GlobalAsm(node_id) => {
236                 hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| {
237                     node_id.hash_stable(hcx, hasher);
238                 })
239             }
240         }
241     }
242 }
243
244 pub struct CodegenUnit<'tcx> {
245     /// A name for this CGU. Incremental compilation requires that
246     /// name be unique amongst **all** crates. Therefore, it should
247     /// contain something unique to this crate (e.g., a module path)
248     /// as well as the crate name and disambiguator.
249     name: Symbol,
250     items: FxHashMap<MonoItem<'tcx>, (Linkage, Visibility)>,
251     size_estimate: Option<usize>,
252 }
253
254 #[derive(Copy, Clone, PartialEq, Debug, RustcEncodable, RustcDecodable)]
255 pub enum Linkage {
256     External,
257     AvailableExternally,
258     LinkOnceAny,
259     LinkOnceODR,
260     WeakAny,
261     WeakODR,
262     Appending,
263     Internal,
264     Private,
265     ExternalWeak,
266     Common,
267 }
268
269 impl_stable_hash_for!(enum self::Linkage {
270     External,
271     AvailableExternally,
272     LinkOnceAny,
273     LinkOnceODR,
274     WeakAny,
275     WeakODR,
276     Appending,
277     Internal,
278     Private,
279     ExternalWeak,
280     Common
281 });
282
283 #[derive(Copy, Clone, PartialEq, Debug)]
284 pub enum Visibility {
285     Default,
286     Hidden,
287     Protected,
288 }
289
290 impl_stable_hash_for!(enum self::Visibility {
291     Default,
292     Hidden,
293     Protected
294 });
295
296 impl<'tcx> CodegenUnit<'tcx> {
297     pub fn new(name: Symbol) -> CodegenUnit<'tcx> {
298         CodegenUnit {
299             name: name,
300             items: Default::default(),
301             size_estimate: None,
302         }
303     }
304
305     pub fn name(&self) -> Symbol {
306         self.name
307     }
308
309     pub fn set_name(&mut self, name: Symbol) {
310         self.name = name;
311     }
312
313     pub fn items(&self) -> &FxHashMap<MonoItem<'tcx>, (Linkage, Visibility)> {
314         &self.items
315     }
316
317     pub fn items_mut(&mut self)
318         -> &mut FxHashMap<MonoItem<'tcx>, (Linkage, Visibility)>
319     {
320         &mut self.items
321     }
322
323     pub fn mangle_name(human_readable_name: &str) -> String {
324         // We generate a 80 bit hash from the name. This should be enough to
325         // avoid collisions and is still reasonably short for filenames.
326         let mut hasher = StableHasher::new();
327         human_readable_name.hash(&mut hasher);
328         let hash: u128 = hasher.finish();
329         let hash = hash & ((1u128 << 80) - 1);
330         base_n::encode(hash, base_n::CASE_INSENSITIVE)
331     }
332
333     pub fn estimate_size(&mut self, tcx: TyCtxt<'tcx>) {
334         // Estimate the size of a codegen unit as (approximately) the number of MIR
335         // statements it corresponds to.
336         self.size_estimate = Some(self.items.keys().map(|mi| mi.size_estimate(tcx)).sum());
337     }
338
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(|| {
364                 panic!("Could not find work-product for CGU `{}`", self.name())
365             })
366     }
367
368     pub fn items_in_deterministic_order(
369         &self,
370         tcx: TyCtxt<'tcx>,
371     ) -> Vec<(MonoItem<'tcx>, (Linkage, Visibility))> {
372         // The codegen tests rely on items being process in the same order as
373         // they appear in the file, so for local items, we sort by node_id first
374         #[derive(PartialEq, Eq, PartialOrd, Ord)]
375         pub struct ItemSortKey(Option<HirId>, SymbolName);
376
377         fn item_sort_key<'tcx>(tcx: TyCtxt<'tcx>, item: MonoItem<'tcx>) -> ItemSortKey {
378             ItemSortKey(match item {
379                 MonoItem::Fn(ref instance) => {
380                     match instance.def {
381                         // We only want to take HirIds of user-defined
382                         // instances into account. The others don't matter for
383                         // the codegen tests and can even make item order
384                         // unstable.
385                         InstanceDef::Item(def_id) => {
386                             tcx.hir().as_local_hir_id(def_id)
387                         }
388                         InstanceDef::VtableShim(..) |
389                         InstanceDef::ReifyShim(..) |
390                         InstanceDef::Intrinsic(..) |
391                         InstanceDef::FnPtrShim(..) |
392                         InstanceDef::Virtual(..) |
393                         InstanceDef::ClosureOnceShim { .. } |
394                         InstanceDef::DropGlue(..) |
395                         InstanceDef::CloneShim(..) => {
396                             None
397                         }
398                     }
399                 }
400                 MonoItem::Static(def_id) => {
401                     tcx.hir().as_local_hir_id(def_id)
402                 }
403                 MonoItem::GlobalAsm(hir_id) => {
404                     Some(hir_id)
405                 }
406             }, item.symbol_name(tcx))
407         }
408
409         let mut items: Vec<_> = self.items().iter().map(|(&i, &l)| (i, l)).collect();
410         items.sort_by_cached_key(|&(i, _)| item_sort_key(tcx, i));
411         items
412     }
413
414     pub fn codegen_dep_node(&self, tcx: TyCtxt<'tcx>) -> DepNode {
415         DepNode::new(tcx, DepConstructor::CompileCodegenUnit(self.name().clone()))
416     }
417 }
418
419 impl<'a, 'tcx> HashStable<StableHashingContext<'a>> for CodegenUnit<'tcx> {
420     fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) {
421         let CodegenUnit {
422             ref items,
423             name,
424             // The size estimate is not relevant to the hash
425             size_estimate: _,
426         } = *self;
427
428         name.hash_stable(hcx, hasher);
429
430         let mut items: Vec<(Fingerprint, _)> = items.iter().map(|(mono_item, &attrs)| {
431             let mut hasher = StableHasher::new();
432             mono_item.hash_stable(hcx, &mut hasher);
433             let mono_item_fingerprint = hasher.finish();
434             (mono_item_fingerprint, attrs)
435         }).collect();
436
437         items.sort_unstable_by_key(|i| i.0);
438         items.hash_stable(hcx, hasher);
439     }
440 }
441
442 pub struct CodegenUnitNameBuilder<'tcx> {
443     tcx: TyCtxt<'tcx>,
444     cache: FxHashMap<CrateNum, String>,
445 }
446
447 impl CodegenUnitNameBuilder<'tcx> {
448     pub fn new(tcx: TyCtxt<'tcx>) -> Self {
449         CodegenUnitNameBuilder {
450             tcx,
451             cache: Default::default(),
452         }
453     }
454
455     /// CGU names should fulfill the following requirements:
456     /// - They should be able to act as a file name on any kind of file system
457     /// - They should not collide with other CGU names, even for different versions
458     ///   of the same crate.
459     ///
460     /// Consequently, we don't use special characters except for '.' and '-' and we
461     /// prefix each name with the crate-name and crate-disambiguator.
462     ///
463     /// This function will build CGU names of the form:
464     ///
465     /// ```
466     /// <crate-name>.<crate-disambiguator>[-in-<local-crate-id>](-<component>)*[.<special-suffix>]
467     /// <local-crate-id> = <local-crate-name>.<local-crate-disambiguator>
468     /// ```
469     ///
470     /// The '.' before `<special-suffix>` makes sure that names with a special
471     /// suffix can never collide with a name built out of regular Rust
472     /// identifiers (e.g., module paths).
473     pub fn build_cgu_name<I, C, S>(&mut self,
474                                    cnum: CrateNum,
475                                    components: I,
476                                    special_suffix: Option<S>)
477                                    -> Symbol
478         where I: IntoIterator<Item=C>,
479               C: fmt::Display,
480               S: fmt::Display,
481     {
482         let cgu_name = self.build_cgu_name_no_mangle(cnum,
483                                                      components,
484                                                      special_suffix);
485
486         if self.tcx.sess.opts.debugging_opts.human_readable_cgu_names {
487             cgu_name
488         } else {
489             let cgu_name = &cgu_name.as_str();
490             Symbol::intern(&CodegenUnit::mangle_name(cgu_name))
491         }
492     }
493
494     /// Same as `CodegenUnit::build_cgu_name()` but will never mangle the
495     /// resulting name.
496     pub fn build_cgu_name_no_mangle<I, C, S>(&mut self,
497                                              cnum: CrateNum,
498                                              components: I,
499                                              special_suffix: Option<S>)
500                                              -> Symbol
501         where I: IntoIterator<Item=C>,
502               C: fmt::Display,
503               S: fmt::Display,
504     {
505         use std::fmt::Write;
506
507         let mut cgu_name = String::with_capacity(64);
508
509         // Start out with the crate name and disambiguator
510         let tcx = self.tcx;
511         let crate_prefix = self.cache.entry(cnum).or_insert_with(|| {
512             // Whenever the cnum is not LOCAL_CRATE we also mix in the
513             // local crate's ID. Otherwise there can be collisions between CGUs
514             // instantiating stuff for upstream crates.
515             let local_crate_id = if cnum != LOCAL_CRATE {
516                 let local_crate_disambiguator =
517                     format!("{}", tcx.crate_disambiguator(LOCAL_CRATE));
518                 format!("-in-{}.{}",
519                         tcx.crate_name(LOCAL_CRATE),
520                         &local_crate_disambiguator[0 .. 8])
521             } else {
522                 String::new()
523             };
524
525             let crate_disambiguator = tcx.crate_disambiguator(cnum).to_string();
526             // Using a shortened disambiguator of about 40 bits
527             format!("{}.{}{}",
528                 tcx.crate_name(cnum),
529                 &crate_disambiguator[0 .. 8],
530                 local_crate_id)
531         });
532
533         write!(cgu_name, "{}", crate_prefix).unwrap();
534
535         // Add the components
536         for component in components {
537             write!(cgu_name, "-{}", component).unwrap();
538         }
539
540         if let Some(special_suffix) = special_suffix {
541             // We add a dot in here so it cannot clash with anything in a regular
542             // Rust identifier
543             write!(cgu_name, ".{}", special_suffix).unwrap();
544         }
545
546         Symbol::intern(&cgu_name[..])
547     }
548 }