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