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