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