]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_monomorphize/src/partitioning/mod.rs
Auto merge of #100754 - davidtwco:translation-incremental, r=compiler-errors
[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 std::cmp;
99 use std::fs::{self, File};
100 use std::io::{BufWriter, Write};
101 use std::path::{Path, PathBuf};
102
103 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
104 use rustc_data_structures::sync;
105 use rustc_hir::def_id::{DefIdSet, LOCAL_CRATE};
106 use rustc_middle::mir;
107 use rustc_middle::mir::mono::MonoItem;
108 use rustc_middle::mir::mono::{CodegenUnit, Linkage};
109 use rustc_middle::ty::print::with_no_trimmed_paths;
110 use rustc_middle::ty::query::Providers;
111 use rustc_middle::ty::TyCtxt;
112 use rustc_session::config::{DumpMonoStatsFormat, SwitchWithOptPath};
113 use rustc_span::symbol::Symbol;
114
115 use crate::collector::InliningMap;
116 use crate::collector::{self, MonoItemCollectionMode};
117 use crate::errors::{
118     CouldntDumpMonoStats, SymbolAlreadyDefined, UnknownCguCollectionMode, UnknownPartitionStrategy,
119 };
120
121 pub struct PartitioningCx<'a, 'tcx> {
122     tcx: TyCtxt<'tcx>,
123     target_cgu_count: usize,
124     inlining_map: &'a InliningMap<'tcx>,
125 }
126
127 trait Partitioner<'tcx> {
128     fn place_root_mono_items(
129         &mut self,
130         cx: &PartitioningCx<'_, 'tcx>,
131         mono_items: &mut dyn Iterator<Item = MonoItem<'tcx>>,
132     ) -> PreInliningPartitioning<'tcx>;
133
134     fn merge_codegen_units(
135         &mut self,
136         cx: &PartitioningCx<'_, 'tcx>,
137         initial_partitioning: &mut PreInliningPartitioning<'tcx>,
138     );
139
140     fn place_inlined_mono_items(
141         &mut self,
142         cx: &PartitioningCx<'_, 'tcx>,
143         initial_partitioning: PreInliningPartitioning<'tcx>,
144     ) -> PostInliningPartitioning<'tcx>;
145
146     fn internalize_symbols(
147         &mut self,
148         cx: &PartitioningCx<'_, 'tcx>,
149         partitioning: &mut PostInliningPartitioning<'tcx>,
150     );
151 }
152
153 fn get_partitioner<'tcx>(tcx: TyCtxt<'tcx>) -> Box<dyn Partitioner<'tcx>> {
154     let strategy = match &tcx.sess.opts.unstable_opts.cgu_partitioning_strategy {
155         None => "default",
156         Some(s) => &s[..],
157     };
158
159     match strategy {
160         "default" => Box::new(default::DefaultPartitioning),
161         _ => {
162             tcx.sess.emit_fatal(UnknownPartitionStrategy);
163         }
164     }
165 }
166
167 pub fn partition<'tcx>(
168     tcx: TyCtxt<'tcx>,
169     mono_items: &mut dyn Iterator<Item = MonoItem<'tcx>>,
170     max_cgu_count: usize,
171     inlining_map: &InliningMap<'tcx>,
172 ) -> Vec<CodegenUnit<'tcx>> {
173     let _prof_timer = tcx.prof.generic_activity("cgu_partitioning");
174
175     let mut partitioner = get_partitioner(tcx);
176     let cx = &PartitioningCx { tcx, target_cgu_count: max_cgu_count, inlining_map };
177     // In the first step, we place all regular monomorphizations into their
178     // respective 'home' codegen unit. Regular monomorphizations are all
179     // functions and statics defined in the local crate.
180     let mut initial_partitioning = {
181         let _prof_timer = tcx.prof.generic_activity("cgu_partitioning_place_roots");
182         partitioner.place_root_mono_items(cx, mono_items)
183     };
184
185     initial_partitioning.codegen_units.iter_mut().for_each(|cgu| cgu.create_size_estimate(tcx));
186
187     debug_dump(tcx, "INITIAL PARTITIONING:", initial_partitioning.codegen_units.iter());
188
189     // Merge until we have at most `max_cgu_count` codegen units.
190     {
191         let _prof_timer = tcx.prof.generic_activity("cgu_partitioning_merge_cgus");
192         partitioner.merge_codegen_units(cx, &mut initial_partitioning);
193         debug_dump(tcx, "POST MERGING:", initial_partitioning.codegen_units.iter());
194     }
195
196     // In the next step, we use the inlining map to determine which additional
197     // monomorphizations have to go into each codegen unit. These additional
198     // monomorphizations can be drop-glue, functions from external crates, and
199     // local functions the definition of which is marked with `#[inline]`.
200     let mut post_inlining = {
201         let _prof_timer = tcx.prof.generic_activity("cgu_partitioning_place_inline_items");
202         partitioner.place_inlined_mono_items(cx, initial_partitioning)
203     };
204
205     post_inlining.codegen_units.iter_mut().for_each(|cgu| cgu.create_size_estimate(tcx));
206
207     debug_dump(tcx, "POST INLINING:", post_inlining.codegen_units.iter());
208
209     // Next we try to make as many symbols "internal" as possible, so LLVM has
210     // more freedom to optimize.
211     if !tcx.sess.link_dead_code() {
212         let _prof_timer = tcx.prof.generic_activity("cgu_partitioning_internalize_symbols");
213         partitioner.internalize_symbols(cx, &mut post_inlining);
214     }
215
216     let instrument_dead_code =
217         tcx.sess.instrument_coverage() && !tcx.sess.instrument_coverage_except_unused_functions();
218
219     if instrument_dead_code {
220         assert!(
221             post_inlining.codegen_units.len() > 0,
222             "There must be at least one CGU that code coverage data can be generated in."
223         );
224
225         // Find the smallest CGU that has exported symbols and put the dead
226         // function stubs in that CGU. We look for exported symbols to increase
227         // the likelihood the linker won't throw away the dead functions.
228         // FIXME(#92165): In order to truly resolve this, we need to make sure
229         // the object file (CGU) containing the dead function stubs is included
230         // in the final binary. This will probably require forcing these
231         // function symbols to be included via `-u` or `/include` linker args.
232         let mut cgus: Vec<_> = post_inlining.codegen_units.iter_mut().collect();
233         cgus.sort_by_key(|cgu| cgu.size_estimate());
234
235         let dead_code_cgu =
236             if let Some(cgu) = cgus.into_iter().rev().find(|cgu| {
237                 cgu.items().iter().any(|(_, (linkage, _))| *linkage == Linkage::External)
238             }) {
239                 cgu
240             } else {
241                 // If there are no CGUs that have externally linked items,
242                 // then we just pick the first CGU as a fallback.
243                 &mut post_inlining.codegen_units[0]
244             };
245         dead_code_cgu.make_code_coverage_dead_code_cgu();
246     }
247
248     // Finally, sort by codegen unit name, so that we get deterministic results.
249     let PostInliningPartitioning {
250         codegen_units: mut result,
251         mono_item_placements: _,
252         internalization_candidates: _,
253     } = post_inlining;
254
255     result.sort_by(|a, b| a.name().as_str().partial_cmp(b.name().as_str()).unwrap());
256
257     result
258 }
259
260 pub struct PreInliningPartitioning<'tcx> {
261     codegen_units: Vec<CodegenUnit<'tcx>>,
262     roots: FxHashSet<MonoItem<'tcx>>,
263     internalization_candidates: FxHashSet<MonoItem<'tcx>>,
264 }
265
266 /// For symbol internalization, we need to know whether a symbol/mono-item is
267 /// accessed from outside the codegen unit it is defined in. This type is used
268 /// to keep track of that.
269 #[derive(Clone, PartialEq, Eq, Debug)]
270 enum MonoItemPlacement {
271     SingleCgu { cgu_name: Symbol },
272     MultipleCgus,
273 }
274
275 struct PostInliningPartitioning<'tcx> {
276     codegen_units: Vec<CodegenUnit<'tcx>>,
277     mono_item_placements: FxHashMap<MonoItem<'tcx>, MonoItemPlacement>,
278     internalization_candidates: FxHashSet<MonoItem<'tcx>>,
279 }
280
281 fn debug_dump<'a, 'tcx, I>(tcx: TyCtxt<'tcx>, label: &str, cgus: I)
282 where
283     I: Iterator<Item = &'a CodegenUnit<'tcx>>,
284     'tcx: 'a,
285 {
286     let dump = move || {
287         use std::fmt::Write;
288
289         let s = &mut String::new();
290         let _ = writeln!(s, "{label}");
291         for cgu in cgus {
292             let _ =
293                 writeln!(s, "CodegenUnit {} estimated size {} :", cgu.name(), cgu.size_estimate());
294
295             for (mono_item, linkage) in cgu.items() {
296                 let symbol_name = mono_item.symbol_name(tcx).name;
297                 let symbol_hash_start = symbol_name.rfind('h');
298                 let symbol_hash = symbol_hash_start.map_or("<no hash>", |i| &symbol_name[i..]);
299
300                 let _ = writeln!(
301                     s,
302                     " - {} [{:?}] [{}] estimated size {}",
303                     mono_item,
304                     linkage,
305                     symbol_hash,
306                     mono_item.size_estimate(tcx)
307                 );
308             }
309
310             let _ = writeln!(s);
311         }
312
313         std::mem::take(s)
314     };
315
316     debug!("{}", dump());
317 }
318
319 #[inline(never)] // give this a place in the profiler
320 fn assert_symbols_are_distinct<'a, 'tcx, I>(tcx: TyCtxt<'tcx>, mono_items: I)
321 where
322     I: Iterator<Item = &'a MonoItem<'tcx>>,
323     'tcx: 'a,
324 {
325     let _prof_timer = tcx.prof.generic_activity("assert_symbols_are_distinct");
326
327     let mut symbols: Vec<_> =
328         mono_items.map(|mono_item| (mono_item, mono_item.symbol_name(tcx))).collect();
329
330     symbols.sort_by_key(|sym| sym.1);
331
332     for &[(mono_item1, ref sym1), (mono_item2, ref sym2)] in symbols.array_windows() {
333         if sym1 == sym2 {
334             let span1 = mono_item1.local_span(tcx);
335             let span2 = mono_item2.local_span(tcx);
336
337             // Deterministically select one of the spans for error reporting
338             let span = match (span1, span2) {
339                 (Some(span1), Some(span2)) => {
340                     Some(if span1.lo().0 > span2.lo().0 { span1 } else { span2 })
341                 }
342                 (span1, span2) => span1.or(span2),
343             };
344
345             tcx.sess.emit_fatal(SymbolAlreadyDefined { span, symbol: sym1.to_string() });
346         }
347     }
348 }
349
350 fn collect_and_partition_mono_items(tcx: TyCtxt<'_>, (): ()) -> (&DefIdSet, &[CodegenUnit<'_>]) {
351     let collection_mode = match tcx.sess.opts.unstable_opts.print_mono_items {
352         Some(ref s) => {
353             let mode = s.to_lowercase();
354             let mode = mode.trim();
355             if mode == "eager" {
356                 MonoItemCollectionMode::Eager
357             } else {
358                 if mode != "lazy" {
359                     tcx.sess.emit_warning(UnknownCguCollectionMode { mode });
360                 }
361
362                 MonoItemCollectionMode::Lazy
363             }
364         }
365         None => {
366             if tcx.sess.link_dead_code() {
367                 MonoItemCollectionMode::Eager
368             } else {
369                 MonoItemCollectionMode::Lazy
370             }
371         }
372     };
373
374     let (items, inlining_map) = collector::collect_crate_mono_items(tcx, collection_mode);
375
376     tcx.sess.abort_if_errors();
377
378     let (codegen_units, _) = tcx.sess.time("partition_and_assert_distinct_symbols", || {
379         sync::join(
380             || {
381                 let mut codegen_units = partition(
382                     tcx,
383                     &mut items.iter().cloned(),
384                     tcx.sess.codegen_units(),
385                     &inlining_map,
386                 );
387                 codegen_units[0].make_primary();
388                 &*tcx.arena.alloc_from_iter(codegen_units)
389             },
390             || assert_symbols_are_distinct(tcx, items.iter()),
391         )
392     });
393
394     if tcx.prof.enabled() {
395         // Record CGU size estimates for self-profiling.
396         for cgu in codegen_units {
397             tcx.prof.artifact_size(
398                 "codegen_unit_size_estimate",
399                 cgu.name().as_str(),
400                 cgu.size_estimate() as u64,
401             );
402         }
403     }
404
405     let mono_items: DefIdSet = items
406         .iter()
407         .filter_map(|mono_item| match *mono_item {
408             MonoItem::Fn(ref instance) => Some(instance.def_id()),
409             MonoItem::Static(def_id) => Some(def_id),
410             _ => None,
411         })
412         .collect();
413
414     // Output monomorphization stats per def_id
415     if let SwitchWithOptPath::Enabled(ref path) = tcx.sess.opts.unstable_opts.dump_mono_stats {
416         if let Err(err) =
417             dump_mono_items_stats(tcx, &codegen_units, path, tcx.crate_name(LOCAL_CRATE))
418         {
419             tcx.sess.emit_fatal(CouldntDumpMonoStats { error: err.to_string() });
420         }
421     }
422
423     if tcx.sess.opts.unstable_opts.print_mono_items.is_some() {
424         let mut item_to_cgus: FxHashMap<_, Vec<_>> = Default::default();
425
426         for cgu in codegen_units {
427             for (&mono_item, &linkage) in cgu.items() {
428                 item_to_cgus.entry(mono_item).or_default().push((cgu.name(), linkage));
429             }
430         }
431
432         let mut item_keys: Vec<_> = items
433             .iter()
434             .map(|i| {
435                 let mut output = with_no_trimmed_paths!(i.to_string());
436                 output.push_str(" @@");
437                 let mut empty = Vec::new();
438                 let cgus = item_to_cgus.get_mut(i).unwrap_or(&mut empty);
439                 cgus.sort_by_key(|(name, _)| *name);
440                 cgus.dedup();
441                 for &(ref cgu_name, (linkage, _)) in cgus.iter() {
442                     output.push(' ');
443                     output.push_str(cgu_name.as_str());
444
445                     let linkage_abbrev = match linkage {
446                         Linkage::External => "External",
447                         Linkage::AvailableExternally => "Available",
448                         Linkage::LinkOnceAny => "OnceAny",
449                         Linkage::LinkOnceODR => "OnceODR",
450                         Linkage::WeakAny => "WeakAny",
451                         Linkage::WeakODR => "WeakODR",
452                         Linkage::Appending => "Appending",
453                         Linkage::Internal => "Internal",
454                         Linkage::Private => "Private",
455                         Linkage::ExternalWeak => "ExternalWeak",
456                         Linkage::Common => "Common",
457                     };
458
459                     output.push('[');
460                     output.push_str(linkage_abbrev);
461                     output.push(']');
462                 }
463                 output
464             })
465             .collect();
466
467         item_keys.sort();
468
469         for item in item_keys {
470             println!("MONO_ITEM {item}");
471         }
472     }
473
474     (tcx.arena.alloc(mono_items), codegen_units)
475 }
476
477 /// Outputs stats about instantation counts and estimated size, per `MonoItem`'s
478 /// def, to a file in the given output directory.
479 fn dump_mono_items_stats<'tcx>(
480     tcx: TyCtxt<'tcx>,
481     codegen_units: &[CodegenUnit<'tcx>],
482     output_directory: &Option<PathBuf>,
483     crate_name: Symbol,
484 ) -> Result<(), Box<dyn std::error::Error>> {
485     let output_directory = if let Some(ref directory) = output_directory {
486         fs::create_dir_all(directory)?;
487         directory
488     } else {
489         Path::new(".")
490     };
491
492     let format = tcx.sess.opts.unstable_opts.dump_mono_stats_format;
493     let ext = format.extension();
494     let filename = format!("{crate_name}.mono_items.{ext}");
495     let output_path = output_directory.join(&filename);
496     let file = File::create(&output_path)?;
497     let mut file = BufWriter::new(file);
498
499     // Gather instantiated mono items grouped by def_id
500     let mut items_per_def_id: FxHashMap<_, Vec<_>> = Default::default();
501     for cgu in codegen_units {
502         for (&mono_item, _) in cgu.items() {
503             // Avoid variable-sized compiler-generated shims
504             if mono_item.is_user_defined() {
505                 items_per_def_id.entry(mono_item.def_id()).or_default().push(mono_item);
506             }
507         }
508     }
509
510     #[derive(serde::Serialize)]
511     struct MonoItem {
512         name: String,
513         instantiation_count: usize,
514         size_estimate: usize,
515         total_estimate: usize,
516     }
517
518     // Output stats sorted by total instantiated size, from heaviest to lightest
519     let mut stats: Vec<_> = items_per_def_id
520         .into_iter()
521         .map(|(def_id, items)| {
522             let name = with_no_trimmed_paths!(tcx.def_path_str(def_id));
523             let instantiation_count = items.len();
524             let size_estimate = items[0].size_estimate(tcx);
525             let total_estimate = instantiation_count * size_estimate;
526             MonoItem { name, instantiation_count, size_estimate, total_estimate }
527         })
528         .collect();
529     stats.sort_unstable_by_key(|item| cmp::Reverse(item.total_estimate));
530
531     if !stats.is_empty() {
532         match format {
533             DumpMonoStatsFormat::Json => serde_json::to_writer(file, &stats)?,
534             DumpMonoStatsFormat::Markdown => {
535                 writeln!(
536                     file,
537                     "| Item | Instantiation count | Estimated Cost Per Instantiation | Total Estimated Cost |"
538                 )?;
539                 writeln!(file, "| --- | ---: | ---: | ---: |")?;
540
541                 for MonoItem { name, instantiation_count, size_estimate, total_estimate } in stats {
542                     writeln!(
543                         file,
544                         "| `{name}` | {instantiation_count} | {size_estimate} | {total_estimate} |"
545                     )?;
546                 }
547             }
548         }
549     }
550
551     Ok(())
552 }
553
554 fn codegened_and_inlined_items(tcx: TyCtxt<'_>, (): ()) -> &DefIdSet {
555     let (items, cgus) = tcx.collect_and_partition_mono_items(());
556     let mut visited = DefIdSet::default();
557     let mut result = items.clone();
558
559     for cgu in cgus {
560         for (item, _) in cgu.items() {
561             if let MonoItem::Fn(ref instance) = item {
562                 let did = instance.def_id();
563                 if !visited.insert(did) {
564                     continue;
565                 }
566                 let body = tcx.instance_mir(instance.def);
567                 for block in body.basic_blocks.iter() {
568                     for statement in &block.statements {
569                         let mir::StatementKind::Coverage(_) = statement.kind else { continue };
570                         let scope = statement.source_info.scope;
571                         if let Some(inlined) = scope.inlined_instance(&body.source_scopes) {
572                             result.insert(inlined.def_id());
573                         }
574                     }
575                 }
576             }
577         }
578     }
579
580     tcx.arena.alloc(result)
581 }
582
583 pub fn provide(providers: &mut Providers) {
584     providers.collect_and_partition_mono_items = collect_and_partition_mono_items;
585     providers.codegened_and_inlined_items = codegened_and_inlined_items;
586
587     providers.is_codegened_item = |tcx, def_id| {
588         let (all_mono_items, _) = tcx.collect_and_partition_mono_items(());
589         all_mono_items.contains(&def_id)
590     };
591
592     providers.codegen_unit = |tcx, name| {
593         let (_, all) = tcx.collect_and_partition_mono_items(());
594         all.iter()
595             .find(|cgu| cgu.name() == name)
596             .unwrap_or_else(|| panic!("failed to find cgu with name {name:?}"))
597     };
598 }