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