]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_ssa/src/back/write.rs
Port pgo.sh to Python
[rust.git] / compiler / rustc_codegen_ssa / src / back / write.rs
1 use super::link::{self, ensure_removed};
2 use super::lto::{self, SerializedModule};
3 use super::symbol_export::symbol_name_for_instance_in_crate;
4
5 use crate::errors;
6 use crate::traits::*;
7 use crate::{
8     CachedModuleCodegen, CodegenResults, CompiledModule, CrateInfo, ModuleCodegen, ModuleKind,
9 };
10 use jobserver::{Acquired, Client};
11 use rustc_data_structures::fx::FxHashMap;
12 use rustc_data_structures::memmap::Mmap;
13 use rustc_data_structures::profiling::SelfProfilerRef;
14 use rustc_data_structures::profiling::TimingGuard;
15 use rustc_data_structures::profiling::VerboseTimingGuard;
16 use rustc_data_structures::sync::Lrc;
17 use rustc_errors::emitter::Emitter;
18 use rustc_errors::{translation::Translate, DiagnosticId, FatalError, Handler, Level};
19 use rustc_errors::{DiagnosticMessage, Style};
20 use rustc_fs_util::link_or_copy;
21 use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
22 use rustc_incremental::{
23     copy_cgu_workproduct_to_incr_comp_cache_dir, in_incr_comp_dir, in_incr_comp_dir_sess,
24 };
25 use rustc_metadata::EncodedMetadata;
26 use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
27 use rustc_middle::middle::exported_symbols::SymbolExportInfo;
28 use rustc_middle::ty::TyCtxt;
29 use rustc_session::cgu_reuse_tracker::CguReuseTracker;
30 use rustc_session::config::{self, CrateType, Lto, OutputFilenames, OutputType};
31 use rustc_session::config::{Passes, SwitchWithOptPath};
32 use rustc_session::Session;
33 use rustc_span::source_map::SourceMap;
34 use rustc_span::symbol::sym;
35 use rustc_span::{BytePos, FileName, InnerSpan, Pos, Span};
36 use rustc_target::spec::{MergeFunctions, SanitizerSet};
37
38 use std::any::Any;
39 use std::borrow::Cow;
40 use std::fs;
41 use std::io;
42 use std::marker::PhantomData;
43 use std::mem;
44 use std::path::{Path, PathBuf};
45 use std::str;
46 use std::sync::mpsc::{channel, Receiver, Sender};
47 use std::sync::Arc;
48 use std::thread;
49
50 const PRE_LTO_BC_EXT: &str = "pre-lto.bc";
51
52 /// What kind of object file to emit.
53 #[derive(Clone, Copy, PartialEq)]
54 pub enum EmitObj {
55     // No object file.
56     None,
57
58     // Just uncompressed llvm bitcode. Provides easy compatibility with
59     // emscripten's ecc compiler, when used as the linker.
60     Bitcode,
61
62     // Object code, possibly augmented with a bitcode section.
63     ObjectCode(BitcodeSection),
64 }
65
66 /// What kind of llvm bitcode section to embed in an object file.
67 #[derive(Clone, Copy, PartialEq)]
68 pub enum BitcodeSection {
69     // No bitcode section.
70     None,
71
72     // A full, uncompressed bitcode section.
73     Full,
74 }
75
76 /// Module-specific configuration for `optimize_and_codegen`.
77 pub struct ModuleConfig {
78     /// Names of additional optimization passes to run.
79     pub passes: Vec<String>,
80     /// Some(level) to optimize at a certain level, or None to run
81     /// absolutely no optimizations (used for the metadata module).
82     pub opt_level: Option<config::OptLevel>,
83
84     /// Some(level) to optimize binary size, or None to not affect program size.
85     pub opt_size: Option<config::OptLevel>,
86
87     pub pgo_gen: SwitchWithOptPath,
88     pub pgo_use: Option<PathBuf>,
89     pub pgo_sample_use: Option<PathBuf>,
90     pub debug_info_for_profiling: bool,
91     pub instrument_coverage: bool,
92     pub instrument_gcov: bool,
93
94     pub sanitizer: SanitizerSet,
95     pub sanitizer_recover: SanitizerSet,
96     pub sanitizer_memory_track_origins: usize,
97
98     // Flags indicating which outputs to produce.
99     pub emit_pre_lto_bc: bool,
100     pub emit_no_opt_bc: bool,
101     pub emit_bc: bool,
102     pub emit_ir: bool,
103     pub emit_asm: bool,
104     pub emit_obj: EmitObj,
105     pub emit_thin_lto: bool,
106     pub bc_cmdline: String,
107
108     // Miscellaneous flags.  These are mostly copied from command-line
109     // options.
110     pub verify_llvm_ir: bool,
111     pub no_prepopulate_passes: bool,
112     pub no_builtins: bool,
113     pub time_module: bool,
114     pub vectorize_loop: bool,
115     pub vectorize_slp: bool,
116     pub merge_functions: bool,
117     pub inline_threshold: Option<u32>,
118     pub emit_lifetime_markers: bool,
119     pub llvm_plugins: Vec<String>,
120 }
121
122 impl ModuleConfig {
123     fn new(
124         kind: ModuleKind,
125         sess: &Session,
126         no_builtins: bool,
127         is_compiler_builtins: bool,
128     ) -> ModuleConfig {
129         // If it's a regular module, use `$regular`, otherwise use `$other`.
130         // `$regular` and `$other` are evaluated lazily.
131         macro_rules! if_regular {
132             ($regular: expr, $other: expr) => {
133                 if let ModuleKind::Regular = kind { $regular } else { $other }
134             };
135         }
136
137         let opt_level_and_size = if_regular!(Some(sess.opts.optimize), None);
138
139         let save_temps = sess.opts.cg.save_temps;
140
141         let should_emit_obj = sess.opts.output_types.contains_key(&OutputType::Exe)
142             || match kind {
143                 ModuleKind::Regular => sess.opts.output_types.contains_key(&OutputType::Object),
144                 ModuleKind::Allocator => false,
145                 ModuleKind::Metadata => sess.opts.output_types.contains_key(&OutputType::Metadata),
146             };
147
148         let emit_obj = if !should_emit_obj {
149             EmitObj::None
150         } else if sess.target.obj_is_bitcode
151             || (sess.opts.cg.linker_plugin_lto.enabled() && !no_builtins)
152         {
153             // This case is selected if the target uses objects as bitcode, or
154             // if linker plugin LTO is enabled. In the linker plugin LTO case
155             // the assumption is that the final link-step will read the bitcode
156             // and convert it to object code. This may be done by either the
157             // native linker or rustc itself.
158             //
159             // Note, however, that the linker-plugin-lto requested here is
160             // explicitly ignored for `#![no_builtins]` crates. These crates are
161             // specifically ignored by rustc's LTO passes and wouldn't work if
162             // loaded into the linker. These crates define symbols that LLVM
163             // lowers intrinsics to, and these symbol dependencies aren't known
164             // until after codegen. As a result any crate marked
165             // `#![no_builtins]` is assumed to not participate in LTO and
166             // instead goes on to generate object code.
167             EmitObj::Bitcode
168         } else if need_bitcode_in_object(sess) {
169             EmitObj::ObjectCode(BitcodeSection::Full)
170         } else {
171             EmitObj::ObjectCode(BitcodeSection::None)
172         };
173
174         ModuleConfig {
175             passes: if_regular!(sess.opts.cg.passes.clone(), vec![]),
176
177             opt_level: opt_level_and_size,
178             opt_size: opt_level_and_size,
179
180             pgo_gen: if_regular!(
181                 sess.opts.cg.profile_generate.clone(),
182                 SwitchWithOptPath::Disabled
183             ),
184             pgo_use: if_regular!(sess.opts.cg.profile_use.clone(), None),
185             pgo_sample_use: if_regular!(sess.opts.unstable_opts.profile_sample_use.clone(), None),
186             debug_info_for_profiling: sess.opts.unstable_opts.debug_info_for_profiling,
187             instrument_coverage: if_regular!(sess.instrument_coverage(), false),
188             instrument_gcov: if_regular!(
189                 // compiler_builtins overrides the codegen-units settings,
190                 // which is incompatible with -Zprofile which requires that
191                 // only a single codegen unit is used per crate.
192                 sess.opts.unstable_opts.profile && !is_compiler_builtins,
193                 false
194             ),
195
196             sanitizer: if_regular!(sess.opts.unstable_opts.sanitizer, SanitizerSet::empty()),
197             sanitizer_recover: if_regular!(
198                 sess.opts.unstable_opts.sanitizer_recover,
199                 SanitizerSet::empty()
200             ),
201             sanitizer_memory_track_origins: if_regular!(
202                 sess.opts.unstable_opts.sanitizer_memory_track_origins,
203                 0
204             ),
205
206             emit_pre_lto_bc: if_regular!(
207                 save_temps || need_pre_lto_bitcode_for_incr_comp(sess),
208                 false
209             ),
210             emit_no_opt_bc: if_regular!(save_temps, false),
211             emit_bc: if_regular!(
212                 save_temps || sess.opts.output_types.contains_key(&OutputType::Bitcode),
213                 save_temps
214             ),
215             emit_ir: if_regular!(
216                 sess.opts.output_types.contains_key(&OutputType::LlvmAssembly),
217                 false
218             ),
219             emit_asm: if_regular!(
220                 sess.opts.output_types.contains_key(&OutputType::Assembly),
221                 false
222             ),
223             emit_obj,
224             emit_thin_lto: sess.opts.unstable_opts.emit_thin_lto,
225             bc_cmdline: sess.target.bitcode_llvm_cmdline.to_string(),
226
227             verify_llvm_ir: sess.verify_llvm_ir(),
228             no_prepopulate_passes: sess.opts.cg.no_prepopulate_passes,
229             no_builtins: no_builtins || sess.target.no_builtins,
230
231             // Exclude metadata and allocator modules from time_passes output,
232             // since they throw off the "LLVM passes" measurement.
233             time_module: if_regular!(true, false),
234
235             // Copy what clang does by turning on loop vectorization at O2 and
236             // slp vectorization at O3.
237             vectorize_loop: !sess.opts.cg.no_vectorize_loops
238                 && (sess.opts.optimize == config::OptLevel::Default
239                     || sess.opts.optimize == config::OptLevel::Aggressive),
240             vectorize_slp: !sess.opts.cg.no_vectorize_slp
241                 && sess.opts.optimize == config::OptLevel::Aggressive,
242
243             // Some targets (namely, NVPTX) interact badly with the
244             // MergeFunctions pass. This is because MergeFunctions can generate
245             // new function calls which may interfere with the target calling
246             // convention; e.g. for the NVPTX target, PTX kernels should not
247             // call other PTX kernels. MergeFunctions can also be configured to
248             // generate aliases instead, but aliases are not supported by some
249             // backends (again, NVPTX). Therefore, allow targets to opt out of
250             // the MergeFunctions pass, but otherwise keep the pass enabled (at
251             // O2 and O3) since it can be useful for reducing code size.
252             merge_functions: match sess
253                 .opts
254                 .unstable_opts
255                 .merge_functions
256                 .unwrap_or(sess.target.merge_functions)
257             {
258                 MergeFunctions::Disabled => false,
259                 MergeFunctions::Trampolines | MergeFunctions::Aliases => {
260                     use config::OptLevel::*;
261                     match sess.opts.optimize {
262                         Aggressive | Default | SizeMin | Size => true,
263                         Less | No => false,
264                     }
265                 }
266             },
267
268             inline_threshold: sess.opts.cg.inline_threshold,
269             emit_lifetime_markers: sess.emit_lifetime_markers(),
270             llvm_plugins: if_regular!(sess.opts.unstable_opts.llvm_plugins.clone(), vec![]),
271         }
272     }
273
274     pub fn bitcode_needed(&self) -> bool {
275         self.emit_bc
276             || self.emit_obj == EmitObj::Bitcode
277             || self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
278     }
279 }
280
281 /// Configuration passed to the function returned by the `target_machine_factory`.
282 pub struct TargetMachineFactoryConfig {
283     /// Split DWARF is enabled in LLVM by checking that `TM.MCOptions.SplitDwarfFile` isn't empty,
284     /// so the path to the dwarf object has to be provided when we create the target machine.
285     /// This can be ignored by backends which do not need it for their Split DWARF support.
286     pub split_dwarf_file: Option<PathBuf>,
287 }
288
289 impl TargetMachineFactoryConfig {
290     pub fn new(
291         cgcx: &CodegenContext<impl WriteBackendMethods>,
292         module_name: &str,
293     ) -> TargetMachineFactoryConfig {
294         let split_dwarf_file = if cgcx.target_can_use_split_dwarf {
295             cgcx.output_filenames.split_dwarf_path(
296                 cgcx.split_debuginfo,
297                 cgcx.split_dwarf_kind,
298                 Some(module_name),
299             )
300         } else {
301             None
302         };
303         TargetMachineFactoryConfig { split_dwarf_file }
304     }
305 }
306
307 pub type TargetMachineFactoryFn<B> = Arc<
308     dyn Fn(TargetMachineFactoryConfig) -> Result<<B as WriteBackendMethods>::TargetMachine, String>
309         + Send
310         + Sync,
311 >;
312
313 pub type ExportedSymbols = FxHashMap<CrateNum, Arc<Vec<(String, SymbolExportInfo)>>>;
314
315 /// Additional resources used by optimize_and_codegen (not module specific)
316 #[derive(Clone)]
317 pub struct CodegenContext<B: WriteBackendMethods> {
318     // Resources needed when running LTO
319     pub backend: B,
320     pub prof: SelfProfilerRef,
321     pub lto: Lto,
322     pub save_temps: bool,
323     pub fewer_names: bool,
324     pub time_trace: bool,
325     pub exported_symbols: Option<Arc<ExportedSymbols>>,
326     pub opts: Arc<config::Options>,
327     pub crate_types: Vec<CrateType>,
328     pub each_linked_rlib_for_lto: Vec<(CrateNum, PathBuf)>,
329     pub output_filenames: Arc<OutputFilenames>,
330     pub regular_module_config: Arc<ModuleConfig>,
331     pub metadata_module_config: Arc<ModuleConfig>,
332     pub allocator_module_config: Arc<ModuleConfig>,
333     pub tm_factory: TargetMachineFactoryFn<B>,
334     pub msvc_imps_needed: bool,
335     pub is_pe_coff: bool,
336     pub target_can_use_split_dwarf: bool,
337     pub target_pointer_width: u32,
338     pub target_arch: String,
339     pub debuginfo: config::DebugInfo,
340     pub split_debuginfo: rustc_target::spec::SplitDebuginfo,
341     pub split_dwarf_kind: rustc_session::config::SplitDwarfKind,
342
343     /// Number of cgus excluding the allocator/metadata modules
344     pub total_cgus: usize,
345     /// Handler to use for diagnostics produced during codegen.
346     pub diag_emitter: SharedEmitter,
347     /// LLVM optimizations for which we want to print remarks.
348     pub remark: Passes,
349     /// Worker thread number
350     pub worker: usize,
351     /// The incremental compilation session directory, or None if we are not
352     /// compiling incrementally
353     pub incr_comp_session_dir: Option<PathBuf>,
354     /// Used to update CGU re-use information during the thinlto phase.
355     pub cgu_reuse_tracker: CguReuseTracker,
356     /// Channel back to the main control thread to send messages to
357     pub coordinator_send: Sender<Box<dyn Any + Send>>,
358 }
359
360 impl<B: WriteBackendMethods> CodegenContext<B> {
361     pub fn create_diag_handler(&self) -> Handler {
362         Handler::with_emitter(true, None, Box::new(self.diag_emitter.clone()))
363     }
364
365     pub fn config(&self, kind: ModuleKind) -> &ModuleConfig {
366         match kind {
367             ModuleKind::Regular => &self.regular_module_config,
368             ModuleKind::Metadata => &self.metadata_module_config,
369             ModuleKind::Allocator => &self.allocator_module_config,
370         }
371     }
372 }
373
374 fn generate_lto_work<B: ExtraBackendMethods>(
375     cgcx: &CodegenContext<B>,
376     needs_fat_lto: Vec<FatLTOInput<B>>,
377     needs_thin_lto: Vec<(String, B::ThinBuffer)>,
378     import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>,
379 ) -> Vec<(WorkItem<B>, u64)> {
380     let _prof_timer = cgcx.prof.generic_activity("codegen_generate_lto_work");
381
382     let (lto_modules, copy_jobs) = if !needs_fat_lto.is_empty() {
383         assert!(needs_thin_lto.is_empty());
384         let lto_module =
385             B::run_fat_lto(cgcx, needs_fat_lto, import_only_modules).unwrap_or_else(|e| e.raise());
386         (vec![lto_module], vec![])
387     } else {
388         assert!(needs_fat_lto.is_empty());
389         B::run_thin_lto(cgcx, needs_thin_lto, import_only_modules).unwrap_or_else(|e| e.raise())
390     };
391
392     lto_modules
393         .into_iter()
394         .map(|module| {
395             let cost = module.cost();
396             (WorkItem::LTO(module), cost)
397         })
398         .chain(copy_jobs.into_iter().map(|wp| {
399             (
400                 WorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
401                     name: wp.cgu_name.clone(),
402                     source: wp,
403                 }),
404                 0,
405             )
406         }))
407         .collect()
408 }
409
410 pub struct CompiledModules {
411     pub modules: Vec<CompiledModule>,
412     pub allocator_module: Option<CompiledModule>,
413 }
414
415 fn need_bitcode_in_object(sess: &Session) -> bool {
416     let requested_for_rlib = sess.opts.cg.embed_bitcode
417         && sess.crate_types().contains(&CrateType::Rlib)
418         && sess.opts.output_types.contains_key(&OutputType::Exe);
419     let forced_by_target = sess.target.forces_embed_bitcode;
420     requested_for_rlib || forced_by_target
421 }
422
423 fn need_pre_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
424     if sess.opts.incremental.is_none() {
425         return false;
426     }
427
428     match sess.lto() {
429         Lto::No => false,
430         Lto::Fat | Lto::Thin | Lto::ThinLocal => true,
431     }
432 }
433
434 pub fn start_async_codegen<B: ExtraBackendMethods>(
435     backend: B,
436     tcx: TyCtxt<'_>,
437     target_cpu: String,
438     metadata: EncodedMetadata,
439     metadata_module: Option<CompiledModule>,
440     total_cgus: usize,
441 ) -> OngoingCodegen<B> {
442     let (coordinator_send, coordinator_receive) = channel();
443     let sess = tcx.sess;
444
445     let crate_attrs = tcx.hir().attrs(rustc_hir::CRATE_HIR_ID);
446     let no_builtins = tcx.sess.contains_name(crate_attrs, sym::no_builtins);
447     let is_compiler_builtins = tcx.sess.contains_name(crate_attrs, sym::compiler_builtins);
448
449     let crate_info = CrateInfo::new(tcx, target_cpu);
450
451     let regular_config =
452         ModuleConfig::new(ModuleKind::Regular, sess, no_builtins, is_compiler_builtins);
453     let metadata_config =
454         ModuleConfig::new(ModuleKind::Metadata, sess, no_builtins, is_compiler_builtins);
455     let allocator_config =
456         ModuleConfig::new(ModuleKind::Allocator, sess, no_builtins, is_compiler_builtins);
457
458     let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
459     let (codegen_worker_send, codegen_worker_receive) = channel();
460
461     let coordinator_thread = start_executing_work(
462         backend.clone(),
463         tcx,
464         &crate_info,
465         shared_emitter,
466         codegen_worker_send,
467         coordinator_receive,
468         total_cgus,
469         sess.jobserver.clone(),
470         Arc::new(regular_config),
471         Arc::new(metadata_config),
472         Arc::new(allocator_config),
473         coordinator_send.clone(),
474     );
475
476     OngoingCodegen {
477         backend,
478         metadata,
479         metadata_module,
480         crate_info,
481
482         codegen_worker_receive,
483         shared_emitter_main,
484         coordinator: Coordinator {
485             sender: coordinator_send,
486             future: Some(coordinator_thread),
487             phantom: PhantomData,
488         },
489         output_filenames: tcx.output_filenames(()).clone(),
490     }
491 }
492
493 fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
494     sess: &Session,
495     compiled_modules: &CompiledModules,
496 ) -> FxHashMap<WorkProductId, WorkProduct> {
497     let mut work_products = FxHashMap::default();
498
499     if sess.opts.incremental.is_none() {
500         return work_products;
501     }
502
503     let _timer = sess.timer("copy_all_cgu_workproducts_to_incr_comp_cache_dir");
504
505     for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
506         let mut files = Vec::new();
507         if let Some(object_file_path) = &module.object {
508             files.push(("o", object_file_path.as_path()));
509         }
510         if let Some(dwarf_object_file_path) = &module.dwarf_object {
511             files.push(("dwo", dwarf_object_file_path.as_path()));
512         }
513
514         if let Some((id, product)) =
515             copy_cgu_workproduct_to_incr_comp_cache_dir(sess, &module.name, files.as_slice())
516         {
517             work_products.insert(id, product);
518         }
519     }
520
521     work_products
522 }
523
524 fn produce_final_output_artifacts(
525     sess: &Session,
526     compiled_modules: &CompiledModules,
527     crate_output: &OutputFilenames,
528 ) {
529     let mut user_wants_bitcode = false;
530     let mut user_wants_objects = false;
531
532     // Produce final compile outputs.
533     let copy_gracefully = |from: &Path, to: &Path| {
534         if let Err(e) = fs::copy(from, to) {
535             sess.emit_err(errors::CopyPath::new(from, to, e));
536         }
537     };
538
539     let copy_if_one_unit = |output_type: OutputType, keep_numbered: bool| {
540         if compiled_modules.modules.len() == 1 {
541             // 1) Only one codegen unit.  In this case it's no difficulty
542             //    to copy `foo.0.x` to `foo.x`.
543             let module_name = Some(&compiled_modules.modules[0].name[..]);
544             let path = crate_output.temp_path(output_type, module_name);
545             copy_gracefully(&path, &crate_output.path(output_type));
546             if !sess.opts.cg.save_temps && !keep_numbered {
547                 // The user just wants `foo.x`, not `foo.#module-name#.x`.
548                 ensure_removed(sess.diagnostic(), &path);
549             }
550         } else {
551             let extension = crate_output
552                 .temp_path(output_type, None)
553                 .extension()
554                 .unwrap()
555                 .to_str()
556                 .unwrap()
557                 .to_owned();
558
559             if crate_output.outputs.contains_key(&output_type) {
560                 // 2) Multiple codegen units, with `--emit foo=some_name`.  We have
561                 //    no good solution for this case, so warn the user.
562                 sess.emit_warning(errors::IgnoringEmitPath { extension });
563             } else if crate_output.single_output_file.is_some() {
564                 // 3) Multiple codegen units, with `-o some_name`.  We have
565                 //    no good solution for this case, so warn the user.
566                 sess.emit_warning(errors::IgnoringOutput { extension });
567             } else {
568                 // 4) Multiple codegen units, but no explicit name.  We
569                 //    just leave the `foo.0.x` files in place.
570                 // (We don't have to do any work in this case.)
571             }
572         }
573     };
574
575     // Flag to indicate whether the user explicitly requested bitcode.
576     // Otherwise, we produced it only as a temporary output, and will need
577     // to get rid of it.
578     for output_type in crate_output.outputs.keys() {
579         match *output_type {
580             OutputType::Bitcode => {
581                 user_wants_bitcode = true;
582                 // Copy to .bc, but always keep the .0.bc.  There is a later
583                 // check to figure out if we should delete .0.bc files, or keep
584                 // them for making an rlib.
585                 copy_if_one_unit(OutputType::Bitcode, true);
586             }
587             OutputType::LlvmAssembly => {
588                 copy_if_one_unit(OutputType::LlvmAssembly, false);
589             }
590             OutputType::Assembly => {
591                 copy_if_one_unit(OutputType::Assembly, false);
592             }
593             OutputType::Object => {
594                 user_wants_objects = true;
595                 copy_if_one_unit(OutputType::Object, true);
596             }
597             OutputType::Mir | OutputType::Metadata | OutputType::Exe | OutputType::DepInfo => {}
598         }
599     }
600
601     // Clean up unwanted temporary files.
602
603     // We create the following files by default:
604     //  - #crate#.#module-name#.bc
605     //  - #crate#.#module-name#.o
606     //  - #crate#.crate.metadata.bc
607     //  - #crate#.crate.metadata.o
608     //  - #crate#.o (linked from crate.##.o)
609     //  - #crate#.bc (copied from crate.##.bc)
610     // We may create additional files if requested by the user (through
611     // `-C save-temps` or `--emit=` flags).
612
613     if !sess.opts.cg.save_temps {
614         // Remove the temporary .#module-name#.o objects.  If the user didn't
615         // explicitly request bitcode (with --emit=bc), and the bitcode is not
616         // needed for building an rlib, then we must remove .#module-name#.bc as
617         // well.
618
619         // Specific rules for keeping .#module-name#.bc:
620         //  - If the user requested bitcode (`user_wants_bitcode`), and
621         //    codegen_units > 1, then keep it.
622         //  - If the user requested bitcode but codegen_units == 1, then we
623         //    can toss .#module-name#.bc because we copied it to .bc earlier.
624         //  - If we're not building an rlib and the user didn't request
625         //    bitcode, then delete .#module-name#.bc.
626         // If you change how this works, also update back::link::link_rlib,
627         // where .#module-name#.bc files are (maybe) deleted after making an
628         // rlib.
629         let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
630
631         let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units() > 1;
632
633         let keep_numbered_objects =
634             needs_crate_object || (user_wants_objects && sess.codegen_units() > 1);
635
636         for module in compiled_modules.modules.iter() {
637             if let Some(ref path) = module.object {
638                 if !keep_numbered_objects {
639                     ensure_removed(sess.diagnostic(), path);
640                 }
641             }
642
643             if let Some(ref path) = module.dwarf_object {
644                 if !keep_numbered_objects {
645                     ensure_removed(sess.diagnostic(), path);
646                 }
647             }
648
649             if let Some(ref path) = module.bytecode {
650                 if !keep_numbered_bitcode {
651                     ensure_removed(sess.diagnostic(), path);
652                 }
653             }
654         }
655
656         if !user_wants_bitcode {
657             if let Some(ref allocator_module) = compiled_modules.allocator_module {
658                 if let Some(ref path) = allocator_module.bytecode {
659                     ensure_removed(sess.diagnostic(), path);
660                 }
661             }
662         }
663     }
664
665     // We leave the following files around by default:
666     //  - #crate#.o
667     //  - #crate#.crate.metadata.o
668     //  - #crate#.bc
669     // These are used in linking steps and will be cleaned up afterward.
670 }
671
672 pub enum WorkItem<B: WriteBackendMethods> {
673     /// Optimize a newly codegened, totally unoptimized module.
674     Optimize(ModuleCodegen<B::Module>),
675     /// Copy the post-LTO artifacts from the incremental cache to the output
676     /// directory.
677     CopyPostLtoArtifacts(CachedModuleCodegen),
678     /// Performs (Thin)LTO on the given module.
679     LTO(lto::LtoModuleCodegen<B>),
680 }
681
682 impl<B: WriteBackendMethods> WorkItem<B> {
683     pub fn module_kind(&self) -> ModuleKind {
684         match *self {
685             WorkItem::Optimize(ref m) => m.kind,
686             WorkItem::CopyPostLtoArtifacts(_) | WorkItem::LTO(_) => ModuleKind::Regular,
687         }
688     }
689
690     fn start_profiling<'a>(&self, cgcx: &'a CodegenContext<B>) -> TimingGuard<'a> {
691         match *self {
692             WorkItem::Optimize(ref m) => {
693                 cgcx.prof.generic_activity_with_arg("codegen_module_optimize", &*m.name)
694             }
695             WorkItem::CopyPostLtoArtifacts(ref m) => cgcx
696                 .prof
697                 .generic_activity_with_arg("codegen_copy_artifacts_from_incr_cache", &*m.name),
698             WorkItem::LTO(ref m) => {
699                 cgcx.prof.generic_activity_with_arg("codegen_module_perform_lto", m.name())
700             }
701         }
702     }
703
704     /// Generate a short description of this work item suitable for use as a thread name.
705     fn short_description(&self) -> String {
706         // `pthread_setname()` on *nix is limited to 15 characters and longer names are ignored.
707         // Use very short descriptions in this case to maximize the space available for the module name.
708         // Windows does not have that limitation so use slightly more descriptive names there.
709         match self {
710             WorkItem::Optimize(m) => {
711                 #[cfg(windows)]
712                 return format!("optimize module {}", m.name);
713                 #[cfg(not(windows))]
714                 return format!("opt {}", m.name);
715             }
716             WorkItem::CopyPostLtoArtifacts(m) => {
717                 #[cfg(windows)]
718                 return format!("copy LTO artifacts for {}", m.name);
719                 #[cfg(not(windows))]
720                 return format!("copy {}", m.name);
721             }
722             WorkItem::LTO(m) => {
723                 #[cfg(windows)]
724                 return format!("LTO module {}", m.name());
725                 #[cfg(not(windows))]
726                 return format!("LTO {}", m.name());
727             }
728         }
729     }
730 }
731
732 enum WorkItemResult<B: WriteBackendMethods> {
733     Compiled(CompiledModule),
734     NeedsLink(ModuleCodegen<B::Module>),
735     NeedsFatLTO(FatLTOInput<B>),
736     NeedsThinLTO(String, B::ThinBuffer),
737 }
738
739 pub enum FatLTOInput<B: WriteBackendMethods> {
740     Serialized { name: String, buffer: B::ModuleBuffer },
741     InMemory(ModuleCodegen<B::Module>),
742 }
743
744 fn execute_work_item<B: ExtraBackendMethods>(
745     cgcx: &CodegenContext<B>,
746     work_item: WorkItem<B>,
747 ) -> Result<WorkItemResult<B>, FatalError> {
748     let module_config = cgcx.config(work_item.module_kind());
749
750     match work_item {
751         WorkItem::Optimize(module) => execute_optimize_work_item(cgcx, module, module_config),
752         WorkItem::CopyPostLtoArtifacts(module) => {
753             Ok(execute_copy_from_cache_work_item(cgcx, module, module_config))
754         }
755         WorkItem::LTO(module) => execute_lto_work_item(cgcx, module, module_config),
756     }
757 }
758
759 /// Actual LTO type we end up choosing based on multiple factors.
760 pub enum ComputedLtoType {
761     No,
762     Thin,
763     Fat,
764 }
765
766 pub fn compute_per_cgu_lto_type(
767     sess_lto: &Lto,
768     opts: &config::Options,
769     sess_crate_types: &[CrateType],
770     module_kind: ModuleKind,
771 ) -> ComputedLtoType {
772     // Metadata modules never participate in LTO regardless of the lto
773     // settings.
774     if module_kind == ModuleKind::Metadata {
775         return ComputedLtoType::No;
776     }
777
778     // If the linker does LTO, we don't have to do it. Note that we
779     // keep doing full LTO, if it is requested, as not to break the
780     // assumption that the output will be a single module.
781     let linker_does_lto = opts.cg.linker_plugin_lto.enabled();
782
783     // When we're automatically doing ThinLTO for multi-codegen-unit
784     // builds we don't actually want to LTO the allocator modules if
785     // it shows up. This is due to various linker shenanigans that
786     // we'll encounter later.
787     let is_allocator = module_kind == ModuleKind::Allocator;
788
789     // We ignore a request for full crate graph LTO if the crate type
790     // is only an rlib, as there is no full crate graph to process,
791     // that'll happen later.
792     //
793     // This use case currently comes up primarily for targets that
794     // require LTO so the request for LTO is always unconditionally
795     // passed down to the backend, but we don't actually want to do
796     // anything about it yet until we've got a final product.
797     let is_rlib = sess_crate_types.len() == 1 && sess_crate_types[0] == CrateType::Rlib;
798
799     match sess_lto {
800         Lto::ThinLocal if !linker_does_lto && !is_allocator => ComputedLtoType::Thin,
801         Lto::Thin if !linker_does_lto && !is_rlib => ComputedLtoType::Thin,
802         Lto::Fat if !is_rlib => ComputedLtoType::Fat,
803         _ => ComputedLtoType::No,
804     }
805 }
806
807 fn execute_optimize_work_item<B: ExtraBackendMethods>(
808     cgcx: &CodegenContext<B>,
809     module: ModuleCodegen<B::Module>,
810     module_config: &ModuleConfig,
811 ) -> Result<WorkItemResult<B>, FatalError> {
812     let diag_handler = cgcx.create_diag_handler();
813
814     unsafe {
815         B::optimize(cgcx, &diag_handler, &module, module_config)?;
816     }
817
818     // After we've done the initial round of optimizations we need to
819     // decide whether to synchronously codegen this module or ship it
820     // back to the coordinator thread for further LTO processing (which
821     // has to wait for all the initial modules to be optimized).
822
823     let lto_type = compute_per_cgu_lto_type(&cgcx.lto, &cgcx.opts, &cgcx.crate_types, module.kind);
824
825     // If we're doing some form of incremental LTO then we need to be sure to
826     // save our module to disk first.
827     let bitcode = if cgcx.config(module.kind).emit_pre_lto_bc {
828         let filename = pre_lto_bitcode_filename(&module.name);
829         cgcx.incr_comp_session_dir.as_ref().map(|path| path.join(&filename))
830     } else {
831         None
832     };
833
834     match lto_type {
835         ComputedLtoType::No => finish_intra_module_work(cgcx, module, module_config),
836         ComputedLtoType::Thin => {
837             let (name, thin_buffer) = B::prepare_thin(module);
838             if let Some(path) = bitcode {
839                 fs::write(&path, thin_buffer.data()).unwrap_or_else(|e| {
840                     panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
841                 });
842             }
843             Ok(WorkItemResult::NeedsThinLTO(name, thin_buffer))
844         }
845         ComputedLtoType::Fat => match bitcode {
846             Some(path) => {
847                 let (name, buffer) = B::serialize_module(module);
848                 fs::write(&path, buffer.data()).unwrap_or_else(|e| {
849                     panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
850                 });
851                 Ok(WorkItemResult::NeedsFatLTO(FatLTOInput::Serialized { name, buffer }))
852             }
853             None => Ok(WorkItemResult::NeedsFatLTO(FatLTOInput::InMemory(module))),
854         },
855     }
856 }
857
858 fn execute_copy_from_cache_work_item<B: ExtraBackendMethods>(
859     cgcx: &CodegenContext<B>,
860     module: CachedModuleCodegen,
861     module_config: &ModuleConfig,
862 ) -> WorkItemResult<B> {
863     assert!(module_config.emit_obj != EmitObj::None);
864
865     let incr_comp_session_dir = cgcx.incr_comp_session_dir.as_ref().unwrap();
866
867     let load_from_incr_comp_dir = |output_path: PathBuf, saved_path: &str| {
868         let source_file = in_incr_comp_dir(&incr_comp_session_dir, saved_path);
869         debug!(
870             "copying pre-existing module `{}` from {:?} to {}",
871             module.name,
872             source_file,
873             output_path.display()
874         );
875         match link_or_copy(&source_file, &output_path) {
876             Ok(_) => Some(output_path),
877             Err(error) => {
878                 cgcx.create_diag_handler().emit_err(errors::CopyPathBuf {
879                     source_file,
880                     output_path,
881                     error,
882                 });
883                 None
884             }
885         }
886     };
887
888     let object = load_from_incr_comp_dir(
889         cgcx.output_filenames.temp_path(OutputType::Object, Some(&module.name)),
890         &module.source.saved_files.get("o").expect("no saved object file in work product"),
891     );
892     let dwarf_object =
893         module.source.saved_files.get("dwo").as_ref().and_then(|saved_dwarf_object_file| {
894             let dwarf_obj_out = cgcx
895                 .output_filenames
896                 .split_dwarf_path(cgcx.split_debuginfo, cgcx.split_dwarf_kind, Some(&module.name))
897                 .expect(
898                     "saved dwarf object in work product but `split_dwarf_path` returned `None`",
899                 );
900             load_from_incr_comp_dir(dwarf_obj_out, &saved_dwarf_object_file)
901         });
902
903     WorkItemResult::Compiled(CompiledModule {
904         name: module.name,
905         kind: ModuleKind::Regular,
906         object,
907         dwarf_object,
908         bytecode: None,
909     })
910 }
911
912 fn execute_lto_work_item<B: ExtraBackendMethods>(
913     cgcx: &CodegenContext<B>,
914     module: lto::LtoModuleCodegen<B>,
915     module_config: &ModuleConfig,
916 ) -> Result<WorkItemResult<B>, FatalError> {
917     let module = unsafe { module.optimize(cgcx)? };
918     finish_intra_module_work(cgcx, module, module_config)
919 }
920
921 fn finish_intra_module_work<B: ExtraBackendMethods>(
922     cgcx: &CodegenContext<B>,
923     module: ModuleCodegen<B::Module>,
924     module_config: &ModuleConfig,
925 ) -> Result<WorkItemResult<B>, FatalError> {
926     let diag_handler = cgcx.create_diag_handler();
927
928     if !cgcx.opts.unstable_opts.combine_cgu
929         || module.kind == ModuleKind::Metadata
930         || module.kind == ModuleKind::Allocator
931     {
932         let module = unsafe { B::codegen(cgcx, &diag_handler, module, module_config)? };
933         Ok(WorkItemResult::Compiled(module))
934     } else {
935         Ok(WorkItemResult::NeedsLink(module))
936     }
937 }
938
939 pub enum Message<B: WriteBackendMethods> {
940     Token(io::Result<Acquired>),
941     NeedsFatLTO {
942         result: FatLTOInput<B>,
943         worker_id: usize,
944     },
945     NeedsThinLTO {
946         name: String,
947         thin_buffer: B::ThinBuffer,
948         worker_id: usize,
949     },
950     NeedsLink {
951         module: ModuleCodegen<B::Module>,
952         worker_id: usize,
953     },
954     Done {
955         result: Result<CompiledModule, Option<WorkerFatalError>>,
956         worker_id: usize,
957     },
958     CodegenDone {
959         llvm_work_item: WorkItem<B>,
960         cost: u64,
961     },
962     AddImportOnlyModule {
963         module_data: SerializedModule<B::ModuleBuffer>,
964         work_product: WorkProduct,
965     },
966     CodegenComplete,
967     CodegenItem,
968     CodegenAborted,
969 }
970
971 type DiagnosticArgName<'source> = Cow<'source, str>;
972
973 struct Diagnostic {
974     msg: Vec<(DiagnosticMessage, Style)>,
975     args: FxHashMap<DiagnosticArgName<'static>, rustc_errors::DiagnosticArgValue<'static>>,
976     code: Option<DiagnosticId>,
977     lvl: Level,
978 }
979
980 #[derive(PartialEq, Clone, Copy, Debug)]
981 enum MainThreadWorkerState {
982     Idle,
983     Codegenning,
984     LLVMing,
985 }
986
987 fn start_executing_work<B: ExtraBackendMethods>(
988     backend: B,
989     tcx: TyCtxt<'_>,
990     crate_info: &CrateInfo,
991     shared_emitter: SharedEmitter,
992     codegen_worker_send: Sender<Message<B>>,
993     coordinator_receive: Receiver<Box<dyn Any + Send>>,
994     total_cgus: usize,
995     jobserver: Client,
996     regular_config: Arc<ModuleConfig>,
997     metadata_config: Arc<ModuleConfig>,
998     allocator_config: Arc<ModuleConfig>,
999     tx_to_llvm_workers: Sender<Box<dyn Any + Send>>,
1000 ) -> thread::JoinHandle<Result<CompiledModules, ()>> {
1001     let coordinator_send = tx_to_llvm_workers;
1002     let sess = tcx.sess;
1003
1004     let mut each_linked_rlib_for_lto = Vec::new();
1005     drop(link::each_linked_rlib(crate_info, None, &mut |cnum, path| {
1006         if link::ignored_for_lto(sess, crate_info, cnum) {
1007             return;
1008         }
1009         each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
1010     }));
1011
1012     // Compute the set of symbols we need to retain when doing LTO (if we need to)
1013     let exported_symbols = {
1014         let mut exported_symbols = FxHashMap::default();
1015
1016         let copy_symbols = |cnum| {
1017             let symbols = tcx
1018                 .exported_symbols(cnum)
1019                 .iter()
1020                 .map(|&(s, lvl)| (symbol_name_for_instance_in_crate(tcx, s, cnum), lvl))
1021                 .collect();
1022             Arc::new(symbols)
1023         };
1024
1025         match sess.lto() {
1026             Lto::No => None,
1027             Lto::ThinLocal => {
1028                 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1029                 Some(Arc::new(exported_symbols))
1030             }
1031             Lto::Fat | Lto::Thin => {
1032                 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1033                 for &(cnum, ref _path) in &each_linked_rlib_for_lto {
1034                     exported_symbols.insert(cnum, copy_symbols(cnum));
1035                 }
1036                 Some(Arc::new(exported_symbols))
1037             }
1038         }
1039     };
1040
1041     // First up, convert our jobserver into a helper thread so we can use normal
1042     // mpsc channels to manage our messages and such.
1043     // After we've requested tokens then we'll, when we can,
1044     // get tokens on `coordinator_receive` which will
1045     // get managed in the main loop below.
1046     let coordinator_send2 = coordinator_send.clone();
1047     let helper = jobserver
1048         .into_helper_thread(move |token| {
1049             drop(coordinator_send2.send(Box::new(Message::Token::<B>(token))));
1050         })
1051         .expect("failed to spawn helper thread");
1052
1053     let ol =
1054         if tcx.sess.opts.unstable_opts.no_codegen || !tcx.sess.opts.output_types.should_codegen() {
1055             // If we know that we won’t be doing codegen, create target machines without optimisation.
1056             config::OptLevel::No
1057         } else {
1058             tcx.backend_optimization_level(())
1059         };
1060     let backend_features = tcx.global_backend_features(());
1061     let cgcx = CodegenContext::<B> {
1062         backend: backend.clone(),
1063         crate_types: sess.crate_types().to_vec(),
1064         each_linked_rlib_for_lto,
1065         lto: sess.lto(),
1066         fewer_names: sess.fewer_names(),
1067         save_temps: sess.opts.cg.save_temps,
1068         time_trace: sess.opts.unstable_opts.llvm_time_trace,
1069         opts: Arc::new(sess.opts.clone()),
1070         prof: sess.prof.clone(),
1071         exported_symbols,
1072         remark: sess.opts.cg.remark.clone(),
1073         worker: 0,
1074         incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1075         cgu_reuse_tracker: sess.cgu_reuse_tracker.clone(),
1076         coordinator_send,
1077         diag_emitter: shared_emitter.clone(),
1078         output_filenames: tcx.output_filenames(()).clone(),
1079         regular_module_config: regular_config,
1080         metadata_module_config: metadata_config,
1081         allocator_module_config: allocator_config,
1082         tm_factory: backend.target_machine_factory(tcx.sess, ol, backend_features),
1083         total_cgus,
1084         msvc_imps_needed: msvc_imps_needed(tcx),
1085         is_pe_coff: tcx.sess.target.is_like_windows,
1086         target_can_use_split_dwarf: tcx.sess.target_can_use_split_dwarf(),
1087         target_pointer_width: tcx.sess.target.pointer_width,
1088         target_arch: tcx.sess.target.arch.to_string(),
1089         debuginfo: tcx.sess.opts.debuginfo,
1090         split_debuginfo: tcx.sess.split_debuginfo(),
1091         split_dwarf_kind: tcx.sess.opts.unstable_opts.split_dwarf_kind,
1092     };
1093
1094     // This is the "main loop" of parallel work happening for parallel codegen.
1095     // It's here that we manage parallelism, schedule work, and work with
1096     // messages coming from clients.
1097     //
1098     // There are a few environmental pre-conditions that shape how the system
1099     // is set up:
1100     //
1101     // - Error reporting can only happen on the main thread because that's the
1102     //   only place where we have access to the compiler `Session`.
1103     // - LLVM work can be done on any thread.
1104     // - Codegen can only happen on the main thread.
1105     // - Each thread doing substantial work must be in possession of a `Token`
1106     //   from the `Jobserver`.
1107     // - The compiler process always holds one `Token`. Any additional `Tokens`
1108     //   have to be requested from the `Jobserver`.
1109     //
1110     // Error Reporting
1111     // ===============
1112     // The error reporting restriction is handled separately from the rest: We
1113     // set up a `SharedEmitter` that holds an open channel to the main thread.
1114     // When an error occurs on any thread, the shared emitter will send the
1115     // error message to the receiver main thread (`SharedEmitterMain`). The
1116     // main thread will periodically query this error message queue and emit
1117     // any error messages it has received. It might even abort compilation if
1118     // it has received a fatal error. In this case we rely on all other threads
1119     // being torn down automatically with the main thread.
1120     // Since the main thread will often be busy doing codegen work, error
1121     // reporting will be somewhat delayed, since the message queue can only be
1122     // checked in between two work packages.
1123     //
1124     // Work Processing Infrastructure
1125     // ==============================
1126     // The work processing infrastructure knows three major actors:
1127     //
1128     // - the coordinator thread,
1129     // - the main thread, and
1130     // - LLVM worker threads
1131     //
1132     // The coordinator thread is running a message loop. It instructs the main
1133     // thread about what work to do when, and it will spawn off LLVM worker
1134     // threads as open LLVM WorkItems become available.
1135     //
1136     // The job of the main thread is to codegen CGUs into LLVM work packages
1137     // (since the main thread is the only thread that can do this). The main
1138     // thread will block until it receives a message from the coordinator, upon
1139     // which it will codegen one CGU, send it to the coordinator and block
1140     // again. This way the coordinator can control what the main thread is
1141     // doing.
1142     //
1143     // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1144     // available, it will spawn off a new LLVM worker thread and let it process
1145     // a WorkItem. When a LLVM worker thread is done with its WorkItem,
1146     // it will just shut down, which also frees all resources associated with
1147     // the given LLVM module, and sends a message to the coordinator that the
1148     // WorkItem has been completed.
1149     //
1150     // Work Scheduling
1151     // ===============
1152     // The scheduler's goal is to minimize the time it takes to complete all
1153     // work there is, however, we also want to keep memory consumption low
1154     // if possible. These two goals are at odds with each other: If memory
1155     // consumption were not an issue, we could just let the main thread produce
1156     // LLVM WorkItems at full speed, assuring maximal utilization of
1157     // Tokens/LLVM worker threads. However, since codegen is usually faster
1158     // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1159     // WorkItem potentially holds on to a substantial amount of memory.
1160     //
1161     // So the actual goal is to always produce just enough LLVM WorkItems as
1162     // not to starve our LLVM worker threads. That means, once we have enough
1163     // WorkItems in our queue, we can block the main thread, so it does not
1164     // produce more until we need them.
1165     //
1166     // Doing LLVM Work on the Main Thread
1167     // ----------------------------------
1168     // Since the main thread owns the compiler process's implicit `Token`, it is
1169     // wasteful to keep it blocked without doing any work. Therefore, what we do
1170     // in this case is: We spawn off an additional LLVM worker thread that helps
1171     // reduce the queue. The work it is doing corresponds to the implicit
1172     // `Token`. The coordinator will mark the main thread as being busy with
1173     // LLVM work. (The actual work happens on another OS thread but we just care
1174     // about `Tokens`, not actual threads).
1175     //
1176     // When any LLVM worker thread finishes while the main thread is marked as
1177     // "busy with LLVM work", we can do a little switcheroo: We give the Token
1178     // of the just finished thread to the LLVM worker thread that is working on
1179     // behalf of the main thread's implicit Token, thus freeing up the main
1180     // thread again. The coordinator can then again decide what the main thread
1181     // should do. This allows the coordinator to make decisions at more points
1182     // in time.
1183     //
1184     // Striking a Balance between Throughput and Memory Consumption
1185     // ------------------------------------------------------------
1186     // Since our two goals, (1) use as many Tokens as possible and (2) keep
1187     // memory consumption as low as possible, are in conflict with each other,
1188     // we have to find a trade off between them. Right now, the goal is to keep
1189     // all workers busy, which means that no worker should find the queue empty
1190     // when it is ready to start.
1191     // How do we do achieve this? Good question :) We actually never know how
1192     // many `Tokens` are potentially available so it's hard to say how much to
1193     // fill up the queue before switching the main thread to LLVM work. Also we
1194     // currently don't have a means to estimate how long a running LLVM worker
1195     // will still be busy with it's current WorkItem. However, we know the
1196     // maximal count of available Tokens that makes sense (=the number of CPU
1197     // cores), so we can take a conservative guess. The heuristic we use here
1198     // is implemented in the `queue_full_enough()` function.
1199     //
1200     // Some Background on Jobservers
1201     // -----------------------------
1202     // It's worth also touching on the management of parallelism here. We don't
1203     // want to just spawn a thread per work item because while that's optimal
1204     // parallelism it may overload a system with too many threads or violate our
1205     // configuration for the maximum amount of cpu to use for this process. To
1206     // manage this we use the `jobserver` crate.
1207     //
1208     // Job servers are an artifact of GNU make and are used to manage
1209     // parallelism between processes. A jobserver is a glorified IPC semaphore
1210     // basically. Whenever we want to run some work we acquire the semaphore,
1211     // and whenever we're done with that work we release the semaphore. In this
1212     // manner we can ensure that the maximum number of parallel workers is
1213     // capped at any one point in time.
1214     //
1215     // LTO and the coordinator thread
1216     // ------------------------------
1217     //
1218     // The final job the coordinator thread is responsible for is managing LTO
1219     // and how that works. When LTO is requested what we'll do is collect all
1220     // optimized LLVM modules into a local vector on the coordinator. Once all
1221     // modules have been codegened and optimized we hand this to the `lto`
1222     // module for further optimization. The `lto` module will return back a list
1223     // of more modules to work on, which the coordinator will continue to spawn
1224     // work for.
1225     //
1226     // Each LLVM module is automatically sent back to the coordinator for LTO if
1227     // necessary. There's already optimizations in place to avoid sending work
1228     // back to the coordinator if LTO isn't requested.
1229     return B::spawn_thread(cgcx.time_trace, move || {
1230         let mut worker_id_counter = 0;
1231         let mut free_worker_ids = Vec::new();
1232         let mut get_worker_id = |free_worker_ids: &mut Vec<usize>| {
1233             if let Some(id) = free_worker_ids.pop() {
1234                 id
1235             } else {
1236                 let id = worker_id_counter;
1237                 worker_id_counter += 1;
1238                 id
1239             }
1240         };
1241
1242         // This is where we collect codegen units that have gone all the way
1243         // through codegen and LLVM.
1244         let mut compiled_modules = vec![];
1245         let mut compiled_allocator_module = None;
1246         let mut needs_link = Vec::new();
1247         let mut needs_fat_lto = Vec::new();
1248         let mut needs_thin_lto = Vec::new();
1249         let mut lto_import_only_modules = Vec::new();
1250         let mut started_lto = false;
1251         let mut codegen_aborted = false;
1252
1253         // This flag tracks whether all items have gone through codegens
1254         let mut codegen_done = false;
1255
1256         // This is the queue of LLVM work items that still need processing.
1257         let mut work_items = Vec::<(WorkItem<B>, u64)>::new();
1258
1259         // This are the Jobserver Tokens we currently hold. Does not include
1260         // the implicit Token the compiler process owns no matter what.
1261         let mut tokens = Vec::new();
1262
1263         let mut main_thread_worker_state = MainThreadWorkerState::Idle;
1264         let mut running = 0;
1265
1266         let prof = &cgcx.prof;
1267         let mut llvm_start_time: Option<VerboseTimingGuard<'_>> = None;
1268
1269         // Run the message loop while there's still anything that needs message
1270         // processing. Note that as soon as codegen is aborted we simply want to
1271         // wait for all existing work to finish, so many of the conditions here
1272         // only apply if codegen hasn't been aborted as they represent pending
1273         // work to be done.
1274         while !codegen_done
1275             || running > 0
1276             || main_thread_worker_state == MainThreadWorkerState::LLVMing
1277             || (!codegen_aborted
1278                 && !(work_items.is_empty()
1279                     && needs_fat_lto.is_empty()
1280                     && needs_thin_lto.is_empty()
1281                     && lto_import_only_modules.is_empty()
1282                     && main_thread_worker_state == MainThreadWorkerState::Idle))
1283         {
1284             // While there are still CGUs to be codegened, the coordinator has
1285             // to decide how to utilize the compiler processes implicit Token:
1286             // For codegenning more CGU or for running them through LLVM.
1287             if !codegen_done {
1288                 if main_thread_worker_state == MainThreadWorkerState::Idle {
1289                     // Compute the number of workers that will be running once we've taken as many
1290                     // items from the work queue as we can, plus one for the main thread. It's not
1291                     // critically important that we use this instead of just `running`, but it
1292                     // prevents the `queue_full_enough` heuristic from fluctuating just because a
1293                     // worker finished up and we decreased the `running` count, even though we're
1294                     // just going to increase it right after this when we put a new worker to work.
1295                     let extra_tokens = tokens.len().checked_sub(running).unwrap();
1296                     let additional_running = std::cmp::min(extra_tokens, work_items.len());
1297                     let anticipated_running = running + additional_running + 1;
1298
1299                     if !queue_full_enough(work_items.len(), anticipated_running) {
1300                         // The queue is not full enough, codegen more items:
1301                         if codegen_worker_send.send(Message::CodegenItem).is_err() {
1302                             panic!("Could not send Message::CodegenItem to main thread")
1303                         }
1304                         main_thread_worker_state = MainThreadWorkerState::Codegenning;
1305                     } else {
1306                         // The queue is full enough to not let the worker
1307                         // threads starve. Use the implicit Token to do some
1308                         // LLVM work too.
1309                         let (item, _) =
1310                             work_items.pop().expect("queue empty - queue_full_enough() broken?");
1311                         let cgcx = CodegenContext {
1312                             worker: get_worker_id(&mut free_worker_ids),
1313                             ..cgcx.clone()
1314                         };
1315                         maybe_start_llvm_timer(
1316                             prof,
1317                             cgcx.config(item.module_kind()),
1318                             &mut llvm_start_time,
1319                         );
1320                         main_thread_worker_state = MainThreadWorkerState::LLVMing;
1321                         spawn_work(cgcx, item);
1322                     }
1323                 }
1324             } else if codegen_aborted {
1325                 // don't queue up any more work if codegen was aborted, we're
1326                 // just waiting for our existing children to finish
1327             } else {
1328                 // If we've finished everything related to normal codegen
1329                 // then it must be the case that we've got some LTO work to do.
1330                 // Perform the serial work here of figuring out what we're
1331                 // going to LTO and then push a bunch of work items onto our
1332                 // queue to do LTO
1333                 if work_items.is_empty()
1334                     && running == 0
1335                     && main_thread_worker_state == MainThreadWorkerState::Idle
1336                 {
1337                     assert!(!started_lto);
1338                     started_lto = true;
1339
1340                     let needs_fat_lto = mem::take(&mut needs_fat_lto);
1341                     let needs_thin_lto = mem::take(&mut needs_thin_lto);
1342                     let import_only_modules = mem::take(&mut lto_import_only_modules);
1343
1344                     for (work, cost) in
1345                         generate_lto_work(&cgcx, needs_fat_lto, needs_thin_lto, import_only_modules)
1346                     {
1347                         let insertion_index = work_items
1348                             .binary_search_by_key(&cost, |&(_, cost)| cost)
1349                             .unwrap_or_else(|e| e);
1350                         work_items.insert(insertion_index, (work, cost));
1351                         if !cgcx.opts.unstable_opts.no_parallel_llvm {
1352                             helper.request_token();
1353                         }
1354                     }
1355                 }
1356
1357                 // In this branch, we know that everything has been codegened,
1358                 // so it's just a matter of determining whether the implicit
1359                 // Token is free to use for LLVM work.
1360                 match main_thread_worker_state {
1361                     MainThreadWorkerState::Idle => {
1362                         if let Some((item, _)) = work_items.pop() {
1363                             let cgcx = CodegenContext {
1364                                 worker: get_worker_id(&mut free_worker_ids),
1365                                 ..cgcx.clone()
1366                             };
1367                             maybe_start_llvm_timer(
1368                                 prof,
1369                                 cgcx.config(item.module_kind()),
1370                                 &mut llvm_start_time,
1371                             );
1372                             main_thread_worker_state = MainThreadWorkerState::LLVMing;
1373                             spawn_work(cgcx, item);
1374                         } else {
1375                             // There is no unstarted work, so let the main thread
1376                             // take over for a running worker. Otherwise the
1377                             // implicit token would just go to waste.
1378                             // We reduce the `running` counter by one. The
1379                             // `tokens.truncate()` below will take care of
1380                             // giving the Token back.
1381                             debug_assert!(running > 0);
1382                             running -= 1;
1383                             main_thread_worker_state = MainThreadWorkerState::LLVMing;
1384                         }
1385                     }
1386                     MainThreadWorkerState::Codegenning => bug!(
1387                         "codegen worker should not be codegenning after \
1388                               codegen was already completed"
1389                     ),
1390                     MainThreadWorkerState::LLVMing => {
1391                         // Already making good use of that token
1392                     }
1393                 }
1394             }
1395
1396             // Spin up what work we can, only doing this while we've got available
1397             // parallelism slots and work left to spawn.
1398             while !codegen_aborted && !work_items.is_empty() && running < tokens.len() {
1399                 let (item, _) = work_items.pop().unwrap();
1400
1401                 maybe_start_llvm_timer(prof, cgcx.config(item.module_kind()), &mut llvm_start_time);
1402
1403                 let cgcx =
1404                     CodegenContext { worker: get_worker_id(&mut free_worker_ids), ..cgcx.clone() };
1405
1406                 spawn_work(cgcx, item);
1407                 running += 1;
1408             }
1409
1410             // Relinquish accidentally acquired extra tokens
1411             tokens.truncate(running);
1412
1413             // If a thread exits successfully then we drop a token associated
1414             // with that worker and update our `running` count. We may later
1415             // re-acquire a token to continue running more work. We may also not
1416             // actually drop a token here if the worker was running with an
1417             // "ephemeral token"
1418             let mut free_worker = |worker_id| {
1419                 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1420                     main_thread_worker_state = MainThreadWorkerState::Idle;
1421                 } else {
1422                     running -= 1;
1423                 }
1424
1425                 free_worker_ids.push(worker_id);
1426             };
1427
1428             let msg = coordinator_receive.recv().unwrap();
1429             match *msg.downcast::<Message<B>>().ok().unwrap() {
1430                 // Save the token locally and the next turn of the loop will use
1431                 // this to spawn a new unit of work, or it may get dropped
1432                 // immediately if we have no more work to spawn.
1433                 Message::Token(token) => {
1434                     match token {
1435                         Ok(token) => {
1436                             tokens.push(token);
1437
1438                             if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1439                                 // If the main thread token is used for LLVM work
1440                                 // at the moment, we turn that thread into a regular
1441                                 // LLVM worker thread, so the main thread is free
1442                                 // to react to codegen demand.
1443                                 main_thread_worker_state = MainThreadWorkerState::Idle;
1444                                 running += 1;
1445                             }
1446                         }
1447                         Err(e) => {
1448                             let msg = &format!("failed to acquire jobserver token: {}", e);
1449                             shared_emitter.fatal(msg);
1450                             // Exit the coordinator thread
1451                             panic!("{}", msg)
1452                         }
1453                     }
1454                 }
1455
1456                 Message::CodegenDone { llvm_work_item, cost } => {
1457                     // We keep the queue sorted by estimated processing cost,
1458                     // so that more expensive items are processed earlier. This
1459                     // is good for throughput as it gives the main thread more
1460                     // time to fill up the queue and it avoids scheduling
1461                     // expensive items to the end.
1462                     // Note, however, that this is not ideal for memory
1463                     // consumption, as LLVM module sizes are not evenly
1464                     // distributed.
1465                     let insertion_index = work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1466                     let insertion_index = match insertion_index {
1467                         Ok(idx) | Err(idx) => idx,
1468                     };
1469                     work_items.insert(insertion_index, (llvm_work_item, cost));
1470
1471                     if !cgcx.opts.unstable_opts.no_parallel_llvm {
1472                         helper.request_token();
1473                     }
1474                     assert_eq!(main_thread_worker_state, MainThreadWorkerState::Codegenning);
1475                     main_thread_worker_state = MainThreadWorkerState::Idle;
1476                 }
1477
1478                 Message::CodegenComplete => {
1479                     codegen_done = true;
1480                     assert_eq!(main_thread_worker_state, MainThreadWorkerState::Codegenning);
1481                     main_thread_worker_state = MainThreadWorkerState::Idle;
1482                 }
1483
1484                 // If codegen is aborted that means translation was aborted due
1485                 // to some normal-ish compiler error. In this situation we want
1486                 // to exit as soon as possible, but we want to make sure all
1487                 // existing work has finished. Flag codegen as being done, and
1488                 // then conditions above will ensure no more work is spawned but
1489                 // we'll keep executing this loop until `running` hits 0.
1490                 Message::CodegenAborted => {
1491                     codegen_done = true;
1492                     codegen_aborted = true;
1493                 }
1494                 Message::Done { result: Ok(compiled_module), worker_id } => {
1495                     free_worker(worker_id);
1496                     match compiled_module.kind {
1497                         ModuleKind::Regular => {
1498                             compiled_modules.push(compiled_module);
1499                         }
1500                         ModuleKind::Allocator => {
1501                             assert!(compiled_allocator_module.is_none());
1502                             compiled_allocator_module = Some(compiled_module);
1503                         }
1504                         ModuleKind::Metadata => bug!("Should be handled separately"),
1505                     }
1506                 }
1507                 Message::NeedsLink { module, worker_id } => {
1508                     free_worker(worker_id);
1509                     needs_link.push(module);
1510                 }
1511                 Message::NeedsFatLTO { result, worker_id } => {
1512                     assert!(!started_lto);
1513                     free_worker(worker_id);
1514                     needs_fat_lto.push(result);
1515                 }
1516                 Message::NeedsThinLTO { name, thin_buffer, worker_id } => {
1517                     assert!(!started_lto);
1518                     free_worker(worker_id);
1519                     needs_thin_lto.push((name, thin_buffer));
1520                 }
1521                 Message::AddImportOnlyModule { module_data, work_product } => {
1522                     assert!(!started_lto);
1523                     assert!(!codegen_done);
1524                     assert_eq!(main_thread_worker_state, MainThreadWorkerState::Codegenning);
1525                     lto_import_only_modules.push((module_data, work_product));
1526                     main_thread_worker_state = MainThreadWorkerState::Idle;
1527                 }
1528                 // If the thread failed that means it panicked, so we abort immediately.
1529                 Message::Done { result: Err(None), worker_id: _ } => {
1530                     bug!("worker thread panicked");
1531                 }
1532                 Message::Done { result: Err(Some(WorkerFatalError)), worker_id } => {
1533                     // Similar to CodegenAborted, wait for remaining work to finish.
1534                     free_worker(worker_id);
1535                     codegen_done = true;
1536                     codegen_aborted = true;
1537                 }
1538                 Message::CodegenItem => bug!("the coordinator should not receive codegen requests"),
1539             }
1540         }
1541
1542         if codegen_aborted {
1543             return Err(());
1544         }
1545
1546         let needs_link = mem::take(&mut needs_link);
1547         if !needs_link.is_empty() {
1548             assert!(compiled_modules.is_empty());
1549             let diag_handler = cgcx.create_diag_handler();
1550             let module = B::run_link(&cgcx, &diag_handler, needs_link).map_err(|_| ())?;
1551             let module = unsafe {
1552                 B::codegen(&cgcx, &diag_handler, module, cgcx.config(ModuleKind::Regular))
1553                     .map_err(|_| ())?
1554             };
1555             compiled_modules.push(module);
1556         }
1557
1558         // Drop to print timings
1559         drop(llvm_start_time);
1560
1561         // Regardless of what order these modules completed in, report them to
1562         // the backend in the same order every time to ensure that we're handing
1563         // out deterministic results.
1564         compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
1565
1566         Ok(CompiledModules {
1567             modules: compiled_modules,
1568             allocator_module: compiled_allocator_module,
1569         })
1570     });
1571
1572     // A heuristic that determines if we have enough LLVM WorkItems in the
1573     // queue so that the main thread can do LLVM work instead of codegen
1574     fn queue_full_enough(items_in_queue: usize, workers_running: usize) -> bool {
1575         // This heuristic scales ahead-of-time codegen according to available
1576         // concurrency, as measured by `workers_running`. The idea is that the
1577         // more concurrency we have available, the more demand there will be for
1578         // work items, and the fuller the queue should be kept to meet demand.
1579         // An important property of this approach is that we codegen ahead of
1580         // time only as much as necessary, so as to keep fewer LLVM modules in
1581         // memory at once, thereby reducing memory consumption.
1582         //
1583         // When the number of workers running is less than the max concurrency
1584         // available to us, this heuristic can cause us to instruct the main
1585         // thread to work on an LLVM item (that is, tell it to "LLVM") instead
1586         // of codegen, even though it seems like it *should* be codegenning so
1587         // that we can create more work items and spawn more LLVM workers.
1588         //
1589         // But this is not a problem. When the main thread is told to LLVM,
1590         // according to this heuristic and how work is scheduled, there is
1591         // always at least one item in the queue, and therefore at least one
1592         // pending jobserver token request. If there *is* more concurrency
1593         // available, we will immediately receive a token, which will upgrade
1594         // the main thread's LLVM worker to a real one (conceptually), and free
1595         // up the main thread to codegen if necessary. On the other hand, if
1596         // there isn't more concurrency, then the main thread working on an LLVM
1597         // item is appropriate, as long as the queue is full enough for demand.
1598         //
1599         // Speaking of which, how full should we keep the queue? Probably less
1600         // full than you'd think. A lot has to go wrong for the queue not to be
1601         // full enough and for that to have a negative effect on compile times.
1602         //
1603         // Workers are unlikely to finish at exactly the same time, so when one
1604         // finishes and takes another work item off the queue, we often have
1605         // ample time to codegen at that point before the next worker finishes.
1606         // But suppose that codegen takes so long that the workers exhaust the
1607         // queue, and we have one or more workers that have nothing to work on.
1608         // Well, it might not be so bad. Of all the LLVM modules we create and
1609         // optimize, one has to finish last. It's not necessarily the case that
1610         // by losing some concurrency for a moment, we delay the point at which
1611         // that last LLVM module is finished and the rest of compilation can
1612         // proceed. Also, when we can't take advantage of some concurrency, we
1613         // give tokens back to the job server. That enables some other rustc to
1614         // potentially make use of the available concurrency. That could even
1615         // *decrease* overall compile time if we're lucky. But yes, if no other
1616         // rustc can make use of the concurrency, then we've squandered it.
1617         //
1618         // However, keeping the queue full is also beneficial when we have a
1619         // surge in available concurrency. Then items can be taken from the
1620         // queue immediately, without having to wait for codegen.
1621         //
1622         // So, the heuristic below tries to keep one item in the queue for every
1623         // four running workers. Based on limited benchmarking, this appears to
1624         // be more than sufficient to avoid increasing compilation times.
1625         let quarter_of_workers = workers_running - 3 * workers_running / 4;
1626         items_in_queue > 0 && items_in_queue >= quarter_of_workers
1627     }
1628
1629     fn maybe_start_llvm_timer<'a>(
1630         prof: &'a SelfProfilerRef,
1631         config: &ModuleConfig,
1632         llvm_start_time: &mut Option<VerboseTimingGuard<'a>>,
1633     ) {
1634         if config.time_module && llvm_start_time.is_none() {
1635             *llvm_start_time = Some(prof.verbose_generic_activity("LLVM_passes"));
1636         }
1637     }
1638 }
1639
1640 /// `FatalError` is explicitly not `Send`.
1641 #[must_use]
1642 pub struct WorkerFatalError;
1643
1644 fn spawn_work<B: ExtraBackendMethods>(cgcx: CodegenContext<B>, work: WorkItem<B>) {
1645     B::spawn_named_thread(cgcx.time_trace, work.short_description(), move || {
1646         // Set up a destructor which will fire off a message that we're done as
1647         // we exit.
1648         struct Bomb<B: ExtraBackendMethods> {
1649             coordinator_send: Sender<Box<dyn Any + Send>>,
1650             result: Option<Result<WorkItemResult<B>, FatalError>>,
1651             worker_id: usize,
1652         }
1653         impl<B: ExtraBackendMethods> Drop for Bomb<B> {
1654             fn drop(&mut self) {
1655                 let worker_id = self.worker_id;
1656                 let msg = match self.result.take() {
1657                     Some(Ok(WorkItemResult::Compiled(m))) => {
1658                         Message::Done::<B> { result: Ok(m), worker_id }
1659                     }
1660                     Some(Ok(WorkItemResult::NeedsLink(m))) => {
1661                         Message::NeedsLink::<B> { module: m, worker_id }
1662                     }
1663                     Some(Ok(WorkItemResult::NeedsFatLTO(m))) => {
1664                         Message::NeedsFatLTO::<B> { result: m, worker_id }
1665                     }
1666                     Some(Ok(WorkItemResult::NeedsThinLTO(name, thin_buffer))) => {
1667                         Message::NeedsThinLTO::<B> { name, thin_buffer, worker_id }
1668                     }
1669                     Some(Err(FatalError)) => {
1670                         Message::Done::<B> { result: Err(Some(WorkerFatalError)), worker_id }
1671                     }
1672                     None => Message::Done::<B> { result: Err(None), worker_id },
1673                 };
1674                 drop(self.coordinator_send.send(Box::new(msg)));
1675             }
1676         }
1677
1678         let mut bomb = Bomb::<B> {
1679             coordinator_send: cgcx.coordinator_send.clone(),
1680             result: None,
1681             worker_id: cgcx.worker,
1682         };
1683
1684         // Execute the work itself, and if it finishes successfully then flag
1685         // ourselves as a success as well.
1686         //
1687         // Note that we ignore any `FatalError` coming out of `execute_work_item`,
1688         // as a diagnostic was already sent off to the main thread - just
1689         // surface that there was an error in this worker.
1690         bomb.result = {
1691             let _prof_timer = work.start_profiling(&cgcx);
1692             Some(execute_work_item(&cgcx, work))
1693         };
1694     })
1695     .expect("failed to spawn thread");
1696 }
1697
1698 enum SharedEmitterMessage {
1699     Diagnostic(Diagnostic),
1700     InlineAsmError(u32, String, Level, Option<(String, Vec<InnerSpan>)>),
1701     AbortIfErrors,
1702     Fatal(String),
1703 }
1704
1705 #[derive(Clone)]
1706 pub struct SharedEmitter {
1707     sender: Sender<SharedEmitterMessage>,
1708 }
1709
1710 pub struct SharedEmitterMain {
1711     receiver: Receiver<SharedEmitterMessage>,
1712 }
1713
1714 impl SharedEmitter {
1715     pub fn new() -> (SharedEmitter, SharedEmitterMain) {
1716         let (sender, receiver) = channel();
1717
1718         (SharedEmitter { sender }, SharedEmitterMain { receiver })
1719     }
1720
1721     pub fn inline_asm_error(
1722         &self,
1723         cookie: u32,
1724         msg: String,
1725         level: Level,
1726         source: Option<(String, Vec<InnerSpan>)>,
1727     ) {
1728         drop(self.sender.send(SharedEmitterMessage::InlineAsmError(cookie, msg, level, source)));
1729     }
1730
1731     pub fn fatal(&self, msg: &str) {
1732         drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1733     }
1734 }
1735
1736 impl Translate for SharedEmitter {
1737     fn fluent_bundle(&self) -> Option<&Lrc<rustc_errors::FluentBundle>> {
1738         None
1739     }
1740
1741     fn fallback_fluent_bundle(&self) -> &rustc_errors::FluentBundle {
1742         panic!("shared emitter attempted to translate a diagnostic");
1743     }
1744 }
1745
1746 impl Emitter for SharedEmitter {
1747     fn emit_diagnostic(&mut self, diag: &rustc_errors::Diagnostic) {
1748         let args: FxHashMap<Cow<'_, str>, rustc_errors::DiagnosticArgValue<'_>> =
1749             diag.args().map(|(name, arg)| (name.clone(), arg.clone())).collect();
1750         drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1751             msg: diag.message.clone(),
1752             args: args.clone(),
1753             code: diag.code.clone(),
1754             lvl: diag.level(),
1755         })));
1756         for child in &diag.children {
1757             drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1758                 msg: child.message.clone(),
1759                 args: args.clone(),
1760                 code: None,
1761                 lvl: child.level,
1762             })));
1763         }
1764         drop(self.sender.send(SharedEmitterMessage::AbortIfErrors));
1765     }
1766
1767     fn source_map(&self) -> Option<&Lrc<SourceMap>> {
1768         None
1769     }
1770 }
1771
1772 impl SharedEmitterMain {
1773     pub fn check(&self, sess: &Session, blocking: bool) {
1774         loop {
1775             let message = if blocking {
1776                 match self.receiver.recv() {
1777                     Ok(message) => Ok(message),
1778                     Err(_) => Err(()),
1779                 }
1780             } else {
1781                 match self.receiver.try_recv() {
1782                     Ok(message) => Ok(message),
1783                     Err(_) => Err(()),
1784                 }
1785             };
1786
1787             match message {
1788                 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
1789                     let handler = sess.diagnostic();
1790                     let mut d = rustc_errors::Diagnostic::new_with_messages(diag.lvl, diag.msg);
1791                     if let Some(code) = diag.code {
1792                         d.code(code);
1793                     }
1794                     d.replace_args(diag.args);
1795                     handler.emit_diagnostic(&mut d);
1796                 }
1797                 Ok(SharedEmitterMessage::InlineAsmError(cookie, msg, level, source)) => {
1798                     let msg = msg.strip_prefix("error: ").unwrap_or(&msg);
1799
1800                     let mut err = match level {
1801                         Level::Error { lint: false } => sess.struct_err(msg).forget_guarantee(),
1802                         Level::Warning(_) => sess.struct_warn(msg),
1803                         Level::Note => sess.struct_note_without_error(msg),
1804                         _ => bug!("Invalid inline asm diagnostic level"),
1805                     };
1806
1807                     // If the cookie is 0 then we don't have span information.
1808                     if cookie != 0 {
1809                         let pos = BytePos::from_u32(cookie);
1810                         let span = Span::with_root_ctxt(pos, pos);
1811                         err.set_span(span);
1812                     };
1813
1814                     // Point to the generated assembly if it is available.
1815                     if let Some((buffer, spans)) = source {
1816                         let source = sess
1817                             .source_map()
1818                             .new_source_file(FileName::inline_asm_source_code(&buffer), buffer);
1819                         let source_span = Span::with_root_ctxt(source.start_pos, source.end_pos);
1820                         let spans: Vec<_> =
1821                             spans.iter().map(|sp| source_span.from_inner(*sp)).collect();
1822                         err.span_note(spans, "instantiated into assembly here");
1823                     }
1824
1825                     err.emit();
1826                 }
1827                 Ok(SharedEmitterMessage::AbortIfErrors) => {
1828                     sess.abort_if_errors();
1829                 }
1830                 Ok(SharedEmitterMessage::Fatal(msg)) => {
1831                     sess.fatal(&msg);
1832                 }
1833                 Err(_) => {
1834                     break;
1835                 }
1836             }
1837         }
1838     }
1839 }
1840
1841 pub struct Coordinator<B: ExtraBackendMethods> {
1842     pub sender: Sender<Box<dyn Any + Send>>,
1843     future: Option<thread::JoinHandle<Result<CompiledModules, ()>>>,
1844     // Only used for the Message type.
1845     phantom: PhantomData<B>,
1846 }
1847
1848 impl<B: ExtraBackendMethods> Coordinator<B> {
1849     fn join(mut self) -> std::thread::Result<Result<CompiledModules, ()>> {
1850         self.future.take().unwrap().join()
1851     }
1852 }
1853
1854 impl<B: ExtraBackendMethods> Drop for Coordinator<B> {
1855     fn drop(&mut self) {
1856         if let Some(future) = self.future.take() {
1857             // If we haven't joined yet, signal to the coordinator that it should spawn no more
1858             // work, and wait for worker threads to finish.
1859             drop(self.sender.send(Box::new(Message::CodegenAborted::<B>)));
1860             drop(future.join());
1861         }
1862     }
1863 }
1864
1865 pub struct OngoingCodegen<B: ExtraBackendMethods> {
1866     pub backend: B,
1867     pub metadata: EncodedMetadata,
1868     pub metadata_module: Option<CompiledModule>,
1869     pub crate_info: CrateInfo,
1870     pub codegen_worker_receive: Receiver<Message<B>>,
1871     pub shared_emitter_main: SharedEmitterMain,
1872     pub output_filenames: Arc<OutputFilenames>,
1873     pub coordinator: Coordinator<B>,
1874 }
1875
1876 impl<B: ExtraBackendMethods> OngoingCodegen<B> {
1877     pub fn join(self, sess: &Session) -> (CodegenResults, FxHashMap<WorkProductId, WorkProduct>) {
1878         let _timer = sess.timer("finish_ongoing_codegen");
1879
1880         self.shared_emitter_main.check(sess, true);
1881         let compiled_modules = sess.time("join_worker_thread", || match self.coordinator.join() {
1882             Ok(Ok(compiled_modules)) => compiled_modules,
1883             Ok(Err(())) => {
1884                 sess.abort_if_errors();
1885                 panic!("expected abort due to worker thread errors")
1886             }
1887             Err(_) => {
1888                 bug!("panic during codegen/LLVM phase");
1889             }
1890         });
1891
1892         sess.cgu_reuse_tracker.check_expected_reuse(sess);
1893
1894         sess.abort_if_errors();
1895
1896         let work_products =
1897             copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess, &compiled_modules);
1898         produce_final_output_artifacts(sess, &compiled_modules, &self.output_filenames);
1899
1900         // FIXME: time_llvm_passes support - does this use a global context or
1901         // something?
1902         if sess.codegen_units() == 1 && sess.opts.unstable_opts.time_llvm_passes {
1903             self.backend.print_pass_timings()
1904         }
1905
1906         (
1907             CodegenResults {
1908                 metadata: self.metadata,
1909                 crate_info: self.crate_info,
1910
1911                 modules: compiled_modules.modules,
1912                 allocator_module: compiled_modules.allocator_module,
1913                 metadata_module: self.metadata_module,
1914             },
1915             work_products,
1916         )
1917     }
1918
1919     pub fn submit_pre_codegened_module_to_llvm(
1920         &self,
1921         tcx: TyCtxt<'_>,
1922         module: ModuleCodegen<B::Module>,
1923     ) {
1924         self.wait_for_signal_to_codegen_item();
1925         self.check_for_errors(tcx.sess);
1926
1927         // These are generally cheap and won't throw off scheduling.
1928         let cost = 0;
1929         submit_codegened_module_to_llvm(&self.backend, &self.coordinator.sender, module, cost);
1930     }
1931
1932     pub fn codegen_finished(&self, tcx: TyCtxt<'_>) {
1933         self.wait_for_signal_to_codegen_item();
1934         self.check_for_errors(tcx.sess);
1935         drop(self.coordinator.sender.send(Box::new(Message::CodegenComplete::<B>)));
1936     }
1937
1938     pub fn check_for_errors(&self, sess: &Session) {
1939         self.shared_emitter_main.check(sess, false);
1940     }
1941
1942     pub fn wait_for_signal_to_codegen_item(&self) {
1943         match self.codegen_worker_receive.recv() {
1944             Ok(Message::CodegenItem) => {
1945                 // Nothing to do
1946             }
1947             Ok(_) => panic!("unexpected message"),
1948             Err(_) => {
1949                 // One of the LLVM threads must have panicked, fall through so
1950                 // error handling can be reached.
1951             }
1952         }
1953     }
1954 }
1955
1956 pub fn submit_codegened_module_to_llvm<B: ExtraBackendMethods>(
1957     _backend: &B,
1958     tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
1959     module: ModuleCodegen<B::Module>,
1960     cost: u64,
1961 ) {
1962     let llvm_work_item = WorkItem::Optimize(module);
1963     drop(tx_to_llvm_workers.send(Box::new(Message::CodegenDone::<B> { llvm_work_item, cost })));
1964 }
1965
1966 pub fn submit_post_lto_module_to_llvm<B: ExtraBackendMethods>(
1967     _backend: &B,
1968     tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
1969     module: CachedModuleCodegen,
1970 ) {
1971     let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
1972     drop(tx_to_llvm_workers.send(Box::new(Message::CodegenDone::<B> { llvm_work_item, cost: 0 })));
1973 }
1974
1975 pub fn submit_pre_lto_module_to_llvm<B: ExtraBackendMethods>(
1976     _backend: &B,
1977     tcx: TyCtxt<'_>,
1978     tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
1979     module: CachedModuleCodegen,
1980 ) {
1981     let filename = pre_lto_bitcode_filename(&module.name);
1982     let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
1983     let file = fs::File::open(&bc_path)
1984         .unwrap_or_else(|e| panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e));
1985
1986     let mmap = unsafe {
1987         Mmap::map(file).unwrap_or_else(|e| {
1988             panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
1989         })
1990     };
1991     // Schedule the module to be loaded
1992     drop(tx_to_llvm_workers.send(Box::new(Message::AddImportOnlyModule::<B> {
1993         module_data: SerializedModule::FromUncompressedFile(mmap),
1994         work_product: module.source,
1995     })));
1996 }
1997
1998 pub fn pre_lto_bitcode_filename(module_name: &str) -> String {
1999     format!("{}.{}", module_name, PRE_LTO_BC_EXT)
2000 }
2001
2002 fn msvc_imps_needed(tcx: TyCtxt<'_>) -> bool {
2003     // This should never be true (because it's not supported). If it is true,
2004     // something is wrong with commandline arg validation.
2005     assert!(
2006         !(tcx.sess.opts.cg.linker_plugin_lto.enabled()
2007             && tcx.sess.target.is_like_windows
2008             && tcx.sess.opts.cg.prefer_dynamic)
2009     );
2010
2011     tcx.sess.target.is_like_windows &&
2012         tcx.sess.crate_types().iter().any(|ct| *ct == CrateType::Rlib) &&
2013     // ThinLTO can't handle this workaround in all cases, so we don't
2014     // emit the `__imp_` symbols. Instead we make them unnecessary by disallowing
2015     // dynamic linking when linker plugin LTO is enabled.
2016     !tcx.sess.opts.cg.linker_plugin_lto.enabled()
2017 }