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.
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.
11 //! Partitioning Codegen Units for Incremental Compilation
12 //! ======================================================
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.
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.
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
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.
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.
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:
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
57 //! In order to see why this heuristic makes sense, let's take a look at when a
58 //! codegen unit can get invalidated:
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
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.
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.
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.
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:
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.
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.
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].
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;
117 use syntax::ast::NodeId;
118 use syntax::symbol::{Symbol, InternedString};
119 use rustc::mir::mono::MonoItem;
120 use monomorphize::item::{MonoItemExt, InstantiationMode};
122 pub use rustc::mir::mono::CodegenUnit;
124 pub enum PartitioningStrategy {
125 /// Generate one codegen unit per source-level module.
128 /// Partition the whole crate into a fixed number of codegen units.
129 FixedUnitCount(usize)
132 pub trait CodegenUnitExt<'tcx> {
133 fn as_codegen_unit(&self) -> &CodegenUnit<'tcx>;
135 fn contains_item(&self, item: &MonoItem<'tcx>) -> bool {
136 self.items().contains_key(item)
139 fn name<'a>(&'a self) -> &'a InternedString
142 &self.as_codegen_unit().name()
145 fn items(&self) -> &FxHashMap<MonoItem<'tcx>, (Linkage, Visibility)> {
146 &self.as_codegen_unit().items()
149 fn work_product_id(&self) -> WorkProductId {
150 WorkProductId::from_cgu_name(&self.name().as_str())
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);
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) => {
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
171 InstanceDef::Item(def_id) => {
172 tcx.hir.as_local_node_id(def_id)
174 InstanceDef::Intrinsic(..) |
175 InstanceDef::FnPtrShim(..) |
176 InstanceDef::Virtual(..) |
177 InstanceDef::ClosureOnceShim { .. } |
178 InstanceDef::DropGlue(..) |
179 InstanceDef::CloneShim(..) => {
184 MonoItem::Static(def_id) => {
185 tcx.hir.as_local_node_id(def_id)
187 MonoItem::GlobalAsm(node_id) => {
190 }, item.symbol_name(tcx))
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));
199 impl<'tcx> CodegenUnitExt<'tcx> for CodegenUnit<'tcx> {
200 fn as_codegen_unit(&self) -> &CodegenUnit<'tcx> {
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";
209 if tcx.sess.opts.debugging_opts.human_readable_cgu_names {
210 Symbol::intern(FALLBACK_CODEGEN_UNIT).as_interned_str()
212 Symbol::intern(&CodegenUnit::mangle_name(FALLBACK_CODEGEN_UNIT)).as_interned_str()
217 pub fn partition<'a, 'tcx, I>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
219 strategy: PartitioningStrategy,
220 inlining_map: &InliningMap<'tcx>)
221 -> Vec<CodegenUnit<'tcx>>
222 where I: Iterator<Item = MonoItem<'tcx>>
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,
230 initial_partitioning.codegen_units.iter_mut().for_each(|cgu| cgu.estimate_size(&tcx));
232 debug_dump(tcx, "INITIAL PARTITIONING:", initial_partitioning.codegen_units.iter());
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());
239 debug_dump(tcx, "POST MERGING:", initial_partitioning.codegen_units.iter());
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,
249 post_inlining.codegen_units.iter_mut().for_each(|cgu| cgu.estimate_size(&tcx));
251 debug_dump(tcx, "POST INLINING:", post_inlining.codegen_units.iter());
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);
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: _,
266 result.sort_by(|cgu1, cgu2| {
267 cgu1.name().cmp(cgu2.name())
273 struct PreInliningPartitioning<'tcx> {
274 codegen_units: Vec<CodegenUnit<'tcx>>,
275 roots: FxHashSet<MonoItem<'tcx>>,
276 internalization_candidates: FxHashSet<MonoItem<'tcx>>,
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 },
288 struct PostInliningPartitioning<'tcx> {
289 codegen_units: Vec<CodegenUnit<'tcx>>,
290 mono_item_placements: FxHashMap<MonoItem<'tcx>, MonoItemPlacement>,
291 internalization_candidates: FxHashSet<MonoItem<'tcx>>,
294 fn place_root_mono_items<'a, 'tcx, I>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
296 -> PreInliningPartitioning<'tcx>
297 where I: Iterator<Item = MonoItem<'tcx>>
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();
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();
311 for mono_item in mono_items {
312 match mono_item.instantiation_mode(tcx) {
313 InstantiationMode::GloballyShared { .. } => {}
314 InstantiationMode::LocalCopy => continue,
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();
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),
326 let codegen_unit = codegen_units.entry(codegen_unit_name.clone())
327 .or_insert_with(|| CodegenUnit::new(codegen_unit_name.clone()));
329 let mut can_be_internalized = true;
330 let (linkage, visibility) = mono_item_linkage_and_visibility(
333 &mut can_be_internalized,
336 if visibility == Visibility::Hidden && can_be_internalized {
337 internalization_candidates.insert(mono_item);
340 codegen_unit.items_mut().insert(mono_item, (linkage, visibility));
341 roots.insert(mono_item);
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()));
352 PreInliningPartitioning {
353 codegen_units: codegen_units.into_iter()
354 .map(|(_, codegen_unit)| codegen_unit)
357 internalization_candidates,
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)
370 let vis = mono_item_visibility(
376 (Linkage::External, vis)
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,
385 let instance = match mono_item {
386 // This is pretty complicated, go below
387 MonoItem::Fn(instance) => instance,
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)
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)
409 let def_id = match instance.def {
410 InstanceDef::Item(def_id) => def_id,
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
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.
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.
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
441 let is_generic = instance.substs.types().next().is_some();
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)
458 if tcx.is_unreachable_local_definition(def_id) {
459 // This instance cannot be used
460 // from another crate.
463 // This instance might be useful in
464 // a downstream crate.
465 *can_be_internalized = false;
466 default_visibility(tcx, def_id, true)
469 // We are not exporting generics or
470 // the definition is not reachable
471 // for downstream crates, we can
472 // internalize its instantiations.
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)
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.
490 // There's two categories of items here:
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.
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
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".
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;
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
536 // Generic functions never have export level C
538 return Visibility::Hidden
541 // Things with export level C don't get instantiated in
544 return Visibility::Hidden
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,
555 fn merge_codegen_units<'tcx>(initial_partitioning: &mut PreInliningPartitioning<'tcx>,
556 target_cgu_count: usize,
558 assert!(target_cgu_count >= 1);
559 let codegen_units = &mut initial_partitioning.codegen_units;
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
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());
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();
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);
585 for (index, cgu) in codegen_units.iter_mut().enumerate() {
586 cgu.set_name(numbered_codegen_unit_name(crate_name, index));
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();
596 let PreInliningPartitioning {
597 codegen_units: initial_cgus,
599 internalization_candidates,
600 } = initial_partitioning;
602 let single_codegen_unit = initial_cgus.len() == 1;
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);
611 let mut new_codegen_unit = CodegenUnit::new(old_codegen_unit.name().clone());
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);
619 if roots.contains(&mono_item) {
620 bug!("GloballyShared mono-item inlined into other CGU: \
624 // This is a cgu-private copy
625 new_codegen_unit.items_mut().insert(
627 (Linkage::Internal, Visibility::Default),
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()
641 MonoItemPlacement::MultipleCgus => true,
643 *placement = MonoItemPlacement::MultipleCgus;
645 Entry::Vacant(e) => {
646 e.insert(MonoItemPlacement::SingleCgu {
647 cgu_name: new_codegen_unit.name().clone()
654 new_partitioning.push(new_codegen_unit);
657 return PostInliningPartitioning {
658 codegen_units: new_partitioning,
659 mono_item_placements,
660 internalization_candidates,
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) {
670 inlining_map.with_inlining_candidates(mono_item, |target| {
671 follow_inlining(target, inlining_map, visited);
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));
693 // Build a map from every monomorphization to all the monomorphizations that
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())
704 let mono_item_placements = &partitioning.mono_item_placements;
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()
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.
718 debug_assert_eq!(mono_item_placements[accessee], home_cgu);
720 if let Some(accessors) = accessor_map.get(accessee) {
722 .filter_map(|accessor| {
723 // Some accessors might not have been
724 // instantiated. We can safely ignore those.
725 mono_item_placements.get(accessor)
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.
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);
741 fn characteristic_def_id_of_mono_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
742 mono_item: MonoItem<'tcx>)
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
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.
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));
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
769 let impl_self_ty = tcx.subst_and_normalize_erasing_regions(
771 ty::ParamEnv::reveal_all(),
772 &tcx.type_of(impl_def_id),
774 if let Some(def_id) = characteristic_def_id_of_type(impl_self_ty) {
781 MonoItem::Static(def_id) => Some(def_id),
782 MonoItem::GlobalAsm(node_id) => Some(tcx.hir.local_def_id(node_id)),
786 fn compute_codegen_unit_name<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
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);
795 let def_path = tcx.def_path(def_id);
796 cgu_name.push_str(&tcx.crate_name(def_path.krate).as_str());
798 for part in tcx.def_path(def_id)
803 DefPathData::Module(..) => true,
807 cgu_name.push_str("-");
808 cgu_name.push_str(&part.data.as_interned_str().as_str());
812 cgu_name.push_str(".volatile");
815 let cgu_name = if tcx.sess.opts.debugging_opts.human_readable_cgu_names {
818 CodegenUnit::mangle_name(&cgu_name)
821 Symbol::intern(&cgu_name[..]).as_interned_str()
824 fn numbered_codegen_unit_name(crate_name: &str, index: usize) -> InternedString {
825 Symbol::intern(&format!("{}{}", crate_name, index)).as_interned_str()
828 fn debug_dump<'a, 'b, 'tcx, I>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
831 where I: Iterator<Item=&'b CodegenUnit<'tcx>>,
834 if cfg!(debug_assertions) {
837 debug!("CodegenUnit {}:", cgu.name());
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>");
845 debug!(" - {} [{:?}] [{}]",
846 mono_item.to_string(tcx),