]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/partitioning.rs
Remove some out-dated comments from CGU partitioning docs.
[rust.git] / src / librustc_trans / 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 translation items of
15 //! a crate and produce a set of codegen units from it, where a codegen unit
16 //! is a named set of (translation-item, linkage) pairs. That is, this module
17 //! decides which translation item 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-translating and re-optimizing code.
23 //! Since the unit of translation 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 collector::InliningMap;
106 use context::SharedCrateContext;
107 use llvm;
108 use monomorphize;
109 use rustc::dep_graph::{DepNode, WorkProductId};
110 use rustc::hir::def_id::DefId;
111 use rustc::hir::map::DefPathData;
112 use rustc::session::config::NUMBERED_CODEGEN_UNIT_MARKER;
113 use rustc::ty::TyCtxt;
114 use rustc::ty::item_path::characteristic_def_id_of_type;
115 use rustc_incremental::IchHasher;
116 use std::cmp::Ordering;
117 use std::hash::Hash;
118 use std::sync::Arc;
119 use symbol_map::SymbolMap;
120 use syntax::ast::NodeId;
121 use syntax::symbol::{Symbol, InternedString};
122 use trans_item::{TransItem, InstantiationMode};
123 use util::nodemap::{FxHashMap, FxHashSet};
124
125 pub enum PartitioningStrategy {
126     /// Generate one codegen unit per source-level module.
127     PerModule,
128
129     /// Partition the whole crate into a fixed number of codegen units.
130     FixedUnitCount(usize)
131 }
132
133 pub struct CodegenUnit<'tcx> {
134     /// A name for this CGU. Incremental compilation requires that
135     /// name be unique amongst **all** crates.  Therefore, it should
136     /// contain something unique to this crate (e.g., a module path)
137     /// as well as the crate name and disambiguator.
138     name: InternedString,
139
140     items: FxHashMap<TransItem<'tcx>, llvm::Linkage>,
141 }
142
143 impl<'tcx> CodegenUnit<'tcx> {
144     pub fn new(name: InternedString,
145                items: FxHashMap<TransItem<'tcx>, llvm::Linkage>)
146                -> Self {
147         CodegenUnit {
148             name: name,
149             items: items,
150         }
151     }
152
153     pub fn empty(name: InternedString) -> Self {
154         Self::new(name, FxHashMap())
155     }
156
157     pub fn contains_item(&self, item: &TransItem<'tcx>) -> bool {
158         self.items.contains_key(item)
159     }
160
161     pub fn name(&self) -> &str {
162         &self.name
163     }
164
165     pub fn items(&self) -> &FxHashMap<TransItem<'tcx>, llvm::Linkage> {
166         &self.items
167     }
168
169     pub fn work_product_id(&self) -> Arc<WorkProductId> {
170         Arc::new(WorkProductId(self.name().to_string()))
171     }
172
173     pub fn work_product_dep_node(&self) -> DepNode<DefId> {
174         DepNode::WorkProduct(self.work_product_id())
175     }
176
177     pub fn compute_symbol_name_hash(&self,
178                                     scx: &SharedCrateContext,
179                                     symbol_map: &SymbolMap) -> u64 {
180         let mut state = IchHasher::new();
181         let exported_symbols = scx.exported_symbols();
182         let all_items = self.items_in_deterministic_order(scx.tcx(), symbol_map);
183         for (item, _) in all_items {
184             let symbol_name = symbol_map.get(item).unwrap();
185             symbol_name.len().hash(&mut state);
186             symbol_name.hash(&mut state);
187             let exported = match item {
188                TransItem::Fn(ref instance) => {
189                     let node_id = scx.tcx().map.as_local_node_id(instance.def);
190                     node_id.map(|node_id| exported_symbols.contains(&node_id))
191                            .unwrap_or(false)
192                }
193                TransItem::Static(node_id) => {
194                     exported_symbols.contains(&node_id)
195                }
196                TransItem::DropGlue(..) => false,
197             };
198             exported.hash(&mut state);
199         }
200         state.finish().to_smaller_hash()
201     }
202
203     pub fn items_in_deterministic_order(&self,
204                                         tcx: TyCtxt,
205                                         symbol_map: &SymbolMap)
206                                         -> Vec<(TransItem<'tcx>, llvm::Linkage)> {
207         let mut items: Vec<(TransItem<'tcx>, llvm::Linkage)> =
208             self.items.iter().map(|(item, linkage)| (*item, *linkage)).collect();
209
210         // The codegen tests rely on items being process in the same order as
211         // they appear in the file, so for local items, we sort by node_id first
212         items.sort_by(|&(trans_item1, _), &(trans_item2, _)| {
213             let node_id1 = local_node_id(tcx, trans_item1);
214             let node_id2 = local_node_id(tcx, trans_item2);
215
216             match (node_id1, node_id2) {
217                 (None, None) => {
218                     let symbol_name1 = symbol_map.get(trans_item1).unwrap();
219                     let symbol_name2 = symbol_map.get(trans_item2).unwrap();
220                     symbol_name1.cmp(symbol_name2)
221                 }
222                 // In the following two cases we can avoid looking up the symbol
223                 (None, Some(_)) => Ordering::Less,
224                 (Some(_), None) => Ordering::Greater,
225                 (Some(node_id1), Some(node_id2)) => {
226                     let ordering = node_id1.cmp(&node_id2);
227
228                     if ordering != Ordering::Equal {
229                         return ordering;
230                     }
231
232                     let symbol_name1 = symbol_map.get(trans_item1).unwrap();
233                     let symbol_name2 = symbol_map.get(trans_item2).unwrap();
234                     symbol_name1.cmp(symbol_name2)
235                 }
236             }
237         });
238
239         return items;
240
241         fn local_node_id(tcx: TyCtxt, trans_item: TransItem) -> Option<NodeId> {
242             match trans_item {
243                 TransItem::Fn(instance) => {
244                     tcx.map.as_local_node_id(instance.def)
245                 }
246                 TransItem::Static(node_id) => Some(node_id),
247                 TransItem::DropGlue(_) => None,
248             }
249         }
250     }
251 }
252
253
254 // Anything we can't find a proper codegen unit for goes into this.
255 const FALLBACK_CODEGEN_UNIT: &'static str = "__rustc_fallback_codegen_unit";
256
257 pub fn partition<'a, 'tcx, I>(scx: &SharedCrateContext<'a, 'tcx>,
258                               trans_items: I,
259                               strategy: PartitioningStrategy,
260                               inlining_map: &InliningMap<'tcx>)
261                               -> Vec<CodegenUnit<'tcx>>
262     where I: Iterator<Item = TransItem<'tcx>>
263 {
264     let tcx = scx.tcx();
265
266     // In the first step, we place all regular translation items into their
267     // respective 'home' codegen unit. Regular translation items are all
268     // functions and statics defined in the local crate.
269     let mut initial_partitioning = place_root_translation_items(scx,
270                                                                 trans_items);
271
272     debug_dump(scx, "INITIAL PARTITONING:", initial_partitioning.codegen_units.iter());
273
274     // If the partitioning should produce a fixed count of codegen units, merge
275     // until that count is reached.
276     if let PartitioningStrategy::FixedUnitCount(count) = strategy {
277         merge_codegen_units(&mut initial_partitioning, count, &tcx.crate_name.as_str());
278
279         debug_dump(scx, "POST MERGING:", initial_partitioning.codegen_units.iter());
280     }
281
282     // In the next step, we use the inlining map to determine which addtional
283     // translation items have to go into each codegen unit. These additional
284     // translation items can be drop-glue, functions from external crates, and
285     // local functions the definition of which is marked with #[inline].
286     let post_inlining = place_inlined_translation_items(initial_partitioning,
287                                                         inlining_map);
288
289     debug_dump(scx, "POST INLINING:", post_inlining.0.iter());
290
291     // Finally, sort by codegen unit name, so that we get deterministic results
292     let mut result = post_inlining.0;
293     result.sort_by(|cgu1, cgu2| {
294         (&cgu1.name[..]).cmp(&cgu2.name[..])
295     });
296
297     result
298 }
299
300 struct PreInliningPartitioning<'tcx> {
301     codegen_units: Vec<CodegenUnit<'tcx>>,
302     roots: FxHashSet<TransItem<'tcx>>,
303 }
304
305 struct PostInliningPartitioning<'tcx>(Vec<CodegenUnit<'tcx>>);
306
307 fn place_root_translation_items<'a, 'tcx, I>(scx: &SharedCrateContext<'a, 'tcx>,
308                                              trans_items: I)
309                                              -> PreInliningPartitioning<'tcx>
310     where I: Iterator<Item = TransItem<'tcx>>
311 {
312     let tcx = scx.tcx();
313     let mut roots = FxHashSet();
314     let mut codegen_units = FxHashMap();
315     let is_incremental_build = tcx.sess.opts.incremental.is_some();
316
317     for trans_item in trans_items {
318         let is_root = trans_item.instantiation_mode(tcx) == InstantiationMode::GloballyShared;
319
320         if is_root {
321             let characteristic_def_id = characteristic_def_id_of_trans_item(scx, trans_item);
322             let is_volatile = is_incremental_build &&
323                               trans_item.is_generic_fn();
324
325             let codegen_unit_name = match characteristic_def_id {
326                 Some(def_id) => compute_codegen_unit_name(tcx, def_id, is_volatile),
327                 None => Symbol::intern(FALLBACK_CODEGEN_UNIT).as_str(),
328             };
329
330             let make_codegen_unit = || {
331                 CodegenUnit::empty(codegen_unit_name.clone())
332             };
333
334             let mut codegen_unit = codegen_units.entry(codegen_unit_name.clone())
335                                                 .or_insert_with(make_codegen_unit);
336
337             let linkage = match trans_item.explicit_linkage(tcx) {
338                 Some(explicit_linkage) => explicit_linkage,
339                 None => {
340                     match trans_item {
341                         TransItem::Fn(..) |
342                         TransItem::Static(..) => llvm::ExternalLinkage,
343                         TransItem::DropGlue(..) => unreachable!(),
344                     }
345                 }
346             };
347
348             codegen_unit.items.insert(trans_item, linkage);
349             roots.insert(trans_item);
350         }
351     }
352
353     // always ensure we have at least one CGU; otherwise, if we have a
354     // crate with just types (for example), we could wind up with no CGU
355     if codegen_units.is_empty() {
356         let codegen_unit_name = Symbol::intern(FALLBACK_CODEGEN_UNIT).as_str();
357         codegen_units.entry(codegen_unit_name.clone())
358                      .or_insert_with(|| CodegenUnit::empty(codegen_unit_name.clone()));
359     }
360
361     PreInliningPartitioning {
362         codegen_units: codegen_units.into_iter()
363                                     .map(|(_, codegen_unit)| codegen_unit)
364                                     .collect(),
365         roots: roots,
366     }
367 }
368
369 fn merge_codegen_units<'tcx>(initial_partitioning: &mut PreInliningPartitioning<'tcx>,
370                              target_cgu_count: usize,
371                              crate_name: &str) {
372     assert!(target_cgu_count >= 1);
373     let codegen_units = &mut initial_partitioning.codegen_units;
374
375     // Merge the two smallest codegen units until the target size is reached.
376     // Note that "size" is estimated here rather inaccurately as the number of
377     // translation items in a given unit. This could be improved on.
378     while codegen_units.len() > target_cgu_count {
379         // Sort small cgus to the back
380         codegen_units.sort_by_key(|cgu| -(cgu.items.len() as i64));
381         let smallest = codegen_units.pop().unwrap();
382         let second_smallest = codegen_units.last_mut().unwrap();
383
384         for (k, v) in smallest.items.into_iter() {
385             second_smallest.items.insert(k, v);
386         }
387     }
388
389     for (index, cgu) in codegen_units.iter_mut().enumerate() {
390         cgu.name = numbered_codegen_unit_name(crate_name, index);
391     }
392
393     // If the initial partitioning contained less than target_cgu_count to begin
394     // with, we won't have enough codegen units here, so add a empty units until
395     // we reach the target count
396     while codegen_units.len() < target_cgu_count {
397         let index = codegen_units.len();
398         codegen_units.push(
399             CodegenUnit::empty(numbered_codegen_unit_name(crate_name, index)));
400     }
401 }
402
403 fn place_inlined_translation_items<'tcx>(initial_partitioning: PreInliningPartitioning<'tcx>,
404                                          inlining_map: &InliningMap<'tcx>)
405                                          -> PostInliningPartitioning<'tcx> {
406     let mut new_partitioning = Vec::new();
407
408     for codegen_unit in &initial_partitioning.codegen_units[..] {
409         // Collect all items that need to be available in this codegen unit
410         let mut reachable = FxHashSet();
411         for root in codegen_unit.items.keys() {
412             follow_inlining(*root, inlining_map, &mut reachable);
413         }
414
415         let mut new_codegen_unit =
416             CodegenUnit::empty(codegen_unit.name.clone());
417
418         // Add all translation items that are not already there
419         for trans_item in reachable {
420             if let Some(linkage) = codegen_unit.items.get(&trans_item) {
421                 // This is a root, just copy it over
422                 new_codegen_unit.items.insert(trans_item, *linkage);
423             } else {
424                 if initial_partitioning.roots.contains(&trans_item) {
425                     bug!("GloballyShared trans-item inlined into other CGU: \
426                           {:?}", trans_item);
427                 }
428
429                 // This is a cgu-private copy
430                 new_codegen_unit.items.insert(trans_item, llvm::InternalLinkage);
431             }
432         }
433
434         new_partitioning.push(new_codegen_unit);
435     }
436
437     return PostInliningPartitioning(new_partitioning);
438
439     fn follow_inlining<'tcx>(trans_item: TransItem<'tcx>,
440                              inlining_map: &InliningMap<'tcx>,
441                              visited: &mut FxHashSet<TransItem<'tcx>>) {
442         if !visited.insert(trans_item) {
443             return;
444         }
445
446         inlining_map.with_inlining_candidates(trans_item, |target| {
447             follow_inlining(target, inlining_map, visited);
448         });
449     }
450 }
451
452 fn characteristic_def_id_of_trans_item<'a, 'tcx>(scx: &SharedCrateContext<'a, 'tcx>,
453                                                  trans_item: TransItem<'tcx>)
454                                                  -> Option<DefId> {
455     let tcx = scx.tcx();
456     match trans_item {
457         TransItem::Fn(instance) => {
458             // If this is a method, we want to put it into the same module as
459             // its self-type. If the self-type does not provide a characteristic
460             // DefId, we use the location of the impl after all.
461
462             if tcx.trait_of_item(instance.def).is_some() {
463                 let self_ty = instance.substs.type_at(0);
464                 // This is an implementation of a trait method.
465                 return characteristic_def_id_of_type(self_ty).or(Some(instance.def));
466             }
467
468             if let Some(impl_def_id) = tcx.impl_of_method(instance.def) {
469                 // This is a method within an inherent impl, find out what the
470                 // self-type is:
471                 let impl_self_ty = tcx.item_type(impl_def_id);
472                 let impl_self_ty = tcx.erase_regions(&impl_self_ty);
473                 let impl_self_ty = monomorphize::apply_param_substs(scx,
474                                                                     instance.substs,
475                                                                     &impl_self_ty);
476
477                 if let Some(def_id) = characteristic_def_id_of_type(impl_self_ty) {
478                     return Some(def_id);
479                 }
480             }
481
482             Some(instance.def)
483         }
484         TransItem::DropGlue(dg) => characteristic_def_id_of_type(dg.ty()),
485         TransItem::Static(node_id) => Some(tcx.map.local_def_id(node_id)),
486     }
487 }
488
489 fn compute_codegen_unit_name<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
490                                        def_id: DefId,
491                                        volatile: bool)
492                                        -> InternedString {
493     // Unfortunately we cannot just use the `ty::item_path` infrastructure here
494     // because we need paths to modules and the DefIds of those are not
495     // available anymore for external items.
496     let mut mod_path = String::with_capacity(64);
497
498     let def_path = tcx.def_path(def_id);
499     mod_path.push_str(&tcx.crate_name(def_path.krate).as_str());
500
501     for part in tcx.def_path(def_id)
502                    .data
503                    .iter()
504                    .take_while(|part| {
505                         match part.data {
506                             DefPathData::Module(..) => true,
507                             _ => false,
508                         }
509                     }) {
510         mod_path.push_str("-");
511         mod_path.push_str(&part.data.as_interned_str());
512     }
513
514     if volatile {
515         mod_path.push_str(".volatile");
516     }
517
518     return Symbol::intern(&mod_path[..]).as_str();
519 }
520
521 fn numbered_codegen_unit_name(crate_name: &str, index: usize) -> InternedString {
522     Symbol::intern(&format!("{}{}{}", crate_name, NUMBERED_CODEGEN_UNIT_MARKER, index)).as_str()
523 }
524
525 fn debug_dump<'a, 'b, 'tcx, I>(scx: &SharedCrateContext<'a, 'tcx>,
526                                label: &str,
527                                cgus: I)
528     where I: Iterator<Item=&'b CodegenUnit<'tcx>>,
529           'tcx: 'a + 'b
530 {
531     if cfg!(debug_assertions) {
532         debug!("{}", label);
533         for cgu in cgus {
534             let symbol_map = SymbolMap::build(scx, cgu.items
535                                                       .iter()
536                                                       .map(|(&trans_item, _)| trans_item));
537             debug!("CodegenUnit {}:", cgu.name);
538
539             for (trans_item, linkage) in &cgu.items {
540                 let symbol_name = symbol_map.get_or_compute(scx, *trans_item);
541                 let symbol_hash_start = symbol_name.rfind('h');
542                 let symbol_hash = symbol_hash_start.map(|i| &symbol_name[i ..])
543                                                    .unwrap_or("<no hash>");
544
545                 debug!(" - {} [{:?}] [{}]",
546                        trans_item.to_string(scx.tcx()),
547                        linkage,
548                        symbol_hash);
549             }
550
551             debug!("");
552         }
553     }
554 }