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