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