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