]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_monomorphize/src/partitioning/mod.rs
Rollup merge of #85766 - workingjubilee:file-options, r=yaahc
[rust.git] / compiler / rustc_monomorphize / src / partitioning / mod.rs
1 //! Partitioning Codegen Units for Incremental Compilation
2 //! ======================================================
3 //!
4 //! The task of this module is to take the complete set of monomorphizations of
5 //! a crate and produce a set of codegen units from it, where a codegen unit
6 //! is a named set of (mono-item, linkage) pairs. That is, this module
7 //! decides which monomorphization appears in which codegen units with which
8 //! linkage. The following paragraphs describe some of the background on the
9 //! partitioning scheme.
10 //!
11 //! The most important opportunity for saving on compilation time with
12 //! incremental compilation is to avoid re-codegenning and re-optimizing code.
13 //! Since the unit of codegen and optimization for LLVM is "modules" or, how
14 //! we call them "codegen units", the particulars of how much time can be saved
15 //! by incremental compilation are tightly linked to how the output program is
16 //! partitioned into these codegen units prior to passing it to LLVM --
17 //! especially because we have to treat codegen units as opaque entities once
18 //! they are created: There is no way for us to incrementally update an existing
19 //! LLVM module and so we have to build any such module from scratch if it was
20 //! affected by some change in the source code.
21 //!
22 //! From that point of view it would make sense to maximize the number of
23 //! codegen units by, for example, putting each function into its own module.
24 //! That way only those modules would have to be re-compiled that were actually
25 //! affected by some change, minimizing the number of functions that could have
26 //! been re-used but just happened to be located in a module that is
27 //! re-compiled.
28 //!
29 //! However, since LLVM optimization does not work across module boundaries,
30 //! using such a highly granular partitioning would lead to very slow runtime
31 //! code since it would effectively prohibit inlining and other inter-procedure
32 //! optimizations. We want to avoid that as much as possible.
33 //!
34 //! Thus we end up with a trade-off: The bigger the codegen units, the better
35 //! LLVM's optimizer can do its work, but also the smaller the compilation time
36 //! reduction we get from incremental compilation.
37 //!
38 //! Ideally, we would create a partitioning such that there are few big codegen
39 //! units with few interdependencies between them. For now though, we use the
40 //! following heuristic to determine the partitioning:
41 //!
42 //! - There are two codegen units for every source-level module:
43 //! - One for "stable", that is non-generic, code
44 //! - One for more "volatile" code, i.e., monomorphized instances of functions
45 //!   defined in that module
46 //!
47 //! In order to see why this heuristic makes sense, let's take a look at when a
48 //! codegen unit can get invalidated:
49 //!
50 //! 1. The most straightforward case is when the BODY of a function or global
51 //! changes. Then any codegen unit containing the code for that item has to be
52 //! re-compiled. Note that this includes all codegen units where the function
53 //! has been inlined.
54 //!
55 //! 2. The next case is when the SIGNATURE of a function or global changes. In
56 //! this case, all codegen units containing a REFERENCE to that item have to be
57 //! re-compiled. This is a superset of case 1.
58 //!
59 //! 3. The final and most subtle case is when a REFERENCE to a generic function
60 //! is added or removed somewhere. Even though the definition of the function
61 //! might be unchanged, a new REFERENCE might introduce a new monomorphized
62 //! instance of this function which has to be placed and compiled somewhere.
63 //! Conversely, when removing a REFERENCE, it might have been the last one with
64 //! that particular set of generic arguments and thus we have to remove it.
65 //!
66 //! From the above we see that just using one codegen unit per source-level
67 //! module is not such a good idea, since just adding a REFERENCE to some
68 //! generic item somewhere else would invalidate everything within the module
69 //! containing the generic item. The heuristic above reduces this detrimental
70 //! side-effect of references a little by at least not touching the non-generic
71 //! code of the module.
72 //!
73 //! A Note on Inlining
74 //! ------------------
75 //! As briefly mentioned above, in order for LLVM to be able to inline a
76 //! function call, the body of the function has to be available in the LLVM
77 //! module where the call is made. This has a few consequences for partitioning:
78 //!
79 //! - The partitioning algorithm has to take care of placing functions into all
80 //!   codegen units where they should be available for inlining. It also has to
81 //!   decide on the correct linkage for these functions.
82 //!
83 //! - The partitioning algorithm has to know which functions are likely to get
84 //!   inlined, so it can distribute function instantiations accordingly. Since
85 //!   there is no way of knowing for sure which functions LLVM will decide to
86 //!   inline in the end, we apply a heuristic here: Only functions marked with
87 //!   `#[inline]` are considered for inlining by the partitioner. The current
88 //!   implementation will not try to determine if a function is likely to be
89 //!   inlined by looking at the functions definition.
90 //!
91 //! Note though that as a side-effect of creating a codegen units per
92 //! source-level module, functions from the same module will be available for
93 //! inlining, even when they are not marked `#[inline]`.
94
95 mod default;
96 mod merging;
97
98 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
99 use rustc_data_structures::sync;
100 use rustc_hir::def_id::DefIdSet;
101 use rustc_middle::mir::mono::MonoItem;
102 use rustc_middle::mir::mono::{CodegenUnit, Linkage};
103 use rustc_middle::ty::print::with_no_trimmed_paths;
104 use rustc_middle::ty::query::Providers;
105 use rustc_middle::ty::TyCtxt;
106 use rustc_span::symbol::Symbol;
107
108 use crate::collector::InliningMap;
109 use crate::collector::{self, MonoItemCollectionMode};
110
111 pub struct PartitioningCx<'a, 'tcx> {
112     tcx: TyCtxt<'tcx>,
113     target_cgu_count: usize,
114     inlining_map: &'a InliningMap<'tcx>,
115 }
116
117 trait Partitioner<'tcx> {
118     fn place_root_mono_items(
119         &mut self,
120         cx: &PartitioningCx<'_, 'tcx>,
121         mono_items: &mut dyn Iterator<Item = MonoItem<'tcx>>,
122     ) -> PreInliningPartitioning<'tcx>;
123
124     fn merge_codegen_units(
125         &mut self,
126         cx: &PartitioningCx<'_, 'tcx>,
127         initial_partitioning: &mut PreInliningPartitioning<'tcx>,
128     );
129
130     fn place_inlined_mono_items(
131         &mut self,
132         cx: &PartitioningCx<'_, 'tcx>,
133         initial_partitioning: PreInliningPartitioning<'tcx>,
134     ) -> PostInliningPartitioning<'tcx>;
135
136     fn internalize_symbols(
137         &mut self,
138         cx: &PartitioningCx<'_, 'tcx>,
139         partitioning: &mut PostInliningPartitioning<'tcx>,
140     );
141 }
142
143 fn get_partitioner<'tcx>(tcx: TyCtxt<'tcx>) -> Box<dyn Partitioner<'tcx>> {
144     let strategy = match &tcx.sess.opts.debugging_opts.cgu_partitioning_strategy {
145         None => "default",
146         Some(s) => &s[..],
147     };
148
149     match strategy {
150         "default" => Box::new(default::DefaultPartitioning),
151         _ => tcx.sess.fatal("unknown partitioning strategy"),
152     }
153 }
154
155 pub fn partition<'tcx>(
156     tcx: TyCtxt<'tcx>,
157     mono_items: &mut dyn Iterator<Item = MonoItem<'tcx>>,
158     max_cgu_count: usize,
159     inlining_map: &InliningMap<'tcx>,
160 ) -> Vec<CodegenUnit<'tcx>> {
161     let _prof_timer = tcx.prof.generic_activity("cgu_partitioning");
162
163     let mut partitioner = get_partitioner(tcx);
164     let cx = &PartitioningCx { tcx, target_cgu_count: max_cgu_count, inlining_map };
165     // In the first step, we place all regular monomorphizations into their
166     // respective 'home' codegen unit. Regular monomorphizations are all
167     // functions and statics defined in the local crate.
168     let mut initial_partitioning = {
169         let _prof_timer = tcx.prof.generic_activity("cgu_partitioning_place_roots");
170         partitioner.place_root_mono_items(cx, mono_items)
171     };
172
173     initial_partitioning.codegen_units.iter_mut().for_each(|cgu| cgu.estimate_size(tcx));
174
175     debug_dump(tcx, "INITIAL PARTITIONING:", initial_partitioning.codegen_units.iter());
176
177     // Merge until we have at most `max_cgu_count` codegen units.
178     {
179         let _prof_timer = tcx.prof.generic_activity("cgu_partitioning_merge_cgus");
180         partitioner.merge_codegen_units(cx, &mut initial_partitioning);
181         debug_dump(tcx, "POST MERGING:", initial_partitioning.codegen_units.iter());
182     }
183
184     // In the next step, we use the inlining map to determine which additional
185     // monomorphizations have to go into each codegen unit. These additional
186     // monomorphizations can be drop-glue, functions from external crates, and
187     // local functions the definition of which is marked with `#[inline]`.
188     let mut post_inlining = {
189         let _prof_timer = tcx.prof.generic_activity("cgu_partitioning_place_inline_items");
190         partitioner.place_inlined_mono_items(cx, initial_partitioning)
191     };
192
193     post_inlining.codegen_units.iter_mut().for_each(|cgu| cgu.estimate_size(tcx));
194
195     debug_dump(tcx, "POST INLINING:", post_inlining.codegen_units.iter());
196
197     // Next we try to make as many symbols "internal" as possible, so LLVM has
198     // more freedom to optimize.
199     if !tcx.sess.link_dead_code() {
200         let _prof_timer = tcx.prof.generic_activity("cgu_partitioning_internalize_symbols");
201         partitioner.internalize_symbols(cx, &mut post_inlining);
202     }
203
204     // Finally, sort by codegen unit name, so that we get deterministic results.
205     let PostInliningPartitioning {
206         codegen_units: mut result,
207         mono_item_placements: _,
208         internalization_candidates: _,
209     } = post_inlining;
210
211     result.sort_by_cached_key(|cgu| cgu.name().as_str());
212
213     result
214 }
215
216 pub struct PreInliningPartitioning<'tcx> {
217     codegen_units: Vec<CodegenUnit<'tcx>>,
218     roots: FxHashSet<MonoItem<'tcx>>,
219     internalization_candidates: FxHashSet<MonoItem<'tcx>>,
220 }
221
222 /// For symbol internalization, we need to know whether a symbol/mono-item is
223 /// accessed from outside the codegen unit it is defined in. This type is used
224 /// to keep track of that.
225 #[derive(Clone, PartialEq, Eq, Debug)]
226 enum MonoItemPlacement {
227     SingleCgu { cgu_name: Symbol },
228     MultipleCgus,
229 }
230
231 struct PostInliningPartitioning<'tcx> {
232     codegen_units: Vec<CodegenUnit<'tcx>>,
233     mono_item_placements: FxHashMap<MonoItem<'tcx>, MonoItemPlacement>,
234     internalization_candidates: FxHashSet<MonoItem<'tcx>>,
235 }
236
237 fn debug_dump<'a, 'tcx, I>(tcx: TyCtxt<'tcx>, label: &str, cgus: I)
238 where
239     I: Iterator<Item = &'a CodegenUnit<'tcx>>,
240     'tcx: 'a,
241 {
242     let dump = move || {
243         use std::fmt::Write;
244
245         let s = &mut String::new();
246         let _ = writeln!(s, "{}", label);
247         for cgu in cgus {
248             let _ =
249                 writeln!(s, "CodegenUnit {} estimated size {} :", cgu.name(), cgu.size_estimate());
250
251             for (mono_item, linkage) in cgu.items() {
252                 let symbol_name = mono_item.symbol_name(tcx).name;
253                 let symbol_hash_start = symbol_name.rfind('h');
254                 let symbol_hash = symbol_hash_start.map_or("<no hash>", |i| &symbol_name[i..]);
255
256                 let _ = writeln!(
257                     s,
258                     " - {} [{:?}] [{}] estimated size {}",
259                     mono_item,
260                     linkage,
261                     symbol_hash,
262                     mono_item.size_estimate(tcx)
263                 );
264             }
265
266             let _ = writeln!(s, "");
267         }
268
269         std::mem::take(s)
270     };
271
272     debug!("{}", dump());
273 }
274
275 #[inline(never)] // give this a place in the profiler
276 fn assert_symbols_are_distinct<'a, 'tcx, I>(tcx: TyCtxt<'tcx>, mono_items: I)
277 where
278     I: Iterator<Item = &'a MonoItem<'tcx>>,
279     'tcx: 'a,
280 {
281     let _prof_timer = tcx.prof.generic_activity("assert_symbols_are_distinct");
282
283     let mut symbols: Vec<_> =
284         mono_items.map(|mono_item| (mono_item, mono_item.symbol_name(tcx))).collect();
285
286     symbols.sort_by_key(|sym| sym.1);
287
288     for &[(mono_item1, ref sym1), (mono_item2, ref sym2)] in symbols.array_windows() {
289         if sym1 == sym2 {
290             let span1 = mono_item1.local_span(tcx);
291             let span2 = mono_item2.local_span(tcx);
292
293             // Deterministically select one of the spans for error reporting
294             let span = match (span1, span2) {
295                 (Some(span1), Some(span2)) => {
296                     Some(if span1.lo().0 > span2.lo().0 { span1 } else { span2 })
297                 }
298                 (span1, span2) => span1.or(span2),
299             };
300
301             let error_message = format!("symbol `{}` is already defined", sym1);
302
303             if let Some(span) = span {
304                 tcx.sess.span_fatal(span, &error_message)
305             } else {
306                 tcx.sess.fatal(&error_message)
307             }
308         }
309     }
310 }
311
312 fn collect_and_partition_mono_items<'tcx>(
313     tcx: TyCtxt<'tcx>,
314     (): (),
315 ) -> (&'tcx DefIdSet, &'tcx [CodegenUnit<'tcx>]) {
316     let collection_mode = match tcx.sess.opts.debugging_opts.print_mono_items {
317         Some(ref s) => {
318             let mode_string = s.to_lowercase();
319             let mode_string = mode_string.trim();
320             if mode_string == "eager" {
321                 MonoItemCollectionMode::Eager
322             } else {
323                 if mode_string != "lazy" {
324                     let message = format!(
325                         "Unknown codegen-item collection mode '{}'. \
326                                            Falling back to 'lazy' mode.",
327                         mode_string
328                     );
329                     tcx.sess.warn(&message);
330                 }
331
332                 MonoItemCollectionMode::Lazy
333             }
334         }
335         None => {
336             if tcx.sess.link_dead_code() {
337                 MonoItemCollectionMode::Eager
338             } else {
339                 MonoItemCollectionMode::Lazy
340             }
341         }
342     };
343
344     let (items, inlining_map) = collector::collect_crate_mono_items(tcx, collection_mode);
345
346     tcx.sess.abort_if_errors();
347
348     let (codegen_units, _) = tcx.sess.time("partition_and_assert_distinct_symbols", || {
349         sync::join(
350             || {
351                 let mut codegen_units = partition(
352                     tcx,
353                     &mut items.iter().cloned(),
354                     tcx.sess.codegen_units(),
355                     &inlining_map,
356                 );
357                 codegen_units[0].make_primary();
358                 &*tcx.arena.alloc_from_iter(codegen_units)
359             },
360             || assert_symbols_are_distinct(tcx, items.iter()),
361         )
362     });
363
364     if tcx.prof.enabled() {
365         // Record CGU size estimates for self-profiling.
366         for cgu in codegen_units {
367             tcx.prof.artifact_size(
368                 "codegen_unit_size_estimate",
369                 &cgu.name().as_str()[..],
370                 cgu.size_estimate() as u64,
371             );
372         }
373     }
374
375     let mono_items: DefIdSet = items
376         .iter()
377         .filter_map(|mono_item| match *mono_item {
378             MonoItem::Fn(ref instance) => Some(instance.def_id()),
379             MonoItem::Static(def_id) => Some(def_id),
380             _ => None,
381         })
382         .collect();
383
384     if tcx.sess.opts.debugging_opts.print_mono_items.is_some() {
385         let mut item_to_cgus: FxHashMap<_, Vec<_>> = Default::default();
386
387         for cgu in codegen_units {
388             for (&mono_item, &linkage) in cgu.items() {
389                 item_to_cgus.entry(mono_item).or_default().push((cgu.name(), linkage));
390             }
391         }
392
393         let mut item_keys: Vec<_> = items
394             .iter()
395             .map(|i| {
396                 let mut output = with_no_trimmed_paths(|| i.to_string());
397                 output.push_str(" @@");
398                 let mut empty = Vec::new();
399                 let cgus = item_to_cgus.get_mut(i).unwrap_or(&mut empty);
400                 cgus.sort_by_key(|(name, _)| *name);
401                 cgus.dedup();
402                 for &(ref cgu_name, (linkage, _)) in cgus.iter() {
403                     output.push(' ');
404                     output.push_str(&cgu_name.as_str());
405
406                     let linkage_abbrev = match linkage {
407                         Linkage::External => "External",
408                         Linkage::AvailableExternally => "Available",
409                         Linkage::LinkOnceAny => "OnceAny",
410                         Linkage::LinkOnceODR => "OnceODR",
411                         Linkage::WeakAny => "WeakAny",
412                         Linkage::WeakODR => "WeakODR",
413                         Linkage::Appending => "Appending",
414                         Linkage::Internal => "Internal",
415                         Linkage::Private => "Private",
416                         Linkage::ExternalWeak => "ExternalWeak",
417                         Linkage::Common => "Common",
418                     };
419
420                     output.push('[');
421                     output.push_str(linkage_abbrev);
422                     output.push(']');
423                 }
424                 output
425             })
426             .collect();
427
428         item_keys.sort();
429
430         for item in item_keys {
431             println!("MONO_ITEM {}", item);
432         }
433     }
434
435     (tcx.arena.alloc(mono_items), codegen_units)
436 }
437
438 fn codegened_and_inlined_items<'tcx>(tcx: TyCtxt<'tcx>, (): ()) -> &'tcx DefIdSet {
439     let (items, cgus) = tcx.collect_and_partition_mono_items(());
440     let mut visited = DefIdSet::default();
441     let mut result = items.clone();
442
443     for cgu in cgus {
444         for (item, _) in cgu.items() {
445             if let MonoItem::Fn(ref instance) = item {
446                 let did = instance.def_id();
447                 if !visited.insert(did) {
448                     continue;
449                 }
450                 for scope in &tcx.instance_mir(instance.def).source_scopes {
451                     if let Some((ref inlined, _)) = scope.inlined {
452                         result.insert(inlined.def_id());
453                     }
454                 }
455             }
456         }
457     }
458
459     tcx.arena.alloc(result)
460 }
461
462 pub fn provide(providers: &mut Providers) {
463     providers.collect_and_partition_mono_items = collect_and_partition_mono_items;
464     providers.codegened_and_inlined_items = codegened_and_inlined_items;
465
466     providers.is_codegened_item = |tcx, def_id| {
467         let (all_mono_items, _) = tcx.collect_and_partition_mono_items(());
468         all_mono_items.contains(&def_id)
469     };
470
471     providers.codegen_unit = |tcx, name| {
472         let (_, all) = tcx.collect_and_partition_mono_items(());
473         all.iter()
474             .find(|cgu| cgu.name() == name)
475             .unwrap_or_else(|| panic!("failed to find cgu with name {:?}", name))
476     };
477 }