]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_ssa/back/write.rs
Auto merge of #58406 - Disasm:rv64-support, r=nagisa
[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, Sanitizer, Lto};
16 use rustc::session::Session;
17 use rustc::util::nodemap::FxHashMap;
18 use rustc::util::time_graph::{self, TimeGraph, Timeline};
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_fs_util::link_or_copy;
23 use rustc_data_structures::svh::Svh;
24 use rustc_errors::{Handler, Level, DiagnosticBuilder, FatalError, DiagnosticId};
25 use rustc_errors::emitter::{Emitter};
26 use rustc_target::spec::MergeFunctions;
27 use syntax::attr;
28 use syntax::ext::hygiene::Mark;
29 use syntax_pos::MultiSpan;
30 use syntax_pos::symbol::Symbol;
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: Option<String>,
58     pub pgo_use: String,
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: None,
96             pgo_use: String::new(),
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_passes();
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 lto: Lto,
205     pub no_landing_pads: bool,
206     pub save_temps: bool,
207     pub fewer_names: bool,
208     pub exported_symbols: Option<Arc<ExportedSymbols>>,
209     pub opts: Arc<config::Options>,
210     pub crate_types: Vec<config::CrateType>,
211     pub each_linked_rlib_for_lto: Vec<(CrateNum, PathBuf)>,
212     pub output_filenames: Arc<OutputFilenames>,
213     pub regular_module_config: Arc<ModuleConfig>,
214     pub metadata_module_config: Arc<ModuleConfig>,
215     pub allocator_module_config: Arc<ModuleConfig>,
216     pub tm_factory: TargetMachineFactory<B>,
217     pub msvc_imps_needed: bool,
218     pub target_pointer_width: String,
219     pub debuginfo: config::DebugInfo,
220
221     // Number of cgus excluding the allocator/metadata modules
222     pub total_cgus: usize,
223     // Handler to use for diagnostics produced during codegen.
224     pub diag_emitter: SharedEmitter,
225     // LLVM passes added by plugins.
226     pub plugin_passes: Vec<String>,
227     // LLVM optimizations for which we want to print remarks.
228     pub remark: Passes,
229     // Worker thread number
230     pub worker: usize,
231     // The incremental compilation session directory, or None if we are not
232     // compiling incrementally
233     pub incr_comp_session_dir: Option<PathBuf>,
234     // Used to update CGU re-use information during the thinlto phase.
235     pub cgu_reuse_tracker: CguReuseTracker,
236     // Channel back to the main control thread to send messages to
237     pub coordinator_send: Sender<Box<dyn Any + Send>>,
238     // A reference to the TimeGraph so we can register timings. None means that
239     // measuring is disabled.
240     pub time_graph: Option<TimeGraph>,
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, false, 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 mut timeline = cgcx.time_graph.as_ref().map(|tg| {
266         tg.start(CODEGEN_WORKER_TIMELINE,
267                  CODEGEN_WORK_PACKAGE_KIND,
268                  "generate lto")
269     }).unwrap_or(Timeline::noop());
270
271     let (lto_modules, copy_jobs) = if !needs_fat_lto.is_empty() {
272         assert!(needs_thin_lto.is_empty());
273         let lto_module = B::run_fat_lto(
274             cgcx,
275             needs_fat_lto,
276             import_only_modules,
277             &mut timeline,
278         )
279         .unwrap_or_else(|e| e.raise());
280         (vec![lto_module], vec![])
281     } else {
282         assert!(needs_fat_lto.is_empty());
283         B::run_thin_lto(cgcx, needs_thin_lto, import_only_modules, &mut timeline)
284             .unwrap_or_else(|e| e.raise())
285     };
286
287     lto_modules.into_iter().map(|module| {
288         let cost = module.cost();
289         (WorkItem::LTO(module), cost)
290     }).chain(copy_jobs.into_iter().map(|wp| {
291         (WorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
292             name: wp.cgu_name.clone(),
293             source: wp,
294         }), 0)
295     })).collect()
296 }
297
298 pub struct CompiledModules {
299     pub modules: Vec<CompiledModule>,
300     pub metadata_module: CompiledModule,
301     pub allocator_module: Option<CompiledModule>,
302 }
303
304 fn need_crate_bitcode_for_rlib(sess: &Session) -> bool {
305     sess.crate_types.borrow().contains(&config::CrateType::Rlib) &&
306     sess.opts.output_types.contains_key(&OutputType::Exe)
307 }
308
309 fn need_pre_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
310     if sess.opts.incremental.is_none() {
311         return false
312     }
313
314     match sess.lto() {
315         Lto::No => false,
316         Lto::Fat |
317         Lto::Thin |
318         Lto::ThinLocal => true,
319     }
320 }
321
322 pub fn start_async_codegen<B: ExtraBackendMethods>(
323     backend: B,
324     tcx: TyCtxt,
325     time_graph: Option<TimeGraph>,
326     metadata: EncodedMetadata,
327     coordinator_receive: Receiver<Box<dyn Any + Send>>,
328     total_cgus: usize
329 ) -> OngoingCodegen<B> {
330     let sess = tcx.sess;
331     let crate_name = tcx.crate_name(LOCAL_CRATE);
332     let crate_hash = tcx.crate_hash(LOCAL_CRATE);
333     let no_builtins = attr::contains_name(&tcx.hir().krate().attrs, "no_builtins");
334     let subsystem = attr::first_attr_value_str_by_name(&tcx.hir().krate().attrs,
335                                                        "windows_subsystem");
336     let windows_subsystem = subsystem.map(|subsystem| {
337         if subsystem != "windows" && subsystem != "console" {
338             tcx.sess.fatal(&format!("invalid windows subsystem `{}`, only \
339                                      `windows` and `console` are allowed",
340                                     subsystem));
341         }
342         subsystem.to_string()
343     });
344
345     let linker_info = LinkerInfo::new(tcx);
346     let crate_info = CrateInfo::new(tcx);
347
348     // Figure out what we actually need to build.
349     let mut modules_config = ModuleConfig::new(sess.opts.cg.passes.clone());
350     let mut metadata_config = ModuleConfig::new(vec![]);
351     let mut allocator_config = ModuleConfig::new(vec![]);
352
353     if let Some(ref sanitizer) = sess.opts.debugging_opts.sanitizer {
354         match *sanitizer {
355             Sanitizer::Address => {
356                 modules_config.passes.push("asan".to_owned());
357                 modules_config.passes.push("asan-module".to_owned());
358             }
359             Sanitizer::Memory => {
360                 modules_config.passes.push("msan".to_owned())
361             }
362             Sanitizer::Thread => {
363                 modules_config.passes.push("tsan".to_owned())
364             }
365             _ => {}
366         }
367     }
368
369     if sess.opts.debugging_opts.profile {
370         modules_config.passes.push("insert-gcov-profiling".to_owned())
371     }
372
373     modules_config.pgo_gen = sess.opts.debugging_opts.pgo_gen.clone();
374     modules_config.pgo_use = sess.opts.debugging_opts.pgo_use.clone();
375
376     modules_config.opt_level = Some(sess.opts.optimize);
377     modules_config.opt_size = Some(sess.opts.optimize);
378
379     // Save all versions of the bytecode if we're saving our temporaries.
380     if sess.opts.cg.save_temps {
381         modules_config.emit_no_opt_bc = true;
382         modules_config.emit_pre_lto_bc = true;
383         modules_config.emit_bc = true;
384         modules_config.emit_lto_bc = true;
385         metadata_config.emit_bc = true;
386         allocator_config.emit_bc = true;
387     }
388
389     // Emit compressed bitcode files for the crate if we're emitting an rlib.
390     // Whenever an rlib is created, the bitcode is inserted into the archive in
391     // order to allow LTO against it.
392     if need_crate_bitcode_for_rlib(sess) {
393         modules_config.emit_bc_compressed = true;
394         allocator_config.emit_bc_compressed = true;
395     }
396
397     modules_config.emit_pre_lto_bc =
398         need_pre_lto_bitcode_for_incr_comp(sess);
399
400     modules_config.no_integrated_as = tcx.sess.opts.cg.no_integrated_as ||
401         tcx.sess.target.target.options.no_integrated_as;
402
403     for output_type in sess.opts.output_types.keys() {
404         match *output_type {
405             OutputType::Bitcode => { modules_config.emit_bc = true; }
406             OutputType::LlvmAssembly => { modules_config.emit_ir = true; }
407             OutputType::Assembly => {
408                 modules_config.emit_asm = true;
409                 // If we're not using the LLVM assembler, this function
410                 // could be invoked specially with output_type_assembly, so
411                 // in this case we still want the metadata object file.
412                 if !sess.opts.output_types.contains_key(&OutputType::Assembly) {
413                     metadata_config.emit_obj = true;
414                     allocator_config.emit_obj = true;
415                 }
416             }
417             OutputType::Object => { modules_config.emit_obj = true; }
418             OutputType::Metadata => { metadata_config.emit_obj = true; }
419             OutputType::Exe => {
420                 modules_config.emit_obj = true;
421                 metadata_config.emit_obj = true;
422                 allocator_config.emit_obj = true;
423             },
424             OutputType::Mir => {}
425             OutputType::DepInfo => {}
426         }
427     }
428
429     modules_config.set_flags(sess, no_builtins);
430     metadata_config.set_flags(sess, no_builtins);
431     allocator_config.set_flags(sess, no_builtins);
432
433     // Exclude metadata and allocator modules from time_passes output, since
434     // they throw off the "LLVM passes" measurement.
435     metadata_config.time_passes = false;
436     allocator_config.time_passes = false;
437
438     let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
439     let (codegen_worker_send, codegen_worker_receive) = channel();
440
441     let coordinator_thread = start_executing_work(backend.clone(),
442                                                   tcx,
443                                                   &crate_info,
444                                                   shared_emitter,
445                                                   codegen_worker_send,
446                                                   coordinator_receive,
447                                                   total_cgus,
448                                                   sess.jobserver.clone(),
449                                                   time_graph.clone(),
450                                                   Arc::new(modules_config),
451                                                   Arc::new(metadata_config),
452                                                   Arc::new(allocator_config));
453
454     OngoingCodegen {
455         backend,
456         crate_name,
457         crate_hash,
458         metadata,
459         windows_subsystem,
460         linker_info,
461         crate_info,
462
463         time_graph,
464         coordinator_send: tcx.tx_to_llvm_workers.lock().clone(),
465         codegen_worker_receive,
466         shared_emitter_main,
467         future: coordinator_thread,
468         output_filenames: tcx.output_filenames(LOCAL_CRATE),
469     }
470 }
471
472 fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
473     sess: &Session,
474     compiled_modules: &CompiledModules,
475 ) -> FxHashMap<WorkProductId, WorkProduct> {
476     let mut work_products = FxHashMap::default();
477
478     if sess.opts.incremental.is_none() {
479         return work_products;
480     }
481
482     for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
483         let mut files = vec![];
484
485         if let Some(ref path) = module.object {
486             files.push((WorkProductFileKind::Object, path.clone()));
487         }
488         if let Some(ref path) = module.bytecode {
489             files.push((WorkProductFileKind::Bytecode, path.clone()));
490         }
491         if let Some(ref path) = module.bytecode_compressed {
492             files.push((WorkProductFileKind::BytecodeCompressed, path.clone()));
493         }
494
495         if let Some((id, product)) =
496                 copy_cgu_workproducts_to_incr_comp_cache_dir(sess, &module.name, &files) {
497             work_products.insert(id, product);
498         }
499     }
500
501     work_products
502 }
503
504 fn produce_final_output_artifacts(sess: &Session,
505                                   compiled_modules: &CompiledModules,
506                                   crate_output: &OutputFilenames) {
507     let mut user_wants_bitcode = false;
508     let mut user_wants_objects = false;
509
510     // Produce final compile outputs.
511     let copy_gracefully = |from: &Path, to: &Path| {
512         if let Err(e) = fs::copy(from, to) {
513             sess.err(&format!("could not copy {:?} to {:?}: {}", from, to, e));
514         }
515     };
516
517     let copy_if_one_unit = |output_type: OutputType,
518                             keep_numbered: bool| {
519         if compiled_modules.modules.len() == 1 {
520             // 1) Only one codegen unit.  In this case it's no difficulty
521             //    to copy `foo.0.x` to `foo.x`.
522             let module_name = Some(&compiled_modules.modules[0].name[..]);
523             let path = crate_output.temp_path(output_type, module_name);
524             copy_gracefully(&path,
525                             &crate_output.path(output_type));
526             if !sess.opts.cg.save_temps && !keep_numbered {
527                 // The user just wants `foo.x`, not `foo.#module-name#.x`.
528                 remove(sess, &path);
529             }
530         } else {
531             let ext = crate_output.temp_path(output_type, None)
532                                   .extension()
533                                   .unwrap()
534                                   .to_str()
535                                   .unwrap()
536                                   .to_owned();
537
538             if crate_output.outputs.contains_key(&output_type) {
539                 // 2) Multiple codegen units, with `--emit foo=some_name`.  We have
540                 //    no good solution for this case, so warn the user.
541                 sess.warn(&format!("ignoring emit path because multiple .{} files \
542                                     were produced", ext));
543             } else if crate_output.single_output_file.is_some() {
544                 // 3) Multiple codegen units, with `-o some_name`.  We have
545                 //    no good solution for this case, so warn the user.
546                 sess.warn(&format!("ignoring -o because multiple .{} files \
547                                     were produced", ext));
548             } else {
549                 // 4) Multiple codegen units, but no explicit name.  We
550                 //    just leave the `foo.0.x` files in place.
551                 // (We don't have to do any work in this case.)
552             }
553         }
554     };
555
556     // Flag to indicate whether the user explicitly requested bitcode.
557     // Otherwise, we produced it only as a temporary output, and will need
558     // to get rid of it.
559     for output_type in crate_output.outputs.keys() {
560         match *output_type {
561             OutputType::Bitcode => {
562                 user_wants_bitcode = true;
563                 // Copy to .bc, but always keep the .0.bc.  There is a later
564                 // check to figure out if we should delete .0.bc files, or keep
565                 // them for making an rlib.
566                 copy_if_one_unit(OutputType::Bitcode, true);
567             }
568             OutputType::LlvmAssembly => {
569                 copy_if_one_unit(OutputType::LlvmAssembly, false);
570             }
571             OutputType::Assembly => {
572                 copy_if_one_unit(OutputType::Assembly, false);
573             }
574             OutputType::Object => {
575                 user_wants_objects = true;
576                 copy_if_one_unit(OutputType::Object, true);
577             }
578             OutputType::Mir |
579             OutputType::Metadata |
580             OutputType::Exe |
581             OutputType::DepInfo => {}
582         }
583     }
584
585     // Clean up unwanted temporary files.
586
587     // We create the following files by default:
588     //  - #crate#.#module-name#.bc
589     //  - #crate#.#module-name#.o
590     //  - #crate#.crate.metadata.bc
591     //  - #crate#.crate.metadata.o
592     //  - #crate#.o (linked from crate.##.o)
593     //  - #crate#.bc (copied from crate.##.bc)
594     // We may create additional files if requested by the user (through
595     // `-C save-temps` or `--emit=` flags).
596
597     if !sess.opts.cg.save_temps {
598         // Remove the temporary .#module-name#.o objects.  If the user didn't
599         // explicitly request bitcode (with --emit=bc), and the bitcode is not
600         // needed for building an rlib, then we must remove .#module-name#.bc as
601         // well.
602
603         // Specific rules for keeping .#module-name#.bc:
604         //  - If the user requested bitcode (`user_wants_bitcode`), and
605         //    codegen_units > 1, then keep it.
606         //  - If the user requested bitcode but codegen_units == 1, then we
607         //    can toss .#module-name#.bc because we copied it to .bc earlier.
608         //  - If we're not building an rlib and the user didn't request
609         //    bitcode, then delete .#module-name#.bc.
610         // If you change how this works, also update back::link::link_rlib,
611         // where .#module-name#.bc files are (maybe) deleted after making an
612         // rlib.
613         let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
614
615         let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units() > 1;
616
617         let keep_numbered_objects = needs_crate_object ||
618                 (user_wants_objects && sess.codegen_units() > 1);
619
620         for module in compiled_modules.modules.iter() {
621             if let Some(ref path) = module.object {
622                 if !keep_numbered_objects {
623                     remove(sess, path);
624                 }
625             }
626
627             if let Some(ref path) = module.bytecode {
628                 if !keep_numbered_bitcode {
629                     remove(sess, path);
630                 }
631             }
632         }
633
634         if !user_wants_bitcode {
635             if let Some(ref path) = compiled_modules.metadata_module.bytecode {
636                 remove(sess, &path);
637             }
638
639             if let Some(ref allocator_module) = compiled_modules.allocator_module {
640                 if let Some(ref path) = allocator_module.bytecode {
641                     remove(sess, path);
642                 }
643             }
644         }
645     }
646
647     // We leave the following files around by default:
648     //  - #crate#.o
649     //  - #crate#.crate.metadata.o
650     //  - #crate#.bc
651     // These are used in linking steps and will be cleaned up afterward.
652 }
653
654 pub fn dump_incremental_data(_codegen_results: &CodegenResults) {
655     // FIXME(mw): This does not work at the moment because the situation has
656     //            become more complicated due to incremental LTO. Now a CGU
657     //            can have more than two caching states.
658     // println!("[incremental] Re-using {} out of {} modules",
659     //           codegen_results.modules.iter().filter(|m| m.pre_existing).count(),
660     //           codegen_results.modules.len());
661 }
662
663 pub enum WorkItem<B: WriteBackendMethods> {
664     /// Optimize a newly codegened, totally unoptimized module.
665     Optimize(ModuleCodegen<B::Module>),
666     /// Copy the post-LTO artifacts from the incremental cache to the output
667     /// directory.
668     CopyPostLtoArtifacts(CachedModuleCodegen),
669     /// Performs (Thin)LTO on the given module.
670     LTO(lto::LtoModuleCodegen<B>),
671 }
672
673 impl<B: WriteBackendMethods> WorkItem<B> {
674     pub fn module_kind(&self) -> ModuleKind {
675         match *self {
676             WorkItem::Optimize(ref m) => m.kind,
677             WorkItem::CopyPostLtoArtifacts(_) |
678             WorkItem::LTO(_) => ModuleKind::Regular,
679         }
680     }
681
682     pub fn name(&self) -> String {
683         match *self {
684             WorkItem::Optimize(ref m) => format!("optimize: {}", m.name),
685             WorkItem::CopyPostLtoArtifacts(ref m) => format!("copy post LTO artifacts: {}", m.name),
686             WorkItem::LTO(ref m) => format!("lto: {}", m.name()),
687         }
688     }
689 }
690
691 enum WorkItemResult<B: WriteBackendMethods> {
692     Compiled(CompiledModule),
693     NeedsFatLTO(FatLTOInput<B>),
694     NeedsThinLTO(String, B::ThinBuffer),
695 }
696
697 pub enum FatLTOInput<B: WriteBackendMethods> {
698     Serialized {
699         name: String,
700         buffer: B::ModuleBuffer,
701     },
702     InMemory(ModuleCodegen<B::Module>),
703 }
704
705 fn execute_work_item<B: ExtraBackendMethods>(
706     cgcx: &CodegenContext<B>,
707     work_item: WorkItem<B>,
708     timeline: &mut Timeline
709 ) -> Result<WorkItemResult<B>, FatalError> {
710     let module_config = cgcx.config(work_item.module_kind());
711
712     match work_item {
713         WorkItem::Optimize(module) => {
714             execute_optimize_work_item(cgcx, module, module_config, timeline)
715         }
716         WorkItem::CopyPostLtoArtifacts(module) => {
717             execute_copy_from_cache_work_item(cgcx, module, module_config, timeline)
718         }
719         WorkItem::LTO(module) => {
720             execute_lto_work_item(cgcx, module, module_config, timeline)
721         }
722     }
723 }
724
725 // Actual LTO type we end up chosing based on multiple factors.
726 enum ComputedLtoType {
727     No,
728     Thin,
729     Fat,
730 }
731
732 fn execute_optimize_work_item<B: ExtraBackendMethods>(
733     cgcx: &CodegenContext<B>,
734     module: ModuleCodegen<B::Module>,
735     module_config: &ModuleConfig,
736     timeline: &mut Timeline
737 ) -> Result<WorkItemResult<B>, FatalError> {
738     let diag_handler = cgcx.create_diag_handler();
739
740     unsafe {
741         B::optimize(cgcx, &diag_handler, &module, module_config, timeline)?;
742     }
743
744     // After we've done the initial round of optimizations we need to
745     // decide whether to synchronously codegen this module or ship it
746     // back to the coordinator thread for further LTO processing (which
747     // has to wait for all the initial modules to be optimized).
748
749     // If the linker does LTO, we don't have to do it. Note that we
750     // keep doing full LTO, if it is requested, as not to break the
751     // assumption that the output will be a single module.
752     let linker_does_lto = cgcx.opts.cg.linker_plugin_lto.enabled();
753
754     // When we're automatically doing ThinLTO for multi-codegen-unit
755     // builds we don't actually want to LTO the allocator modules if
756     // it shows up. This is due to various linker shenanigans that
757     // we'll encounter later.
758     let is_allocator = module.kind == ModuleKind::Allocator;
759
760     // We ignore a request for full crate grath LTO if the cate type
761     // is only an rlib, as there is no full crate graph to process,
762     // that'll happen later.
763     //
764     // This use case currently comes up primarily for targets that
765     // require LTO so the request for LTO is always unconditionally
766     // passed down to the backend, but we don't actually want to do
767     // anything about it yet until we've got a final product.
768     let is_rlib = cgcx.crate_types.len() == 1
769         && cgcx.crate_types[0] == config::CrateType::Rlib;
770
771     // Metadata modules never participate in LTO regardless of the lto
772     // settings.
773     let lto_type = if module.kind == ModuleKind::Metadata {
774         ComputedLtoType::No
775     } else {
776         match cgcx.lto {
777             Lto::ThinLocal if !linker_does_lto && !is_allocator
778                 => ComputedLtoType::Thin,
779             Lto::Thin if !linker_does_lto && !is_rlib
780                 => ComputedLtoType::Thin,
781             Lto::Fat if !is_rlib => ComputedLtoType::Fat,
782             _ => ComputedLtoType::No,
783         }
784     };
785
786     // If we're doing some form of incremental LTO then we need to be sure to
787     // save our module to disk first.
788     let bitcode = if cgcx.config(module.kind).emit_pre_lto_bc {
789         let filename = pre_lto_bitcode_filename(&module.name);
790         cgcx.incr_comp_session_dir.as_ref().map(|path| path.join(&filename))
791     } else {
792         None
793     };
794
795     Ok(match lto_type {
796         ComputedLtoType::No => {
797             let module = unsafe {
798                 B::codegen(cgcx, &diag_handler, module, module_config, timeline)?
799             };
800             WorkItemResult::Compiled(module)
801         }
802         ComputedLtoType::Thin => {
803             let (name, thin_buffer) = B::prepare_thin(module);
804             if let Some(path) = bitcode {
805                 fs::write(&path, thin_buffer.data()).unwrap_or_else(|e| {
806                     panic!("Error writing pre-lto-bitcode file `{}`: {}",
807                            path.display(),
808                            e);
809                 });
810             }
811             WorkItemResult::NeedsThinLTO(name, thin_buffer)
812         }
813         ComputedLtoType::Fat => {
814             match bitcode {
815                 Some(path) => {
816                     let (name, buffer) = B::serialize_module(module);
817                     fs::write(&path, buffer.data()).unwrap_or_else(|e| {
818                         panic!("Error writing pre-lto-bitcode file `{}`: {}",
819                                path.display(),
820                                e);
821                     });
822                     WorkItemResult::NeedsFatLTO(FatLTOInput::Serialized { name, buffer })
823                 }
824                 None => WorkItemResult::NeedsFatLTO(FatLTOInput::InMemory(module)),
825             }
826         }
827     })
828 }
829
830 fn execute_copy_from_cache_work_item<B: ExtraBackendMethods>(
831     cgcx: &CodegenContext<B>,
832     module: CachedModuleCodegen,
833     module_config: &ModuleConfig,
834     _: &mut Timeline
835 ) -> Result<WorkItemResult<B>, FatalError> {
836     let incr_comp_session_dir = cgcx.incr_comp_session_dir
837                                     .as_ref()
838                                     .unwrap();
839     let mut object = None;
840     let mut bytecode = None;
841     let mut bytecode_compressed = None;
842     for (kind, saved_file) in &module.source.saved_files {
843         let obj_out = match kind {
844             WorkProductFileKind::Object => {
845                 let path = cgcx.output_filenames.temp_path(OutputType::Object,
846                                                            Some(&module.name));
847                 object = Some(path.clone());
848                 path
849             }
850             WorkProductFileKind::Bytecode => {
851                 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode,
852                                                            Some(&module.name));
853                 bytecode = Some(path.clone());
854                 path
855             }
856             WorkProductFileKind::BytecodeCompressed => {
857                 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode,
858                                                            Some(&module.name))
859                     .with_extension(RLIB_BYTECODE_EXTENSION);
860                 bytecode_compressed = Some(path.clone());
861                 path
862             }
863         };
864         let source_file = in_incr_comp_dir(&incr_comp_session_dir,
865                                            &saved_file);
866         debug!("copying pre-existing module `{}` from {:?} to {}",
867                module.name,
868                source_file,
869                obj_out.display());
870         if let Err(err) = link_or_copy(&source_file, &obj_out) {
871             let diag_handler = cgcx.create_diag_handler();
872             diag_handler.err(&format!("unable to copy {} to {}: {}",
873                                       source_file.display(),
874                                       obj_out.display(),
875                                       err));
876         }
877     }
878
879     assert_eq!(object.is_some(), module_config.emit_obj);
880     assert_eq!(bytecode.is_some(), module_config.emit_bc);
881     assert_eq!(bytecode_compressed.is_some(), module_config.emit_bc_compressed);
882
883     Ok(WorkItemResult::Compiled(CompiledModule {
884         name: module.name,
885         kind: ModuleKind::Regular,
886         object,
887         bytecode,
888         bytecode_compressed,
889     }))
890 }
891
892 fn execute_lto_work_item<B: ExtraBackendMethods>(
893     cgcx: &CodegenContext<B>,
894     mut module: lto::LtoModuleCodegen<B>,
895     module_config: &ModuleConfig,
896     timeline: &mut Timeline
897 ) -> Result<WorkItemResult<B>, FatalError> {
898     let diag_handler = cgcx.create_diag_handler();
899
900     unsafe {
901         let module = module.optimize(cgcx, timeline)?;
902         let module = B::codegen(cgcx, &diag_handler, module, module_config, timeline)?;
903         Ok(WorkItemResult::Compiled(module))
904     }
905 }
906
907 pub enum Message<B: WriteBackendMethods> {
908     Token(io::Result<Acquired>),
909     NeedsFatLTO {
910         result: FatLTOInput<B>,
911         worker_id: usize,
912     },
913     NeedsThinLTO {
914         name: String,
915         thin_buffer: B::ThinBuffer,
916         worker_id: usize,
917     },
918     Done {
919         result: Result<CompiledModule, ()>,
920         worker_id: usize,
921     },
922     CodegenDone {
923         llvm_work_item: WorkItem<B>,
924         cost: u64,
925     },
926     AddImportOnlyModule {
927         module_data: SerializedModule<B::ModuleBuffer>,
928         work_product: WorkProduct,
929     },
930     CodegenComplete,
931     CodegenItem,
932     CodegenAborted,
933 }
934
935 struct Diagnostic {
936     msg: String,
937     code: Option<DiagnosticId>,
938     lvl: Level,
939 }
940
941 #[derive(PartialEq, Clone, Copy, Debug)]
942 enum MainThreadWorkerState {
943     Idle,
944     Codegenning,
945     LLVMing,
946 }
947
948 fn start_executing_work<B: ExtraBackendMethods>(
949     backend: B,
950     tcx: TyCtxt,
951     crate_info: &CrateInfo,
952     shared_emitter: SharedEmitter,
953     codegen_worker_send: Sender<Message<B>>,
954     coordinator_receive: Receiver<Box<dyn Any + Send>>,
955     total_cgus: usize,
956     jobserver: Client,
957     time_graph: Option<TimeGraph>,
958     modules_config: Arc<ModuleConfig>,
959     metadata_config: Arc<ModuleConfig>,
960     allocator_config: Arc<ModuleConfig>
961 ) -> thread::JoinHandle<Result<CompiledModules, ()>> {
962     let coordinator_send = tcx.tx_to_llvm_workers.lock().clone();
963     let sess = tcx.sess;
964
965     // Compute the set of symbols we need to retain when doing LTO (if we need to)
966     let exported_symbols = {
967         let mut exported_symbols = FxHashMap::default();
968
969         let copy_symbols = |cnum| {
970             let symbols = tcx.exported_symbols(cnum)
971                              .iter()
972                              .map(|&(s, lvl)| (s.symbol_name(tcx).to_string(), lvl))
973                              .collect();
974             Arc::new(symbols)
975         };
976
977         match sess.lto() {
978             Lto::No => None,
979             Lto::ThinLocal => {
980                 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
981                 Some(Arc::new(exported_symbols))
982             }
983             Lto::Fat | Lto::Thin => {
984                 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
985                 for &cnum in tcx.crates().iter() {
986                     exported_symbols.insert(cnum, copy_symbols(cnum));
987                 }
988                 Some(Arc::new(exported_symbols))
989             }
990         }
991     };
992
993     // First up, convert our jobserver into a helper thread so we can use normal
994     // mpsc channels to manage our messages and such.
995     // After we've requested tokens then we'll, when we can,
996     // get tokens on `coordinator_receive` which will
997     // get managed in the main loop below.
998     let coordinator_send2 = coordinator_send.clone();
999     let helper = jobserver.into_helper_thread(move |token| {
1000         drop(coordinator_send2.send(Box::new(Message::Token::<B>(token))));
1001     }).expect("failed to spawn helper thread");
1002
1003     let mut each_linked_rlib_for_lto = Vec::new();
1004     drop(link::each_linked_rlib(sess, crate_info, &mut |cnum, path| {
1005         if link::ignored_for_lto(sess, crate_info, cnum) {
1006             return
1007         }
1008         each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
1009     }));
1010
1011     let assembler_cmd = if modules_config.no_integrated_as {
1012         // HACK: currently we use linker (gcc) as our assembler
1013         let (linker, flavor) = link::linker_and_flavor(sess);
1014
1015         let (name, mut cmd) = get_linker(sess, &linker, flavor);
1016         cmd.args(&sess.target.target.options.asm_args);
1017         Some(Arc::new(AssemblerCommand {
1018             name,
1019             cmd,
1020         }))
1021     } else {
1022         None
1023     };
1024
1025     let ol = tcx.backend_optimization_level(LOCAL_CRATE);
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_passes(),
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         time_graph,
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         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 =
1294                         mem::replace(&mut needs_fat_lto, Vec::new());
1295                     let needs_thin_lto =
1296                         mem::replace(&mut needs_thin_lto, Vec::new());
1297                     let import_only_modules =
1298                         mem::replace(&mut lto_import_only_modules, Vec::new());
1299
1300                     for (work, cost) in generate_lto_work(&cgcx, needs_fat_lto,
1301                                                           needs_thin_lto, import_only_modules) {
1302                         let insertion_index = work_items
1303                             .binary_search_by_key(&cost, |&(_, cost)| cost)
1304                             .unwrap_or_else(|e| e);
1305                         work_items.insert(insertion_index, (work, cost));
1306                         if !cgcx.opts.debugging_opts.no_parallel_llvm {
1307                             helper.request_token();
1308                         }
1309                     }
1310                 }
1311
1312                 // In this branch, we know that everything has been codegened,
1313                 // so it's just a matter of determining whether the implicit
1314                 // Token is free to use for LLVM work.
1315                 match main_thread_worker_state {
1316                     MainThreadWorkerState::Idle => {
1317                         if let Some((item, _)) = work_items.pop() {
1318                             let cgcx = CodegenContext {
1319                                 worker: get_worker_id(&mut free_worker_ids),
1320                                 .. cgcx.clone()
1321                             };
1322                             maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1323                                                    &mut llvm_start_time);
1324                             main_thread_worker_state = MainThreadWorkerState::LLVMing;
1325                             spawn_work(cgcx, item);
1326                         } else {
1327                             // There is no unstarted work, so let the main thread
1328                             // take over for a running worker. Otherwise the
1329                             // implicit token would just go to waste.
1330                             // We reduce the `running` counter by one. The
1331                             // `tokens.truncate()` below will take care of
1332                             // giving the Token back.
1333                             debug_assert!(running > 0);
1334                             running -= 1;
1335                             main_thread_worker_state = MainThreadWorkerState::LLVMing;
1336                         }
1337                     }
1338                     MainThreadWorkerState::Codegenning => {
1339                         bug!("codegen worker should not be codegenning after \
1340                               codegen was already completed")
1341                     }
1342                     MainThreadWorkerState::LLVMing => {
1343                         // Already making good use of that token
1344                     }
1345                 }
1346             }
1347
1348             // Spin up what work we can, only doing this while we've got available
1349             // parallelism slots and work left to spawn.
1350             while !codegen_aborted && work_items.len() > 0 && running < tokens.len() {
1351                 let (item, _) = work_items.pop().unwrap();
1352
1353                 maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1354                                        &mut llvm_start_time);
1355
1356                 let cgcx = CodegenContext {
1357                     worker: get_worker_id(&mut free_worker_ids),
1358                     .. cgcx.clone()
1359                 };
1360
1361                 spawn_work(cgcx, item);
1362                 running += 1;
1363             }
1364
1365             // Relinquish accidentally acquired extra tokens
1366             tokens.truncate(running);
1367
1368             // If a thread exits successfully then we drop a token associated
1369             // with that worker and update our `running` count. We may later
1370             // re-acquire a token to continue running more work. We may also not
1371             // actually drop a token here if the worker was running with an
1372             // "ephemeral token"
1373             let mut free_worker = |worker_id| {
1374                 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1375                     main_thread_worker_state = MainThreadWorkerState::Idle;
1376                 } else {
1377                     running -= 1;
1378                 }
1379
1380                 free_worker_ids.push(worker_id);
1381             };
1382
1383             let msg = coordinator_receive.recv().unwrap();
1384             match *msg.downcast::<Message<B>>().ok().unwrap() {
1385                 // Save the token locally and the next turn of the loop will use
1386                 // this to spawn a new unit of work, or it may get dropped
1387                 // immediately if we have no more work to spawn.
1388                 Message::Token(token) => {
1389                     match token {
1390                         Ok(token) => {
1391                             tokens.push(token);
1392
1393                             if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1394                                 // If the main thread token is used for LLVM work
1395                                 // at the moment, we turn that thread into a regular
1396                                 // LLVM worker thread, so the main thread is free
1397                                 // to react to codegen demand.
1398                                 main_thread_worker_state = MainThreadWorkerState::Idle;
1399                                 running += 1;
1400                             }
1401                         }
1402                         Err(e) => {
1403                             let msg = &format!("failed to acquire jobserver token: {}", e);
1404                             shared_emitter.fatal(msg);
1405                             // Exit the coordinator thread
1406                             panic!("{}", msg)
1407                         }
1408                     }
1409                 }
1410
1411                 Message::CodegenDone { llvm_work_item, cost } => {
1412                     // We keep the queue sorted by estimated processing cost,
1413                     // so that more expensive items are processed earlier. This
1414                     // is good for throughput as it gives the main thread more
1415                     // time to fill up the queue and it avoids scheduling
1416                     // expensive items to the end.
1417                     // Note, however, that this is not ideal for memory
1418                     // consumption, as LLVM module sizes are not evenly
1419                     // distributed.
1420                     let insertion_index =
1421                         work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1422                     let insertion_index = match insertion_index {
1423                         Ok(idx) | Err(idx) => idx
1424                     };
1425                     work_items.insert(insertion_index, (llvm_work_item, cost));
1426
1427                     if !cgcx.opts.debugging_opts.no_parallel_llvm {
1428                         helper.request_token();
1429                     }
1430                     assert!(!codegen_aborted);
1431                     assert_eq!(main_thread_worker_state,
1432                                MainThreadWorkerState::Codegenning);
1433                     main_thread_worker_state = MainThreadWorkerState::Idle;
1434                 }
1435
1436                 Message::CodegenComplete => {
1437                     codegen_done = true;
1438                     assert!(!codegen_aborted);
1439                     assert_eq!(main_thread_worker_state,
1440                                MainThreadWorkerState::Codegenning);
1441                     main_thread_worker_state = MainThreadWorkerState::Idle;
1442                 }
1443
1444                 // If codegen is aborted that means translation was aborted due
1445                 // to some normal-ish compiler error. In this situation we want
1446                 // to exit as soon as possible, but we want to make sure all
1447                 // existing work has finished. Flag codegen as being done, and
1448                 // then conditions above will ensure no more work is spawned but
1449                 // we'll keep executing this loop until `running` hits 0.
1450                 Message::CodegenAborted => {
1451                     assert!(!codegen_aborted);
1452                     codegen_done = true;
1453                     codegen_aborted = true;
1454                     assert_eq!(main_thread_worker_state,
1455                                MainThreadWorkerState::Codegenning);
1456                 }
1457                 Message::Done { result: Ok(compiled_module), worker_id } => {
1458                     free_worker(worker_id);
1459                     match compiled_module.kind {
1460                         ModuleKind::Regular => {
1461                             compiled_modules.push(compiled_module);
1462                         }
1463                         ModuleKind::Metadata => {
1464                             assert!(compiled_metadata_module.is_none());
1465                             compiled_metadata_module = Some(compiled_module);
1466                         }
1467                         ModuleKind::Allocator => {
1468                             assert!(compiled_allocator_module.is_none());
1469                             compiled_allocator_module = Some(compiled_module);
1470                         }
1471                     }
1472                 }
1473                 Message::NeedsFatLTO { result, worker_id } => {
1474                     assert!(!started_lto);
1475                     free_worker(worker_id);
1476                     needs_fat_lto.push(result);
1477                 }
1478                 Message::NeedsThinLTO { name, thin_buffer, worker_id } => {
1479                     assert!(!started_lto);
1480                     free_worker(worker_id);
1481                     needs_thin_lto.push((name, thin_buffer));
1482                 }
1483                 Message::AddImportOnlyModule { module_data, work_product } => {
1484                     assert!(!started_lto);
1485                     assert!(!codegen_done);
1486                     assert_eq!(main_thread_worker_state,
1487                                MainThreadWorkerState::Codegenning);
1488                     lto_import_only_modules.push((module_data, work_product));
1489                     main_thread_worker_state = MainThreadWorkerState::Idle;
1490                 }
1491                 // If the thread failed that means it panicked, so we abort immediately.
1492                 Message::Done { result: Err(()), worker_id: _ } => {
1493                     bug!("worker thread panicked");
1494                 }
1495                 Message::CodegenItem => {
1496                     bug!("the coordinator should not receive codegen requests")
1497                 }
1498             }
1499         }
1500
1501         if let Some(llvm_start_time) = llvm_start_time {
1502             let total_llvm_time = Instant::now().duration_since(llvm_start_time);
1503             // This is the top-level timing for all of LLVM, set the time-depth
1504             // to zero.
1505             set_time_depth(0);
1506             print_time_passes_entry(cgcx.time_passes,
1507                                     "LLVM passes",
1508                                     total_llvm_time);
1509         }
1510
1511         // Regardless of what order these modules completed in, report them to
1512         // the backend in the same order every time to ensure that we're handing
1513         // out deterministic results.
1514         compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
1515
1516         let compiled_metadata_module = compiled_metadata_module
1517             .expect("Metadata module not compiled?");
1518
1519         Ok(CompiledModules {
1520             modules: compiled_modules,
1521             metadata_module: compiled_metadata_module,
1522             allocator_module: compiled_allocator_module,
1523         })
1524     });
1525
1526     // A heuristic that determines if we have enough LLVM WorkItems in the
1527     // queue so that the main thread can do LLVM work instead of codegen
1528     fn queue_full_enough(items_in_queue: usize,
1529                          workers_running: usize,
1530                          max_workers: usize) -> bool {
1531         // Tune me, plz.
1532         items_in_queue > 0 &&
1533         items_in_queue >= max_workers.saturating_sub(workers_running / 2)
1534     }
1535
1536     fn maybe_start_llvm_timer(config: &ModuleConfig,
1537                               llvm_start_time: &mut Option<Instant>) {
1538         // We keep track of the -Ztime-passes output manually,
1539         // since the closure-based interface does not fit well here.
1540         if config.time_passes {
1541             if llvm_start_time.is_none() {
1542                 *llvm_start_time = Some(Instant::now());
1543             }
1544         }
1545     }
1546 }
1547
1548 pub const CODEGEN_WORKER_ID: usize = ::std::usize::MAX;
1549 pub const CODEGEN_WORKER_TIMELINE: time_graph::TimelineId =
1550     time_graph::TimelineId(CODEGEN_WORKER_ID);
1551 pub const CODEGEN_WORK_PACKAGE_KIND: time_graph::WorkPackageKind =
1552     time_graph::WorkPackageKind(&["#DE9597", "#FED1D3", "#FDC5C7", "#B46668", "#88494B"]);
1553 const LLVM_WORK_PACKAGE_KIND: time_graph::WorkPackageKind =
1554     time_graph::WorkPackageKind(&["#7DB67A", "#C6EEC4", "#ACDAAA", "#579354", "#3E6F3C"]);
1555
1556 fn spawn_work<B: ExtraBackendMethods>(
1557     cgcx: CodegenContext<B>,
1558     work: WorkItem<B>
1559 ) {
1560     let depth = time_depth();
1561
1562     thread::spawn(move || {
1563         set_time_depth(depth);
1564
1565         // Set up a destructor which will fire off a message that we're done as
1566         // we exit.
1567         struct Bomb<B: ExtraBackendMethods> {
1568             coordinator_send: Sender<Box<dyn Any + Send>>,
1569             result: Option<WorkItemResult<B>>,
1570             worker_id: usize,
1571         }
1572         impl<B: ExtraBackendMethods> Drop for Bomb<B> {
1573             fn drop(&mut self) {
1574                 let worker_id = self.worker_id;
1575                 let msg = match self.result.take() {
1576                     Some(WorkItemResult::Compiled(m)) => {
1577                         Message::Done::<B> { result: Ok(m), worker_id }
1578                     }
1579                     Some(WorkItemResult::NeedsFatLTO(m)) => {
1580                         Message::NeedsFatLTO::<B> { result: m, worker_id }
1581                     }
1582                     Some(WorkItemResult::NeedsThinLTO(name, thin_buffer)) => {
1583                         Message::NeedsThinLTO::<B> { name, thin_buffer, worker_id }
1584                     }
1585                     None => Message::Done::<B> { result: Err(()), worker_id }
1586                 };
1587                 drop(self.coordinator_send.send(Box::new(msg)));
1588             }
1589         }
1590
1591         let mut bomb = Bomb::<B> {
1592             coordinator_send: cgcx.coordinator_send.clone(),
1593             result: None,
1594             worker_id: cgcx.worker,
1595         };
1596
1597         // Execute the work itself, and if it finishes successfully then flag
1598         // ourselves as a success as well.
1599         //
1600         // Note that we ignore any `FatalError` coming out of `execute_work_item`,
1601         // as a diagnostic was already sent off to the main thread - just
1602         // surface that there was an error in this worker.
1603         bomb.result = {
1604             let timeline = cgcx.time_graph.as_ref().map(|tg| {
1605                 tg.start(time_graph::TimelineId(cgcx.worker),
1606                          LLVM_WORK_PACKAGE_KIND,
1607                          &work.name())
1608             });
1609             let mut timeline = timeline.unwrap_or(Timeline::noop());
1610             execute_work_item(&cgcx, work, &mut timeline).ok()
1611         };
1612     });
1613 }
1614
1615 pub fn run_assembler<B: ExtraBackendMethods>(
1616     cgcx: &CodegenContext<B>,
1617     handler: &Handler,
1618     assembly: &Path,
1619     object: &Path
1620 ) {
1621     let assembler = cgcx.assembler_cmd
1622         .as_ref()
1623         .expect("cgcx.assembler_cmd is missing?");
1624
1625     let pname = &assembler.name;
1626     let mut cmd = assembler.cmd.clone();
1627     cmd.arg("-c").arg("-o").arg(object).arg(assembly);
1628     debug!("{:?}", cmd);
1629
1630     match cmd.output() {
1631         Ok(prog) => {
1632             if !prog.status.success() {
1633                 let mut note = prog.stderr.clone();
1634                 note.extend_from_slice(&prog.stdout);
1635
1636                 handler.struct_err(&format!("linking with `{}` failed: {}",
1637                                             pname.display(),
1638                                             prog.status))
1639                     .note(&format!("{:?}", &cmd))
1640                     .note(str::from_utf8(&note[..]).unwrap())
1641                     .emit();
1642                 handler.abort_if_errors();
1643             }
1644         },
1645         Err(e) => {
1646             handler.err(&format!("could not exec the linker `{}`: {}", pname.display(), e));
1647             handler.abort_if_errors();
1648         }
1649     }
1650 }
1651
1652
1653 enum SharedEmitterMessage {
1654     Diagnostic(Diagnostic),
1655     InlineAsmError(u32, String),
1656     AbortIfErrors,
1657     Fatal(String),
1658 }
1659
1660 #[derive(Clone)]
1661 pub struct SharedEmitter {
1662     sender: Sender<SharedEmitterMessage>,
1663 }
1664
1665 pub struct SharedEmitterMain {
1666     receiver: Receiver<SharedEmitterMessage>,
1667 }
1668
1669 impl SharedEmitter {
1670     pub fn new() -> (SharedEmitter, SharedEmitterMain) {
1671         let (sender, receiver) = channel();
1672
1673         (SharedEmitter { sender }, SharedEmitterMain { receiver })
1674     }
1675
1676     pub fn inline_asm_error(&self, cookie: u32, msg: String) {
1677         drop(self.sender.send(SharedEmitterMessage::InlineAsmError(cookie, msg)));
1678     }
1679
1680     pub fn fatal(&self, msg: &str) {
1681         drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1682     }
1683 }
1684
1685 impl Emitter for SharedEmitter {
1686     fn emit(&mut self, db: &DiagnosticBuilder) {
1687         drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1688             msg: db.message(),
1689             code: db.code.clone(),
1690             lvl: db.level,
1691         })));
1692         for child in &db.children {
1693             drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1694                 msg: child.message(),
1695                 code: None,
1696                 lvl: child.level,
1697             })));
1698         }
1699         drop(self.sender.send(SharedEmitterMessage::AbortIfErrors));
1700     }
1701 }
1702
1703 impl SharedEmitterMain {
1704     pub fn check(&self, sess: &Session, blocking: bool) {
1705         loop {
1706             let message = if blocking {
1707                 match self.receiver.recv() {
1708                     Ok(message) => Ok(message),
1709                     Err(_) => Err(()),
1710                 }
1711             } else {
1712                 match self.receiver.try_recv() {
1713                     Ok(message) => Ok(message),
1714                     Err(_) => Err(()),
1715                 }
1716             };
1717
1718             match message {
1719                 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
1720                     let handler = sess.diagnostic();
1721                     match diag.code {
1722                         Some(ref code) => {
1723                             handler.emit_with_code(&MultiSpan::new(),
1724                                                    &diag.msg,
1725                                                    code.clone(),
1726                                                    diag.lvl);
1727                         }
1728                         None => {
1729                             handler.emit(&MultiSpan::new(),
1730                                          &diag.msg,
1731                                          diag.lvl);
1732                         }
1733                     }
1734                 }
1735                 Ok(SharedEmitterMessage::InlineAsmError(cookie, msg)) => {
1736                     match Mark::from_u32(cookie).expn_info() {
1737                         Some(ei) => sess.span_err(ei.call_site, &msg),
1738                         None     => sess.err(&msg),
1739                     }
1740                 }
1741                 Ok(SharedEmitterMessage::AbortIfErrors) => {
1742                     sess.abort_if_errors();
1743                 }
1744                 Ok(SharedEmitterMessage::Fatal(msg)) => {
1745                     sess.fatal(&msg);
1746                 }
1747                 Err(_) => {
1748                     break;
1749                 }
1750             }
1751
1752         }
1753     }
1754 }
1755
1756 pub struct OngoingCodegen<B: ExtraBackendMethods> {
1757     pub backend: B,
1758     pub crate_name: Symbol,
1759     pub crate_hash: Svh,
1760     pub metadata: EncodedMetadata,
1761     pub windows_subsystem: Option<String>,
1762     pub linker_info: LinkerInfo,
1763     pub crate_info: CrateInfo,
1764     pub time_graph: Option<TimeGraph>,
1765     pub coordinator_send: Sender<Box<dyn Any + Send>>,
1766     pub codegen_worker_receive: Receiver<Message<B>>,
1767     pub shared_emitter_main: SharedEmitterMain,
1768     pub future: thread::JoinHandle<Result<CompiledModules, ()>>,
1769     pub output_filenames: Arc<OutputFilenames>,
1770 }
1771
1772 impl<B: ExtraBackendMethods> OngoingCodegen<B> {
1773     pub fn join(
1774         self,
1775         sess: &Session
1776     ) -> (CodegenResults, FxHashMap<WorkProductId, WorkProduct>) {
1777         self.shared_emitter_main.check(sess, true);
1778         let compiled_modules = match self.future.join() {
1779             Ok(Ok(compiled_modules)) => compiled_modules,
1780             Ok(Err(())) => {
1781                 sess.abort_if_errors();
1782                 panic!("expected abort due to worker thread errors")
1783             },
1784             Err(_) => {
1785                 bug!("panic during codegen/LLVM phase");
1786             }
1787         };
1788
1789         sess.cgu_reuse_tracker.check_expected_reuse(sess);
1790
1791         sess.abort_if_errors();
1792
1793         if let Some(time_graph) = self.time_graph {
1794             time_graph.dump(&format!("{}-timings", self.crate_name));
1795         }
1796
1797         let work_products =
1798             copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess,
1799                                                              &compiled_modules);
1800         produce_final_output_artifacts(sess,
1801                                        &compiled_modules,
1802                                        &self.output_filenames);
1803
1804         // FIXME: time_llvm_passes support - does this use a global context or
1805         // something?
1806         if sess.codegen_units() == 1 && sess.time_llvm_passes() {
1807             self.backend.print_pass_timings()
1808         }
1809
1810         (CodegenResults {
1811             crate_name: self.crate_name,
1812             crate_hash: self.crate_hash,
1813             metadata: self.metadata,
1814             windows_subsystem: self.windows_subsystem,
1815             linker_info: self.linker_info,
1816             crate_info: self.crate_info,
1817
1818             modules: compiled_modules.modules,
1819             allocator_module: compiled_modules.allocator_module,
1820             metadata_module: compiled_modules.metadata_module,
1821         }, work_products)
1822     }
1823
1824     pub fn submit_pre_codegened_module_to_llvm(&self,
1825                                                        tcx: TyCtxt,
1826                                                        module: ModuleCodegen<B::Module>) {
1827         self.wait_for_signal_to_codegen_item();
1828         self.check_for_errors(tcx.sess);
1829
1830         // These are generally cheap and won't through off scheduling.
1831         let cost = 0;
1832         submit_codegened_module_to_llvm(&self.backend, tcx, module, cost);
1833     }
1834
1835     pub fn codegen_finished(&self, tcx: TyCtxt) {
1836         self.wait_for_signal_to_codegen_item();
1837         self.check_for_errors(tcx.sess);
1838         drop(self.coordinator_send.send(Box::new(Message::CodegenComplete::<B>)));
1839     }
1840
1841     /// Consumes this context indicating that codegen was entirely aborted, and
1842     /// we need to exit as quickly as possible.
1843     ///
1844     /// This method blocks the current thread until all worker threads have
1845     /// finished, and all worker threads should have exited or be real close to
1846     /// exiting at this point.
1847     pub fn codegen_aborted(self) {
1848         // Signal to the coordinator it should spawn no more work and start
1849         // shutdown.
1850         drop(self.coordinator_send.send(Box::new(Message::CodegenAborted::<B>)));
1851         drop(self.future.join());
1852     }
1853
1854     pub fn check_for_errors(&self, sess: &Session) {
1855         self.shared_emitter_main.check(sess, false);
1856     }
1857
1858     pub fn wait_for_signal_to_codegen_item(&self) {
1859         match self.codegen_worker_receive.recv() {
1860             Ok(Message::CodegenItem) => {
1861                 // Nothing to do
1862             }
1863             Ok(_) => panic!("unexpected message"),
1864             Err(_) => {
1865                 // One of the LLVM threads must have panicked, fall through so
1866                 // error handling can be reached.
1867             }
1868         }
1869     }
1870 }
1871
1872 pub fn submit_codegened_module_to_llvm<B: ExtraBackendMethods>(
1873     _backend: &B,
1874     tcx: TyCtxt,
1875     module: ModuleCodegen<B::Module>,
1876     cost: u64
1877 ) {
1878     let llvm_work_item = WorkItem::Optimize(module);
1879     drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::CodegenDone::<B> {
1880         llvm_work_item,
1881         cost,
1882     })));
1883 }
1884
1885 pub fn submit_post_lto_module_to_llvm<B: ExtraBackendMethods>(
1886     _backend: &B,
1887     tcx: TyCtxt,
1888     module: CachedModuleCodegen
1889 ) {
1890     let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
1891     drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::CodegenDone::<B> {
1892         llvm_work_item,
1893         cost: 0,
1894     })));
1895 }
1896
1897 pub fn submit_pre_lto_module_to_llvm<B: ExtraBackendMethods>(
1898     _backend: &B,
1899     tcx: TyCtxt,
1900     module: CachedModuleCodegen
1901 ) {
1902     let filename = pre_lto_bitcode_filename(&module.name);
1903     let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
1904     let file = fs::File::open(&bc_path).unwrap_or_else(|e| {
1905         panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e)
1906     });
1907
1908     let mmap = unsafe {
1909         memmap::Mmap::map(&file).unwrap_or_else(|e| {
1910             panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
1911         })
1912     };
1913     // Schedule the module to be loaded
1914     drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::AddImportOnlyModule::<B> {
1915         module_data: SerializedModule::FromUncompressedFile(mmap),
1916         work_product: module.source,
1917     })));
1918 }
1919
1920 pub fn pre_lto_bitcode_filename(module_name: &str) -> String {
1921     format!("{}.{}", module_name, PRE_LTO_BC_EXT)
1922 }
1923
1924 fn msvc_imps_needed(tcx: TyCtxt) -> bool {
1925     // This should never be true (because it's not supported). If it is true,
1926     // something is wrong with commandline arg validation.
1927     assert!(!(tcx.sess.opts.cg.linker_plugin_lto.enabled() &&
1928               tcx.sess.target.target.options.is_like_msvc &&
1929               tcx.sess.opts.cg.prefer_dynamic));
1930
1931     tcx.sess.target.target.options.is_like_msvc &&
1932         tcx.sess.crate_types.borrow().iter().any(|ct| *ct == config::CrateType::Rlib) &&
1933     // ThinLTO can't handle this workaround in all cases, so we don't
1934     // emit the `__imp_` symbols. Instead we make them unnecessary by disallowing
1935     // dynamic linking when linker plugin LTO is enabled.
1936     !tcx.sess.opts.cg.linker_plugin_lto.enabled()
1937 }