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