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