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