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