]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/monomorphize/partitioning.rs
Rollup merge of #65417 - weiznich:more_coherence_tests, r=nikomatsakis
[rust.git] / src / librustc_mir / monomorphize / partitioning.rs
1 //! Partitioning Codegen Units for Incremental Compilation
2 //! ======================================================
3 //!
4 //! The task of this module is to take the complete set of monomorphizations of
5 //! a crate and produce a set of codegen units from it, where a codegen unit
6 //! is a named set of (mono-item, linkage) pairs. That is, this module
7 //! decides which monomorphization appears in which codegen units with which
8 //! linkage. The following paragraphs describe some of the background on the
9 //! partitioning scheme.
10 //!
11 //! The most important opportunity for saving on compilation time with
12 //! incremental compilation is to avoid re-codegenning and re-optimizing code.
13 //! Since the unit of codegen and optimization for LLVM is "modules" or, how
14 //! we call them "codegen units", the particulars of how much time can be saved
15 //! by incremental compilation are tightly linked to how the output program is
16 //! partitioned into these codegen units prior to passing it to LLVM --
17 //! especially because we have to treat codegen units as opaque entities once
18 //! they are created: There is no way for us to incrementally update an existing
19 //! LLVM module and so we have to build any such module from scratch if it was
20 //! affected by some change in the source code.
21 //!
22 //! From that point of view it would make sense to maximize the number of
23 //! codegen units by, for example, putting each function into its own module.
24 //! That way only those modules would have to be re-compiled that were actually
25 //! affected by some change, minimizing the number of functions that could have
26 //! been re-used but just happened to be located in a module that is
27 //! re-compiled.
28 //!
29 //! However, since LLVM optimization does not work across module boundaries,
30 //! using such a highly granular partitioning would lead to very slow runtime
31 //! code since it would effectively prohibit inlining and other inter-procedure
32 //! optimizations. We want to avoid that as much as possible.
33 //!
34 //! Thus we end up with a trade-off: The bigger the codegen units, the better
35 //! LLVM's optimizer can do its work, but also the smaller the compilation time
36 //! reduction we get from incremental compilation.
37 //!
38 //! Ideally, we would create a partitioning such that there are few big codegen
39 //! units with few interdependencies between them. For now though, we use the
40 //! following heuristic to determine the partitioning:
41 //!
42 //! - There are two codegen units for every source-level module:
43 //! - One for "stable", that is non-generic, code
44 //! - One for more "volatile" code, i.e., monomorphized instances of functions
45 //!   defined in that module
46 //!
47 //! In order to see why this heuristic makes sense, let's take a look at when a
48 //! codegen unit can get invalidated:
49 //!
50 //! 1. The most straightforward case is when the BODY of a function or global
51 //! changes. Then any codegen unit containing the code for that item has to be
52 //! re-compiled. Note that this includes all codegen units where the function
53 //! has been inlined.
54 //!
55 //! 2. The next case is when the SIGNATURE of a function or global changes. In
56 //! this case, all codegen units containing a REFERENCE to that item have to be
57 //! re-compiled. This is a superset of case 1.
58 //!
59 //! 3. The final and most subtle case is when a REFERENCE to a generic function
60 //! is added or removed somewhere. Even though the definition of the function
61 //! might be unchanged, a new REFERENCE might introduce a new monomorphized
62 //! instance of this function which has to be placed and compiled somewhere.
63 //! Conversely, when removing a REFERENCE, it might have been the last one with
64 //! that particular set of generic arguments and thus we have to remove it.
65 //!
66 //! From the above we see that just using one codegen unit per source-level
67 //! module is not such a good idea, since just adding a REFERENCE to some
68 //! generic item somewhere else would invalidate everything within the module
69 //! containing the generic item. The heuristic above reduces this detrimental
70 //! side-effect of references a little by at least not touching the non-generic
71 //! code of the module.
72 //!
73 //! A Note on Inlining
74 //! ------------------
75 //! As briefly mentioned above, in order for LLVM to be able to inline a
76 //! function call, the body of the function has to be available in the LLVM
77 //! module where the call is made. This has a few consequences for partitioning:
78 //!
79 //! - The partitioning algorithm has to take care of placing functions into all
80 //!   codegen units where they should be available for inlining. It also has to
81 //!   decide on the correct linkage for these functions.
82 //!
83 //! - The partitioning algorithm has to know which functions are likely to get
84 //!   inlined, so it can distribute function instantiations accordingly. Since
85 //!   there is no way of knowing for sure which functions LLVM will decide to
86 //!   inline in the end, we apply a heuristic here: Only functions marked with
87 //!   `#[inline]` are considered for inlining by the partitioner. The current
88 //!   implementation will not try to determine if a function is likely to be
89 //!   inlined by looking at the functions definition.
90 //!
91 //! Note though that as a side-effect of creating a codegen units per
92 //! source-level module, functions from the same module will be available for
93 //! inlining, even when they are not marked `#[inline]`.
94
95 use std::collections::hash_map::Entry;
96 use std::cmp;
97 use std::sync::Arc;
98
99 use syntax::symbol::InternedString;
100 use rustc::hir::CodegenFnAttrFlags;
101 use rustc::hir::def::DefKind;
102 use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE, CRATE_DEF_INDEX};
103 use rustc::mir::mono::{Linkage, Visibility, CodegenUnitNameBuilder, CodegenUnit};
104 use rustc::middle::exported_symbols::SymbolExportLevel;
105 use rustc::ty::{self, DefIdTree, TyCtxt, InstanceDef};
106 use rustc::ty::print::characteristic_def_id_of_type;
107 use rustc::ty::query::Providers;
108 use rustc::util::common::time;
109 use rustc::util::nodemap::{DefIdSet, FxHashMap, FxHashSet};
110 use rustc::mir::mono::{MonoItem, InstantiationMode};
111
112 use crate::monomorphize::collector::InliningMap;
113 use crate::monomorphize::collector::{self, MonoItemCollectionMode};
114
115 pub enum PartitioningStrategy {
116     /// Generates one codegen unit per source-level module.
117     PerModule,
118
119     /// Partition the whole crate into a fixed number of codegen units.
120     FixedUnitCount(usize)
121 }
122
123 // Anything we can't find a proper codegen unit for goes into this.
124 fn fallback_cgu_name(name_builder: &mut CodegenUnitNameBuilder<'_>) -> InternedString {
125     name_builder.build_cgu_name(LOCAL_CRATE, &["fallback"], Some("cgu"))
126 }
127
128 pub fn partition<'tcx, I>(
129     tcx: TyCtxt<'tcx>,
130     mono_items: I,
131     strategy: PartitioningStrategy,
132     inlining_map: &InliningMap<'tcx>,
133 ) -> Vec<CodegenUnit<'tcx>>
134 where
135     I: Iterator<Item = MonoItem<'tcx>>,
136 {
137     let _prof_timer = tcx.prof.generic_activity("cgu_partitioning");
138
139     // In the first step, we place all regular monomorphizations into their
140     // respective 'home' codegen unit. Regular monomorphizations are all
141     // functions and statics defined in the local crate.
142     let mut initial_partitioning = {
143         let _prof_timer = tcx.prof.generic_activity("cgu_partitioning_place_roots");
144         place_root_mono_items(tcx, mono_items)
145     };
146
147     initial_partitioning.codegen_units.iter_mut().for_each(|cgu| cgu.estimate_size(tcx));
148
149     debug_dump(tcx, "INITIAL PARTITIONING:", initial_partitioning.codegen_units.iter());
150
151     // If the partitioning should produce a fixed count of codegen units, merge
152     // until that count is reached.
153     if let PartitioningStrategy::FixedUnitCount(count) = strategy {
154         let _prof_timer = tcx.prof.generic_activity("cgu_partitioning_merge_cgus");
155         merge_codegen_units(tcx, &mut initial_partitioning, count);
156         debug_dump(tcx, "POST MERGING:", initial_partitioning.codegen_units.iter());
157     }
158
159     // In the next step, we use the inlining map to determine which additional
160     // monomorphizations have to go into each codegen unit. These additional
161     // monomorphizations can be drop-glue, functions from external crates, and
162     // local functions the definition of which is marked with `#[inline]`.
163     let mut post_inlining = {
164         let _prof_timer =
165             tcx.prof.generic_activity("cgu_partitioning_place_inline_items");
166         place_inlined_mono_items(initial_partitioning, inlining_map)
167     };
168
169     post_inlining.codegen_units.iter_mut().for_each(|cgu| cgu.estimate_size(tcx));
170
171     debug_dump(tcx, "POST INLINING:", post_inlining.codegen_units.iter());
172
173     // Next we try to make as many symbols "internal" as possible, so LLVM has
174     // more freedom to optimize.
175     if !tcx.sess.opts.cg.link_dead_code {
176         let _prof_timer =
177             tcx.prof.generic_activity("cgu_partitioning_internalize_symbols");
178         internalize_symbols(tcx, &mut post_inlining, inlining_map);
179     }
180
181     // Finally, sort by codegen unit name, so that we get deterministic results.
182     let PostInliningPartitioning {
183         codegen_units: mut result,
184         mono_item_placements: _,
185         internalization_candidates: _,
186     } = post_inlining;
187
188     result.sort_by(|cgu1, cgu2| {
189         cgu1.name().cmp(cgu2.name())
190     });
191
192     result
193 }
194
195 struct PreInliningPartitioning<'tcx> {
196     codegen_units: Vec<CodegenUnit<'tcx>>,
197     roots: FxHashSet<MonoItem<'tcx>>,
198     internalization_candidates: FxHashSet<MonoItem<'tcx>>,
199 }
200
201 /// For symbol internalization, we need to know whether a symbol/mono-item is
202 /// accessed from outside the codegen unit it is defined in. This type is used
203 /// to keep track of that.
204 #[derive(Clone, PartialEq, Eq, Debug)]
205 enum MonoItemPlacement {
206     SingleCgu { cgu_name: InternedString },
207     MultipleCgus,
208 }
209
210 struct PostInliningPartitioning<'tcx> {
211     codegen_units: Vec<CodegenUnit<'tcx>>,
212     mono_item_placements: FxHashMap<MonoItem<'tcx>, MonoItemPlacement>,
213     internalization_candidates: FxHashSet<MonoItem<'tcx>>,
214 }
215
216 fn place_root_mono_items<'tcx, I>(tcx: TyCtxt<'tcx>, mono_items: I) -> PreInliningPartitioning<'tcx>
217 where
218     I: Iterator<Item = MonoItem<'tcx>>,
219 {
220     let mut roots = FxHashSet::default();
221     let mut codegen_units = FxHashMap::default();
222     let is_incremental_build = tcx.sess.opts.incremental.is_some();
223     let mut internalization_candidates = FxHashSet::default();
224
225     // Determine if monomorphizations instantiated in this crate will be made
226     // available to downstream crates. This depends on whether we are in
227     // share-generics mode and whether the current crate can even have
228     // downstream crates.
229     let export_generics = tcx.sess.opts.share_generics() &&
230                           tcx.local_crate_exports_generics();
231
232     let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
233     let cgu_name_cache = &mut FxHashMap::default();
234
235     for mono_item in mono_items {
236         match mono_item.instantiation_mode(tcx) {
237             InstantiationMode::GloballyShared { .. } => {}
238             InstantiationMode::LocalCopy => continue,
239         }
240
241         let characteristic_def_id = characteristic_def_id_of_mono_item(tcx, mono_item);
242         let is_volatile = is_incremental_build &&
243                           mono_item.is_generic_fn();
244
245         let codegen_unit_name = match characteristic_def_id {
246             Some(def_id) => compute_codegen_unit_name(tcx,
247                                                       cgu_name_builder,
248                                                       def_id,
249                                                       is_volatile,
250                                                       cgu_name_cache),
251             None => fallback_cgu_name(cgu_name_builder),
252         };
253
254         let codegen_unit = codegen_units.entry(codegen_unit_name.clone())
255             .or_insert_with(|| CodegenUnit::new(codegen_unit_name.clone()));
256
257         let mut can_be_internalized = true;
258         let (linkage, visibility) = mono_item_linkage_and_visibility(
259             tcx,
260             &mono_item,
261             &mut can_be_internalized,
262             export_generics,
263         );
264         if visibility == Visibility::Hidden && can_be_internalized {
265             internalization_candidates.insert(mono_item);
266         }
267
268         codegen_unit.items_mut().insert(mono_item, (linkage, visibility));
269         roots.insert(mono_item);
270     }
271
272     // Always ensure we have at least one CGU; otherwise, if we have a
273     // crate with just types (for example), we could wind up with no CGU.
274     if codegen_units.is_empty() {
275         let codegen_unit_name = fallback_cgu_name(cgu_name_builder);
276         codegen_units.insert(codegen_unit_name.clone(),
277                              CodegenUnit::new(codegen_unit_name.clone()));
278     }
279
280     PreInliningPartitioning {
281         codegen_units: codegen_units.into_iter()
282                                     .map(|(_, codegen_unit)| codegen_unit)
283                                     .collect(),
284         roots,
285         internalization_candidates,
286     }
287 }
288
289 fn mono_item_linkage_and_visibility(
290     tcx: TyCtxt<'tcx>,
291     mono_item: &MonoItem<'tcx>,
292     can_be_internalized: &mut bool,
293     export_generics: bool,
294 ) -> (Linkage, Visibility) {
295     if let Some(explicit_linkage) = mono_item.explicit_linkage(tcx) {
296         return (explicit_linkage, Visibility::Default)
297     }
298     let vis = mono_item_visibility(
299         tcx,
300         mono_item,
301         can_be_internalized,
302         export_generics,
303     );
304     (Linkage::External, vis)
305 }
306
307 fn mono_item_visibility(
308     tcx: TyCtxt<'tcx>,
309     mono_item: &MonoItem<'tcx>,
310     can_be_internalized: &mut bool,
311     export_generics: bool,
312 ) -> Visibility {
313     let instance = match mono_item {
314         // This is pretty complicated; see below.
315         MonoItem::Fn(instance) => instance,
316
317         // Misc handling for generics and such, but otherwise:
318         MonoItem::Static(def_id) => {
319             return if tcx.is_reachable_non_generic(*def_id) {
320                 *can_be_internalized = false;
321                 default_visibility(tcx, *def_id, false)
322             } else {
323                 Visibility::Hidden
324             };
325         }
326         MonoItem::GlobalAsm(hir_id) => {
327             let def_id = tcx.hir().local_def_id(*hir_id);
328             return if tcx.is_reachable_non_generic(def_id) {
329                 *can_be_internalized = false;
330                 default_visibility(tcx, def_id, false)
331             } else {
332                 Visibility::Hidden
333             };
334         }
335     };
336
337     let def_id = match instance.def {
338         InstanceDef::Item(def_id) => def_id,
339
340         // These are all compiler glue and such, never exported, always hidden.
341         InstanceDef::VtableShim(..) |
342         InstanceDef::ReifyShim(..) |
343         InstanceDef::FnPtrShim(..) |
344         InstanceDef::Virtual(..) |
345         InstanceDef::Intrinsic(..) |
346         InstanceDef::ClosureOnceShim { .. } |
347         InstanceDef::DropGlue(..) |
348         InstanceDef::CloneShim(..) => {
349             return Visibility::Hidden
350         }
351     };
352
353     // The `start_fn` lang item is actually a monomorphized instance of a
354     // function in the standard library, used for the `main` function. We don't
355     // want to export it so we tag it with `Hidden` visibility but this symbol
356     // is only referenced from the actual `main` symbol which we unfortunately
357     // don't know anything about during partitioning/collection. As a result we
358     // forcibly keep this symbol out of the `internalization_candidates` set.
359     //
360     // FIXME: eventually we don't want to always force this symbol to have
361     //        hidden visibility, it should indeed be a candidate for
362     //        internalization, but we have to understand that it's referenced
363     //        from the `main` symbol we'll generate later.
364     //
365     //        This may be fixable with a new `InstanceDef` perhaps? Unsure!
366     if tcx.lang_items().start_fn() == Some(def_id) {
367         *can_be_internalized = false;
368         return Visibility::Hidden
369     }
370
371     let is_generic = instance.substs.non_erasable_generics().next().is_some();
372
373     // Upstream `DefId` instances get different handling than local ones.
374     if !def_id.is_local() {
375         return if export_generics && is_generic {
376             // If it is a upstream monomorphization and we export generics, we must make
377             // it available to downstream crates.
378             *can_be_internalized = false;
379             default_visibility(tcx, def_id, true)
380         } else {
381             Visibility::Hidden
382         }
383     }
384
385     if is_generic {
386         if export_generics {
387             if tcx.is_unreachable_local_definition(def_id) {
388                 // This instance cannot be used from another crate.
389                 Visibility::Hidden
390             } else {
391                 // This instance might be useful in a downstream crate.
392                 *can_be_internalized = false;
393                 default_visibility(tcx, def_id, true)
394             }
395         } else {
396             // We are not exporting generics or the definition is not reachable
397             // for downstream crates, we can internalize its instantiations.
398             Visibility::Hidden
399         }
400     } else {
401
402         // If this isn't a generic function then we mark this a `Default` if
403         // this is a reachable item, meaning that it's a symbol other crates may
404         // access when they link to us.
405         if tcx.is_reachable_non_generic(def_id) {
406             *can_be_internalized = false;
407             debug_assert!(!is_generic);
408             return default_visibility(tcx, def_id, false)
409         }
410
411         // If this isn't reachable then we're gonna tag this with `Hidden`
412         // visibility. In some situations though we'll want to prevent this
413         // symbol from being internalized.
414         //
415         // There's two categories of items here:
416         //
417         // * First is weak lang items. These are basically mechanisms for
418         //   libcore to forward-reference symbols defined later in crates like
419         //   the standard library or `#[panic_handler]` definitions. The
420         //   definition of these weak lang items needs to be referenceable by
421         //   libcore, so we're no longer a candidate for internalization.
422         //   Removal of these functions can't be done by LLVM but rather must be
423         //   done by the linker as it's a non-local decision.
424         //
425         // * Second is "std internal symbols". Currently this is primarily used
426         //   for allocator symbols. Allocators are a little weird in their
427         //   implementation, but the idea is that the compiler, at the last
428         //   minute, defines an allocator with an injected object file. The
429         //   `alloc` crate references these symbols (`__rust_alloc`) and the
430         //   definition doesn't get hooked up until a linked crate artifact is
431         //   generated.
432         //
433         //   The symbols synthesized by the compiler (`__rust_alloc`) are thin
434         //   veneers around the actual implementation, some other symbol which
435         //   implements the same ABI. These symbols (things like `__rg_alloc`,
436         //   `__rdl_alloc`, `__rde_alloc`, etc), are all tagged with "std
437         //   internal symbols".
438         //
439         //   The std-internal symbols here **should not show up in a dll as an
440         //   exported interface**, so they return `false` from
441         //   `is_reachable_non_generic` above and we'll give them `Hidden`
442         //   visibility below. Like the weak lang items, though, we can't let
443         //   LLVM internalize them as this decision is left up to the linker to
444         //   omit them, so prevent them from being internalized.
445         let attrs = tcx.codegen_fn_attrs(def_id);
446         if attrs.flags.contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL) {
447             *can_be_internalized = false;
448         }
449
450         Visibility::Hidden
451     }
452 }
453
454 fn default_visibility(tcx: TyCtxt<'_>, id: DefId, is_generic: bool) -> Visibility {
455     if !tcx.sess.target.target.options.default_hidden_visibility {
456         return Visibility::Default
457     }
458
459     // Generic functions never have export-level C.
460     if is_generic {
461         return Visibility::Hidden
462     }
463
464     // Things with export level C don't get instantiated in
465     // downstream crates.
466     if !id.is_local() {
467         return Visibility::Hidden
468     }
469
470     // C-export level items remain at `Default`, all other internal
471     // items become `Hidden`.
472     match tcx.reachable_non_generics(id.krate).get(&id) {
473         Some(SymbolExportLevel::C) => Visibility::Default,
474         _ => Visibility::Hidden,
475     }
476 }
477
478 fn merge_codegen_units<'tcx>(
479     tcx: TyCtxt<'tcx>,
480     initial_partitioning: &mut PreInliningPartitioning<'tcx>,
481     target_cgu_count: usize,
482 ) {
483     assert!(target_cgu_count >= 1);
484     let codegen_units = &mut initial_partitioning.codegen_units;
485
486     // Note that at this point in time the `codegen_units` here may not be in a
487     // deterministic order (but we know they're deterministically the same set).
488     // We want this merging to produce a deterministic ordering of codegen units
489     // from the input.
490     //
491     // Due to basically how we've implemented the merging below (merge the two
492     // smallest into each other) we're sure to start off with a deterministic
493     // order (sorted by name). This'll mean that if two cgus have the same size
494     // the stable sort below will keep everything nice and deterministic.
495     codegen_units.sort_by_key(|cgu| *cgu.name());
496
497     // Merge the two smallest codegen units until the target size is reached.
498     while codegen_units.len() > target_cgu_count {
499         // Sort small cgus to the back
500         codegen_units.sort_by_cached_key(|cgu| cmp::Reverse(cgu.size_estimate()));
501         let mut smallest = codegen_units.pop().unwrap();
502         let second_smallest = codegen_units.last_mut().unwrap();
503
504         second_smallest.modify_size_estimate(smallest.size_estimate());
505         for (k, v) in smallest.items_mut().drain() {
506             second_smallest.items_mut().insert(k, v);
507         }
508         debug!("CodegenUnit {} merged in to CodegenUnit {}",
509                smallest.name(),
510                second_smallest.name());
511     }
512
513     let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
514     for (index, cgu) in codegen_units.iter_mut().enumerate() {
515         cgu.set_name(numbered_codegen_unit_name(cgu_name_builder, index));
516     }
517 }
518
519 fn place_inlined_mono_items<'tcx>(initial_partitioning: PreInliningPartitioning<'tcx>,
520                                   inlining_map: &InliningMap<'tcx>)
521                                   -> PostInliningPartitioning<'tcx> {
522     let mut new_partitioning = Vec::new();
523     let mut mono_item_placements = FxHashMap::default();
524
525     let PreInliningPartitioning {
526         codegen_units: initial_cgus,
527         roots,
528         internalization_candidates,
529     } = initial_partitioning;
530
531     let single_codegen_unit = initial_cgus.len() == 1;
532
533     for old_codegen_unit in initial_cgus {
534         // Collect all items that need to be available in this codegen unit.
535         let mut reachable = FxHashSet::default();
536         for root in old_codegen_unit.items().keys() {
537             follow_inlining(*root, inlining_map, &mut reachable);
538         }
539
540         let mut new_codegen_unit = CodegenUnit::new(old_codegen_unit.name().clone());
541
542         // Add all monomorphizations that are not already there.
543         for mono_item in reachable {
544             if let Some(linkage) = old_codegen_unit.items().get(&mono_item) {
545                 // This is a root, just copy it over.
546                 new_codegen_unit.items_mut().insert(mono_item, *linkage);
547             } else {
548                 if roots.contains(&mono_item) {
549                     bug!("GloballyShared mono-item inlined into other CGU: \
550                           {:?}", mono_item);
551                 }
552
553                 // This is a CGU-private copy.
554                 new_codegen_unit.items_mut().insert(
555                     mono_item,
556                     (Linkage::Internal, Visibility::Default),
557                 );
558             }
559
560             if !single_codegen_unit {
561                 // If there is more than one codegen unit, we need to keep track
562                 // in which codegen units each monomorphization is placed.
563                 match mono_item_placements.entry(mono_item) {
564                     Entry::Occupied(e) => {
565                         let placement = e.into_mut();
566                         debug_assert!(match *placement {
567                             MonoItemPlacement::SingleCgu { ref cgu_name } => {
568                                 *cgu_name != *new_codegen_unit.name()
569                             }
570                             MonoItemPlacement::MultipleCgus => true,
571                         });
572                         *placement = MonoItemPlacement::MultipleCgus;
573                     }
574                     Entry::Vacant(e) => {
575                         e.insert(MonoItemPlacement::SingleCgu {
576                             cgu_name: new_codegen_unit.name().clone()
577                         });
578                     }
579                 }
580             }
581         }
582
583         new_partitioning.push(new_codegen_unit);
584     }
585
586     return PostInliningPartitioning {
587         codegen_units: new_partitioning,
588         mono_item_placements,
589         internalization_candidates,
590     };
591
592     fn follow_inlining<'tcx>(mono_item: MonoItem<'tcx>,
593                              inlining_map: &InliningMap<'tcx>,
594                              visited: &mut FxHashSet<MonoItem<'tcx>>) {
595         if !visited.insert(mono_item) {
596             return;
597         }
598
599         inlining_map.with_inlining_candidates(mono_item, |target| {
600             follow_inlining(target, inlining_map, visited);
601         });
602     }
603 }
604
605 fn internalize_symbols<'tcx>(
606     _tcx: TyCtxt<'tcx>,
607     partitioning: &mut PostInliningPartitioning<'tcx>,
608     inlining_map: &InliningMap<'tcx>,
609 ) {
610     if partitioning.codegen_units.len() == 1 {
611         // Fast path for when there is only one codegen unit. In this case we
612         // can internalize all candidates, since there is nowhere else they
613         // could be accessed from.
614         for cgu in &mut partitioning.codegen_units {
615             for candidate in &partitioning.internalization_candidates {
616                 cgu.items_mut().insert(*candidate,
617                                        (Linkage::Internal, Visibility::Default));
618             }
619         }
620
621         return;
622     }
623
624     // Build a map from every monomorphization to all the monomorphizations that
625     // reference it.
626     let mut accessor_map: FxHashMap<MonoItem<'tcx>, Vec<MonoItem<'tcx>>> = Default::default();
627     inlining_map.iter_accesses(|accessor, accessees| {
628         for accessee in accessees {
629             accessor_map.entry(*accessee)
630                         .or_default()
631                         .push(accessor);
632         }
633     });
634
635     let mono_item_placements = &partitioning.mono_item_placements;
636
637     // For each internalization candidates in each codegen unit, check if it is
638     // accessed from outside its defining codegen unit.
639     for cgu in &mut partitioning.codegen_units {
640         let home_cgu = MonoItemPlacement::SingleCgu {
641             cgu_name: cgu.name().clone()
642         };
643
644         for (accessee, linkage_and_visibility) in cgu.items_mut() {
645             if !partitioning.internalization_candidates.contains(accessee) {
646                 // This item is no candidate for internalizing, so skip it.
647                 continue
648             }
649             debug_assert_eq!(mono_item_placements[accessee], home_cgu);
650
651             if let Some(accessors) = accessor_map.get(accessee) {
652                 if accessors.iter()
653                             .filter_map(|accessor| {
654                                 // Some accessors might not have been
655                                 // instantiated. We can safely ignore those.
656                                 mono_item_placements.get(accessor)
657                             })
658                             .any(|placement| *placement != home_cgu) {
659                     // Found an accessor from another CGU, so skip to the next
660                     // item without marking this one as internal.
661                     continue
662                 }
663             }
664
665             // If we got here, we did not find any accesses from other CGUs,
666             // so it's fine to make this monomorphization internal.
667             *linkage_and_visibility = (Linkage::Internal, Visibility::Default);
668         }
669     }
670 }
671
672 fn characteristic_def_id_of_mono_item<'tcx>(
673     tcx: TyCtxt<'tcx>,
674     mono_item: MonoItem<'tcx>,
675 ) -> Option<DefId> {
676     match mono_item {
677         MonoItem::Fn(instance) => {
678             let def_id = match instance.def {
679                 ty::InstanceDef::Item(def_id) => def_id,
680                 ty::InstanceDef::VtableShim(..) |
681                 ty::InstanceDef::ReifyShim(..) |
682                 ty::InstanceDef::FnPtrShim(..) |
683                 ty::InstanceDef::ClosureOnceShim { .. } |
684                 ty::InstanceDef::Intrinsic(..) |
685                 ty::InstanceDef::DropGlue(..) |
686                 ty::InstanceDef::Virtual(..) |
687                 ty::InstanceDef::CloneShim(..) => return None
688             };
689
690             // If this is a method, we want to put it into the same module as
691             // its self-type. If the self-type does not provide a characteristic
692             // DefId, we use the location of the impl after all.
693
694             if tcx.trait_of_item(def_id).is_some() {
695                 let self_ty = instance.substs.type_at(0);
696                 // This is an implementation of a trait method.
697                 return characteristic_def_id_of_type(self_ty).or(Some(def_id));
698             }
699
700             if let Some(impl_def_id) = tcx.impl_of_method(def_id) {
701                 // This is a method within an inherent impl, find out what the
702                 // self-type is:
703                 let impl_self_ty = tcx.subst_and_normalize_erasing_regions(
704                     instance.substs,
705                     ty::ParamEnv::reveal_all(),
706                     &tcx.type_of(impl_def_id),
707                 );
708                 if let Some(def_id) = characteristic_def_id_of_type(impl_self_ty) {
709                     return Some(def_id);
710                 }
711             }
712
713             Some(def_id)
714         }
715         MonoItem::Static(def_id) => Some(def_id),
716         MonoItem::GlobalAsm(hir_id) => Some(tcx.hir().local_def_id(hir_id)),
717     }
718 }
719
720 type CguNameCache = FxHashMap<(DefId, bool), InternedString>;
721
722 fn compute_codegen_unit_name(
723     tcx: TyCtxt<'_>,
724     name_builder: &mut CodegenUnitNameBuilder<'_>,
725     def_id: DefId,
726     volatile: bool,
727     cache: &mut CguNameCache,
728 ) -> InternedString {
729     // Find the innermost module that is not nested within a function.
730     let mut current_def_id = def_id;
731     let mut cgu_def_id = None;
732     // Walk backwards from the item we want to find the module for.
733     loop {
734         if current_def_id.index == CRATE_DEF_INDEX {
735             if cgu_def_id.is_none() {
736                 // If we have not found a module yet, take the crate root.
737                 cgu_def_id = Some(DefId {
738                     krate: def_id.krate,
739                     index: CRATE_DEF_INDEX,
740                 });
741             }
742             break
743         } else if tcx.def_kind(current_def_id) == Some(DefKind::Mod) {
744             if cgu_def_id.is_none() {
745                 cgu_def_id = Some(current_def_id);
746             }
747         } else {
748             // If we encounter something that is not a module, throw away
749             // any module that we've found so far because we now know that
750             // it is nested within something else.
751             cgu_def_id = None;
752         }
753
754         current_def_id = tcx.parent(current_def_id).unwrap();
755     }
756
757     let cgu_def_id = cgu_def_id.unwrap();
758
759     cache.entry((cgu_def_id, volatile)).or_insert_with(|| {
760         let def_path = tcx.def_path(cgu_def_id);
761
762         let components = def_path
763             .data
764             .iter()
765             .map(|part| part.data.as_interned_str());
766
767         let volatile_suffix = if volatile {
768             Some("volatile")
769         } else {
770             None
771         };
772
773         name_builder.build_cgu_name(def_path.krate, components, volatile_suffix)
774     }).clone()
775 }
776
777 fn numbered_codegen_unit_name(
778     name_builder: &mut CodegenUnitNameBuilder<'_>,
779     index: usize,
780 ) -> InternedString {
781     name_builder.build_cgu_name_no_mangle(LOCAL_CRATE, &["cgu"], Some(index))
782 }
783
784 fn debug_dump<'a, 'tcx, I>(tcx: TyCtxt<'tcx>, label: &str, cgus: I)
785 where
786     I: Iterator<Item = &'a CodegenUnit<'tcx>>,
787     'tcx: 'a,
788 {
789     if cfg!(debug_assertions) {
790         debug!("{}", label);
791         for cgu in cgus {
792             debug!("CodegenUnit {} estimated size {} :", cgu.name(), cgu.size_estimate());
793
794             for (mono_item, linkage) in cgu.items() {
795                 let symbol_name = mono_item.symbol_name(tcx).name.as_str();
796                 let symbol_hash_start = symbol_name.rfind('h');
797                 let symbol_hash = symbol_hash_start.map(|i| &symbol_name[i ..])
798                                                    .unwrap_or("<no hash>");
799
800                 debug!(" - {} [{:?}] [{}] estimated size {}",
801                        mono_item.to_string(tcx, true),
802                        linkage,
803                        symbol_hash,
804                        mono_item.size_estimate(tcx));
805             }
806
807             debug!("");
808         }
809     }
810 }
811
812 #[inline(never)] // give this a place in the profiler
813 fn assert_symbols_are_distinct<'a, 'tcx, I>(tcx: TyCtxt<'tcx>, mono_items: I)
814 where
815     I: Iterator<Item = &'a MonoItem<'tcx>>,
816     'tcx: 'a,
817 {
818     let mut symbols: Vec<_> = mono_items.map(|mono_item| {
819         (mono_item, mono_item.symbol_name(tcx))
820     }).collect();
821
822     symbols.sort_by_key(|sym| sym.1);
823
824     for pair in symbols.windows(2) {
825         let sym1 = &pair[0].1;
826         let sym2 = &pair[1].1;
827
828         if sym1 == sym2 {
829             let mono_item1 = pair[0].0;
830             let mono_item2 = pair[1].0;
831
832             let span1 = mono_item1.local_span(tcx);
833             let span2 = mono_item2.local_span(tcx);
834
835             // Deterministically select one of the spans for error reporting
836             let span = match (span1, span2) {
837                 (Some(span1), Some(span2)) => {
838                     Some(if span1.lo().0 > span2.lo().0 {
839                         span1
840                     } else {
841                         span2
842                     })
843                 }
844                 (span1, span2) => span1.or(span2),
845             };
846
847             let error_message = format!("symbol `{}` is already defined", sym1);
848
849             if let Some(span) = span {
850                 tcx.sess.span_fatal(span, &error_message)
851             } else {
852                 tcx.sess.fatal(&error_message)
853             }
854         }
855     }
856 }
857
858 fn collect_and_partition_mono_items(
859     tcx: TyCtxt<'_>,
860     cnum: CrateNum,
861 ) -> (Arc<DefIdSet>, Arc<Vec<Arc<CodegenUnit<'_>>>>) {
862     assert_eq!(cnum, LOCAL_CRATE);
863
864     let collection_mode = match tcx.sess.opts.debugging_opts.print_mono_items {
865         Some(ref s) => {
866             let mode_string = s.to_lowercase();
867             let mode_string = mode_string.trim();
868             if mode_string == "eager" {
869                 MonoItemCollectionMode::Eager
870             } else {
871                 if mode_string != "lazy" {
872                     let message = format!("Unknown codegen-item collection mode '{}'. \
873                                            Falling back to 'lazy' mode.",
874                                           mode_string);
875                     tcx.sess.warn(&message);
876                 }
877
878                 MonoItemCollectionMode::Lazy
879             }
880         }
881         None => {
882             if tcx.sess.opts.cg.link_dead_code {
883                 MonoItemCollectionMode::Eager
884             } else {
885                 MonoItemCollectionMode::Lazy
886             }
887         }
888     };
889
890     let (items, inlining_map) =
891         time(tcx.sess, "monomorphization collection", || {
892             collector::collect_crate_mono_items(tcx, collection_mode)
893     });
894
895     tcx.sess.abort_if_errors();
896
897     assert_symbols_are_distinct(tcx, items.iter());
898
899     let strategy = if tcx.sess.opts.incremental.is_some() {
900         PartitioningStrategy::PerModule
901     } else {
902         PartitioningStrategy::FixedUnitCount(tcx.sess.codegen_units())
903     };
904
905     let codegen_units = time(tcx.sess, "codegen unit partitioning", || {
906         partition(
907             tcx,
908             items.iter().cloned(),
909             strategy,
910             &inlining_map
911         )
912             .into_iter()
913             .map(Arc::new)
914             .collect::<Vec<_>>()
915     });
916
917     let mono_items: DefIdSet = items.iter().filter_map(|mono_item| {
918         match *mono_item {
919             MonoItem::Fn(ref instance) => Some(instance.def_id()),
920             MonoItem::Static(def_id) => Some(def_id),
921             _ => None,
922         }
923     }).collect();
924
925     if tcx.sess.opts.debugging_opts.print_mono_items.is_some() {
926         let mut item_to_cgus: FxHashMap<_, Vec<_>> = Default::default();
927
928         for cgu in &codegen_units {
929             for (&mono_item, &linkage) in cgu.items() {
930                 item_to_cgus.entry(mono_item)
931                             .or_default()
932                             .push((cgu.name().clone(), linkage));
933             }
934         }
935
936         let mut item_keys: Vec<_> = items
937             .iter()
938             .map(|i| {
939                 let mut output = i.to_string(tcx, false);
940                 output.push_str(" @@");
941                 let mut empty = Vec::new();
942                 let cgus = item_to_cgus.get_mut(i).unwrap_or(&mut empty);
943                 cgus.sort_by_key(|(name, _)| *name);
944                 cgus.dedup();
945                 for &(ref cgu_name, (linkage, _)) in cgus.iter() {
946                     output.push_str(" ");
947                     output.push_str(&cgu_name.as_str());
948
949                     let linkage_abbrev = match linkage {
950                         Linkage::External => "External",
951                         Linkage::AvailableExternally => "Available",
952                         Linkage::LinkOnceAny => "OnceAny",
953                         Linkage::LinkOnceODR => "OnceODR",
954                         Linkage::WeakAny => "WeakAny",
955                         Linkage::WeakODR => "WeakODR",
956                         Linkage::Appending => "Appending",
957                         Linkage::Internal => "Internal",
958                         Linkage::Private => "Private",
959                         Linkage::ExternalWeak => "ExternalWeak",
960                         Linkage::Common => "Common",
961                     };
962
963                     output.push_str("[");
964                     output.push_str(linkage_abbrev);
965                     output.push_str("]");
966                 }
967                 output
968             })
969             .collect();
970
971         item_keys.sort();
972
973         for item in item_keys {
974             println!("MONO_ITEM {}", item);
975         }
976     }
977
978     (Arc::new(mono_items), Arc::new(codegen_units))
979 }
980
981 pub fn provide(providers: &mut Providers<'_>) {
982     providers.collect_and_partition_mono_items =
983         collect_and_partition_mono_items;
984
985     providers.is_codegened_item = |tcx, def_id| {
986         let (all_mono_items, _) =
987             tcx.collect_and_partition_mono_items(LOCAL_CRATE);
988         all_mono_items.contains(&def_id)
989     };
990
991     providers.codegen_unit = |tcx, name| {
992         let (_, all) = tcx.collect_and_partition_mono_items(LOCAL_CRATE);
993         all.iter()
994             .find(|cgu| *cgu.name() == name)
995             .cloned()
996             .unwrap_or_else(|| panic!("failed to find cgu with name {:?}", name))
997     };
998 }