]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_ssa/back/write.rs
Rollup merge of #58057 - michaelwoerister:stabilize-xlto, r=alexcrichton
[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_THIN_LTO_BC_EXT: &str = "pre-thin-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_thin_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_thin_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<ModuleCodegen<B::Module>>,
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         assert!(import_only_modules.is_empty());
274         let lto_module = B::run_fat_lto(cgcx, needs_fat_lto, &mut timeline)
275             .unwrap_or_else(|e| e.raise());
276         (vec![lto_module], vec![])
277     } else {
278         assert!(needs_fat_lto.is_empty());
279         B::run_thin_lto(cgcx, needs_thin_lto, import_only_modules, &mut timeline)
280             .unwrap_or_else(|e| e.raise())
281     };
282
283     lto_modules.into_iter().map(|module| {
284         let cost = module.cost();
285         (WorkItem::LTO(module), cost)
286     }).chain(copy_jobs.into_iter().map(|wp| {
287         (WorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
288             name: wp.cgu_name.clone(),
289             source: wp,
290         }), 0)
291     })).collect()
292 }
293
294 pub struct CompiledModules {
295     pub modules: Vec<CompiledModule>,
296     pub metadata_module: CompiledModule,
297     pub allocator_module: Option<CompiledModule>,
298 }
299
300 fn need_crate_bitcode_for_rlib(sess: &Session) -> bool {
301     sess.crate_types.borrow().contains(&config::CrateType::Rlib) &&
302     sess.opts.output_types.contains_key(&OutputType::Exe)
303 }
304
305 fn need_pre_thin_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
306     if sess.opts.incremental.is_none() {
307         return false
308     }
309
310     match sess.lto() {
311         Lto::Fat |
312         Lto::No => false,
313         Lto::Thin |
314         Lto::ThinLocal => true,
315     }
316 }
317
318 pub fn start_async_codegen<B: ExtraBackendMethods>(
319     backend: B,
320     tcx: TyCtxt,
321     time_graph: Option<TimeGraph>,
322     metadata: EncodedMetadata,
323     coordinator_receive: Receiver<Box<dyn Any + Send>>,
324     total_cgus: usize
325 ) -> OngoingCodegen<B> {
326     let sess = tcx.sess;
327     let crate_name = tcx.crate_name(LOCAL_CRATE);
328     let crate_hash = tcx.crate_hash(LOCAL_CRATE);
329     let no_builtins = attr::contains_name(&tcx.hir().krate().attrs, "no_builtins");
330     let subsystem = attr::first_attr_value_str_by_name(&tcx.hir().krate().attrs,
331                                                        "windows_subsystem");
332     let windows_subsystem = subsystem.map(|subsystem| {
333         if subsystem != "windows" && subsystem != "console" {
334             tcx.sess.fatal(&format!("invalid windows subsystem `{}`, only \
335                                      `windows` and `console` are allowed",
336                                     subsystem));
337         }
338         subsystem.to_string()
339     });
340
341     let linker_info = LinkerInfo::new(tcx);
342     let crate_info = CrateInfo::new(tcx);
343
344     // Figure out what we actually need to build.
345     let mut modules_config = ModuleConfig::new(sess.opts.cg.passes.clone());
346     let mut metadata_config = ModuleConfig::new(vec![]);
347     let mut allocator_config = ModuleConfig::new(vec![]);
348
349     if let Some(ref sanitizer) = sess.opts.debugging_opts.sanitizer {
350         match *sanitizer {
351             Sanitizer::Address => {
352                 modules_config.passes.push("asan".to_owned());
353                 modules_config.passes.push("asan-module".to_owned());
354             }
355             Sanitizer::Memory => {
356                 modules_config.passes.push("msan".to_owned())
357             }
358             Sanitizer::Thread => {
359                 modules_config.passes.push("tsan".to_owned())
360             }
361             _ => {}
362         }
363     }
364
365     if sess.opts.debugging_opts.profile {
366         modules_config.passes.push("insert-gcov-profiling".to_owned())
367     }
368
369     modules_config.pgo_gen = sess.opts.debugging_opts.pgo_gen.clone();
370     modules_config.pgo_use = sess.opts.debugging_opts.pgo_use.clone();
371
372     modules_config.opt_level = Some(sess.opts.optimize);
373     modules_config.opt_size = Some(sess.opts.optimize);
374
375     // Save all versions of the bytecode if we're saving our temporaries.
376     if sess.opts.cg.save_temps {
377         modules_config.emit_no_opt_bc = true;
378         modules_config.emit_pre_thin_lto_bc = true;
379         modules_config.emit_bc = true;
380         modules_config.emit_lto_bc = true;
381         metadata_config.emit_bc = true;
382         allocator_config.emit_bc = true;
383     }
384
385     // Emit compressed bitcode files for the crate if we're emitting an rlib.
386     // Whenever an rlib is created, the bitcode is inserted into the archive in
387     // order to allow LTO against it.
388     if need_crate_bitcode_for_rlib(sess) {
389         modules_config.emit_bc_compressed = true;
390         allocator_config.emit_bc_compressed = true;
391     }
392
393     modules_config.emit_pre_thin_lto_bc =
394         need_pre_thin_lto_bitcode_for_incr_comp(sess);
395
396     modules_config.no_integrated_as = tcx.sess.opts.cg.no_integrated_as ||
397         tcx.sess.target.target.options.no_integrated_as;
398
399     for output_type in sess.opts.output_types.keys() {
400         match *output_type {
401             OutputType::Bitcode => { modules_config.emit_bc = true; }
402             OutputType::LlvmAssembly => { modules_config.emit_ir = true; }
403             OutputType::Assembly => {
404                 modules_config.emit_asm = true;
405                 // If we're not using the LLVM assembler, this function
406                 // could be invoked specially with output_type_assembly, so
407                 // in this case we still want the metadata object file.
408                 if !sess.opts.output_types.contains_key(&OutputType::Assembly) {
409                     metadata_config.emit_obj = true;
410                     allocator_config.emit_obj = true;
411                 }
412             }
413             OutputType::Object => { modules_config.emit_obj = true; }
414             OutputType::Metadata => { metadata_config.emit_obj = true; }
415             OutputType::Exe => {
416                 modules_config.emit_obj = true;
417                 metadata_config.emit_obj = true;
418                 allocator_config.emit_obj = true;
419             },
420             OutputType::Mir => {}
421             OutputType::DepInfo => {}
422         }
423     }
424
425     modules_config.set_flags(sess, no_builtins);
426     metadata_config.set_flags(sess, no_builtins);
427     allocator_config.set_flags(sess, no_builtins);
428
429     // Exclude metadata and allocator modules from time_passes output, since
430     // they throw off the "LLVM passes" measurement.
431     metadata_config.time_passes = false;
432     allocator_config.time_passes = false;
433
434     let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
435     let (codegen_worker_send, codegen_worker_receive) = channel();
436
437     let coordinator_thread = start_executing_work(backend.clone(),
438                                                   tcx,
439                                                   &crate_info,
440                                                   shared_emitter,
441                                                   codegen_worker_send,
442                                                   coordinator_receive,
443                                                   total_cgus,
444                                                   sess.jobserver.clone(),
445                                                   time_graph.clone(),
446                                                   Arc::new(modules_config),
447                                                   Arc::new(metadata_config),
448                                                   Arc::new(allocator_config));
449
450     OngoingCodegen {
451         backend,
452         crate_name,
453         crate_hash,
454         metadata,
455         windows_subsystem,
456         linker_info,
457         crate_info,
458
459         time_graph,
460         coordinator_send: tcx.tx_to_llvm_workers.lock().clone(),
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 path) = compiled_modules.metadata_module.bytecode {
632                 remove(sess, &path);
633             }
634
635             if let Some(ref allocator_module) = compiled_modules.allocator_module {
636                 if let Some(ref path) = allocator_module.bytecode {
637                     remove(sess, path);
638                 }
639             }
640         }
641     }
642
643     // We leave the following files around by default:
644     //  - #crate#.o
645     //  - #crate#.crate.metadata.o
646     //  - #crate#.bc
647     // These are used in linking steps and will be cleaned up afterward.
648 }
649
650 pub fn dump_incremental_data(_codegen_results: &CodegenResults) {
651     // FIXME(mw): This does not work at the moment because the situation has
652     //            become more complicated due to incremental LTO. Now a CGU
653     //            can have more than two caching states.
654     // println!("[incremental] Re-using {} out of {} modules",
655     //           codegen_results.modules.iter().filter(|m| m.pre_existing).count(),
656     //           codegen_results.modules.len());
657 }
658
659 pub enum WorkItem<B: WriteBackendMethods> {
660     /// Optimize a newly codegened, totally unoptimized module.
661     Optimize(ModuleCodegen<B::Module>),
662     /// Copy the post-LTO artifacts from the incremental cache to the output
663     /// directory.
664     CopyPostLtoArtifacts(CachedModuleCodegen),
665     /// Performs (Thin)LTO on the given module.
666     LTO(lto::LtoModuleCodegen<B>),
667 }
668
669 impl<B: WriteBackendMethods> WorkItem<B> {
670     pub fn module_kind(&self) -> ModuleKind {
671         match *self {
672             WorkItem::Optimize(ref m) => m.kind,
673             WorkItem::CopyPostLtoArtifacts(_) |
674             WorkItem::LTO(_) => ModuleKind::Regular,
675         }
676     }
677
678     pub fn name(&self) -> String {
679         match *self {
680             WorkItem::Optimize(ref m) => format!("optimize: {}", m.name),
681             WorkItem::CopyPostLtoArtifacts(ref m) => format!("copy post LTO artifacts: {}", m.name),
682             WorkItem::LTO(ref m) => format!("lto: {}", m.name()),
683         }
684     }
685 }
686
687 enum WorkItemResult<B: WriteBackendMethods> {
688     Compiled(CompiledModule),
689     NeedsFatLTO(ModuleCodegen<B::Module>),
690     NeedsThinLTO(String, B::ThinBuffer),
691 }
692
693 fn execute_work_item<B: ExtraBackendMethods>(
694     cgcx: &CodegenContext<B>,
695     work_item: WorkItem<B>,
696     timeline: &mut Timeline
697 ) -> Result<WorkItemResult<B>, FatalError> {
698     let module_config = cgcx.config(work_item.module_kind());
699
700     match work_item {
701         WorkItem::Optimize(module) => {
702             execute_optimize_work_item(cgcx, module, module_config, timeline)
703         }
704         WorkItem::CopyPostLtoArtifacts(module) => {
705             execute_copy_from_cache_work_item(cgcx, module, module_config, timeline)
706         }
707         WorkItem::LTO(module) => {
708             execute_lto_work_item(cgcx, module, module_config, timeline)
709         }
710     }
711 }
712
713 // Actual LTO type we end up chosing based on multiple factors.
714 enum ComputedLtoType {
715     No,
716     Thin,
717     Fat,
718 }
719
720 fn execute_optimize_work_item<B: ExtraBackendMethods>(
721     cgcx: &CodegenContext<B>,
722     module: ModuleCodegen<B::Module>,
723     module_config: &ModuleConfig,
724     timeline: &mut Timeline
725 ) -> Result<WorkItemResult<B>, FatalError> {
726     let diag_handler = cgcx.create_diag_handler();
727
728     unsafe {
729         B::optimize(cgcx, &diag_handler, &module, module_config, timeline)?;
730     }
731
732     // After we've done the initial round of optimizations we need to
733     // decide whether to synchronously codegen this module or ship it
734     // back to the coordinator thread for further LTO processing (which
735     // has to wait for all the initial modules to be optimized).
736
737     // If the linker does LTO, we don't have to do it. Note that we
738     // keep doing full LTO, if it is requested, as not to break the
739     // assumption that the output will be a single module.
740     let linker_does_lto = cgcx.opts.cg.linker_plugin_lto.enabled();
741
742     // When we're automatically doing ThinLTO for multi-codegen-unit
743     // builds we don't actually want to LTO the allocator modules if
744     // it shows up. This is due to various linker shenanigans that
745     // we'll encounter later.
746     let is_allocator = module.kind == ModuleKind::Allocator;
747
748     // We ignore a request for full crate grath LTO if the cate type
749     // is only an rlib, as there is no full crate graph to process,
750     // that'll happen later.
751     //
752     // This use case currently comes up primarily for targets that
753     // require LTO so the request for LTO is always unconditionally
754     // passed down to the backend, but we don't actually want to do
755     // anything about it yet until we've got a final product.
756     let is_rlib = cgcx.crate_types.len() == 1
757         && cgcx.crate_types[0] == config::CrateType::Rlib;
758
759     // Metadata modules never participate in LTO regardless of the lto
760     // settings.
761     let lto_type = if module.kind == ModuleKind::Metadata {
762         ComputedLtoType::No
763     } else {
764         match cgcx.lto {
765             Lto::ThinLocal if !linker_does_lto && !is_allocator
766                 => ComputedLtoType::Thin,
767             Lto::Thin if !linker_does_lto && !is_rlib
768                 => ComputedLtoType::Thin,
769             Lto::Fat if !is_rlib => ComputedLtoType::Fat,
770             _ => ComputedLtoType::No,
771         }
772     };
773
774     Ok(match lto_type {
775         ComputedLtoType::No => {
776             let module = unsafe {
777                 B::codegen(cgcx, &diag_handler, module, module_config, timeline)?
778             };
779             WorkItemResult::Compiled(module)
780         }
781         ComputedLtoType::Thin => {
782             let (name, thin_buffer) = B::prepare_thin(cgcx, module);
783             WorkItemResult::NeedsThinLTO(name, thin_buffer)
784         }
785         ComputedLtoType::Fat => WorkItemResult::NeedsFatLTO(module),
786     })
787 }
788
789 fn execute_copy_from_cache_work_item<B: ExtraBackendMethods>(
790     cgcx: &CodegenContext<B>,
791     module: CachedModuleCodegen,
792     module_config: &ModuleConfig,
793     _: &mut Timeline
794 ) -> Result<WorkItemResult<B>, FatalError> {
795     let incr_comp_session_dir = cgcx.incr_comp_session_dir
796                                     .as_ref()
797                                     .unwrap();
798     let mut object = None;
799     let mut bytecode = None;
800     let mut bytecode_compressed = None;
801     for (kind, saved_file) in &module.source.saved_files {
802         let obj_out = match kind {
803             WorkProductFileKind::Object => {
804                 let path = cgcx.output_filenames.temp_path(OutputType::Object,
805                                                            Some(&module.name));
806                 object = Some(path.clone());
807                 path
808             }
809             WorkProductFileKind::Bytecode => {
810                 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode,
811                                                            Some(&module.name));
812                 bytecode = Some(path.clone());
813                 path
814             }
815             WorkProductFileKind::BytecodeCompressed => {
816                 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode,
817                                                            Some(&module.name))
818                     .with_extension(RLIB_BYTECODE_EXTENSION);
819                 bytecode_compressed = Some(path.clone());
820                 path
821             }
822         };
823         let source_file = in_incr_comp_dir(&incr_comp_session_dir,
824                                            &saved_file);
825         debug!("copying pre-existing module `{}` from {:?} to {}",
826                module.name,
827                source_file,
828                obj_out.display());
829         if let Err(err) = link_or_copy(&source_file, &obj_out) {
830             let diag_handler = cgcx.create_diag_handler();
831             diag_handler.err(&format!("unable to copy {} to {}: {}",
832                                       source_file.display(),
833                                       obj_out.display(),
834                                       err));
835         }
836     }
837
838     assert_eq!(object.is_some(), module_config.emit_obj);
839     assert_eq!(bytecode.is_some(), module_config.emit_bc);
840     assert_eq!(bytecode_compressed.is_some(), module_config.emit_bc_compressed);
841
842     Ok(WorkItemResult::Compiled(CompiledModule {
843         name: module.name,
844         kind: ModuleKind::Regular,
845         object,
846         bytecode,
847         bytecode_compressed,
848     }))
849 }
850
851 fn execute_lto_work_item<B: ExtraBackendMethods>(
852     cgcx: &CodegenContext<B>,
853     mut module: lto::LtoModuleCodegen<B>,
854     module_config: &ModuleConfig,
855     timeline: &mut Timeline
856 ) -> Result<WorkItemResult<B>, FatalError> {
857     let diag_handler = cgcx.create_diag_handler();
858
859     unsafe {
860         let module = module.optimize(cgcx, timeline)?;
861         let module = B::codegen(cgcx, &diag_handler, module, module_config, timeline)?;
862         Ok(WorkItemResult::Compiled(module))
863     }
864 }
865
866 pub enum Message<B: WriteBackendMethods> {
867     Token(io::Result<Acquired>),
868     NeedsFatLTO {
869         result: ModuleCodegen<B::Module>,
870         worker_id: usize,
871     },
872     NeedsThinLTO {
873         name: String,
874         thin_buffer: B::ThinBuffer,
875         worker_id: usize,
876     },
877     Done {
878         result: Result<CompiledModule, ()>,
879         worker_id: usize,
880     },
881     CodegenDone {
882         llvm_work_item: WorkItem<B>,
883         cost: u64,
884     },
885     AddImportOnlyModule {
886         module_data: SerializedModule<B::ModuleBuffer>,
887         work_product: WorkProduct,
888     },
889     CodegenComplete,
890     CodegenItem,
891     CodegenAborted,
892 }
893
894 struct Diagnostic {
895     msg: String,
896     code: Option<DiagnosticId>,
897     lvl: Level,
898 }
899
900 #[derive(PartialEq, Clone, Copy, Debug)]
901 enum MainThreadWorkerState {
902     Idle,
903     Codegenning,
904     LLVMing,
905 }
906
907 fn start_executing_work<B: ExtraBackendMethods>(
908     backend: B,
909     tcx: TyCtxt,
910     crate_info: &CrateInfo,
911     shared_emitter: SharedEmitter,
912     codegen_worker_send: Sender<Message<B>>,
913     coordinator_receive: Receiver<Box<dyn Any + Send>>,
914     total_cgus: usize,
915     jobserver: Client,
916     time_graph: Option<TimeGraph>,
917     modules_config: Arc<ModuleConfig>,
918     metadata_config: Arc<ModuleConfig>,
919     allocator_config: Arc<ModuleConfig>
920 ) -> thread::JoinHandle<Result<CompiledModules, ()>> {
921     let coordinator_send = tcx.tx_to_llvm_workers.lock().clone();
922     let sess = tcx.sess;
923
924     // Compute the set of symbols we need to retain when doing LTO (if we need to)
925     let exported_symbols = {
926         let mut exported_symbols = FxHashMap::default();
927
928         let copy_symbols = |cnum| {
929             let symbols = tcx.exported_symbols(cnum)
930                              .iter()
931                              .map(|&(s, lvl)| (s.symbol_name(tcx).to_string(), lvl))
932                              .collect();
933             Arc::new(symbols)
934         };
935
936         match sess.lto() {
937             Lto::No => None,
938             Lto::ThinLocal => {
939                 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
940                 Some(Arc::new(exported_symbols))
941             }
942             Lto::Fat | Lto::Thin => {
943                 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
944                 for &cnum in tcx.crates().iter() {
945                     exported_symbols.insert(cnum, copy_symbols(cnum));
946                 }
947                 Some(Arc::new(exported_symbols))
948             }
949         }
950     };
951
952     // First up, convert our jobserver into a helper thread so we can use normal
953     // mpsc channels to manage our messages and such.
954     // After we've requested tokens then we'll, when we can,
955     // get tokens on `coordinator_receive` which will
956     // get managed in the main loop below.
957     let coordinator_send2 = coordinator_send.clone();
958     let helper = jobserver.into_helper_thread(move |token| {
959         drop(coordinator_send2.send(Box::new(Message::Token::<B>(token))));
960     }).expect("failed to spawn helper thread");
961
962     let mut each_linked_rlib_for_lto = Vec::new();
963     drop(link::each_linked_rlib(sess, crate_info, &mut |cnum, path| {
964         if link::ignored_for_lto(sess, crate_info, cnum) {
965             return
966         }
967         each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
968     }));
969
970     let assembler_cmd = if modules_config.no_integrated_as {
971         // HACK: currently we use linker (gcc) as our assembler
972         let (linker, flavor) = link::linker_and_flavor(sess);
973
974         let (name, mut cmd) = get_linker(sess, &linker, flavor);
975         cmd.args(&sess.target.target.options.asm_args);
976         Some(Arc::new(AssemblerCommand {
977             name,
978             cmd,
979         }))
980     } else {
981         None
982     };
983
984     let ol = tcx.backend_optimization_level(LOCAL_CRATE);
985     let cgcx = CodegenContext::<B> {
986         backend: backend.clone(),
987         crate_types: sess.crate_types.borrow().clone(),
988         each_linked_rlib_for_lto,
989         lto: sess.lto(),
990         no_landing_pads: sess.no_landing_pads(),
991         fewer_names: sess.fewer_names(),
992         save_temps: sess.opts.cg.save_temps,
993         opts: Arc::new(sess.opts.clone()),
994         time_passes: sess.time_passes(),
995         exported_symbols,
996         plugin_passes: sess.plugin_llvm_passes.borrow().clone(),
997         remark: sess.opts.cg.remark.clone(),
998         worker: 0,
999         incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1000         cgu_reuse_tracker: sess.cgu_reuse_tracker.clone(),
1001         coordinator_send,
1002         diag_emitter: shared_emitter.clone(),
1003         time_graph,
1004         output_filenames: tcx.output_filenames(LOCAL_CRATE),
1005         regular_module_config: modules_config,
1006         metadata_module_config: metadata_config,
1007         allocator_module_config: allocator_config,
1008         tm_factory: TargetMachineFactory(backend.target_machine_factory(tcx.sess, ol, false)),
1009         total_cgus,
1010         msvc_imps_needed: msvc_imps_needed(tcx),
1011         target_pointer_width: tcx.sess.target.target.target_pointer_width.clone(),
1012         debuginfo: tcx.sess.opts.debuginfo,
1013         assembler_cmd,
1014     };
1015
1016     // This is the "main loop" of parallel work happening for parallel codegen.
1017     // It's here that we manage parallelism, schedule work, and work with
1018     // messages coming from clients.
1019     //
1020     // There are a few environmental pre-conditions that shape how the system
1021     // is set up:
1022     //
1023     // - Error reporting only can happen on the main thread because that's the
1024     //   only place where we have access to the compiler `Session`.
1025     // - LLVM work can be done on any thread.
1026     // - Codegen can only happen on the main thread.
1027     // - Each thread doing substantial work most be in possession of a `Token`
1028     //   from the `Jobserver`.
1029     // - The compiler process always holds one `Token`. Any additional `Tokens`
1030     //   have to be requested from the `Jobserver`.
1031     //
1032     // Error Reporting
1033     // ===============
1034     // The error reporting restriction is handled separately from the rest: We
1035     // set up a `SharedEmitter` the holds an open channel to the main thread.
1036     // When an error occurs on any thread, the shared emitter will send the
1037     // error message to the receiver main thread (`SharedEmitterMain`). The
1038     // main thread will periodically query this error message queue and emit
1039     // any error messages it has received. It might even abort compilation if
1040     // has received a fatal error. In this case we rely on all other threads
1041     // being torn down automatically with the main thread.
1042     // Since the main thread will often be busy doing codegen work, error
1043     // reporting will be somewhat delayed, since the message queue can only be
1044     // checked in between to work packages.
1045     //
1046     // Work Processing Infrastructure
1047     // ==============================
1048     // The work processing infrastructure knows three major actors:
1049     //
1050     // - the coordinator thread,
1051     // - the main thread, and
1052     // - LLVM worker threads
1053     //
1054     // The coordinator thread is running a message loop. It instructs the main
1055     // thread about what work to do when, and it will spawn off LLVM worker
1056     // threads as open LLVM WorkItems become available.
1057     //
1058     // The job of the main thread is to codegen CGUs into LLVM work package
1059     // (since the main thread is the only thread that can do this). The main
1060     // thread will block until it receives a message from the coordinator, upon
1061     // which it will codegen one CGU, send it to the coordinator and block
1062     // again. This way the coordinator can control what the main thread is
1063     // doing.
1064     //
1065     // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1066     // available, it will spawn off a new LLVM worker thread and let it process
1067     // that a WorkItem. When a LLVM worker thread is done with its WorkItem,
1068     // it will just shut down, which also frees all resources associated with
1069     // the given LLVM module, and sends a message to the coordinator that the
1070     // has been completed.
1071     //
1072     // Work Scheduling
1073     // ===============
1074     // The scheduler's goal is to minimize the time it takes to complete all
1075     // work there is, however, we also want to keep memory consumption low
1076     // if possible. These two goals are at odds with each other: If memory
1077     // consumption were not an issue, we could just let the main thread produce
1078     // LLVM WorkItems at full speed, assuring maximal utilization of
1079     // Tokens/LLVM worker threads. However, since codegen usual is faster
1080     // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1081     // WorkItem potentially holds on to a substantial amount of memory.
1082     //
1083     // So the actual goal is to always produce just enough LLVM WorkItems as
1084     // not to starve our LLVM worker threads. That means, once we have enough
1085     // WorkItems in our queue, we can block the main thread, so it does not
1086     // produce more until we need them.
1087     //
1088     // Doing LLVM Work on the Main Thread
1089     // ----------------------------------
1090     // Since the main thread owns the compiler processes implicit `Token`, it is
1091     // wasteful to keep it blocked without doing any work. Therefore, what we do
1092     // in this case is: We spawn off an additional LLVM worker thread that helps
1093     // reduce the queue. The work it is doing corresponds to the implicit
1094     // `Token`. The coordinator will mark the main thread as being busy with
1095     // LLVM work. (The actual work happens on another OS thread but we just care
1096     // about `Tokens`, not actual threads).
1097     //
1098     // When any LLVM worker thread finishes while the main thread is marked as
1099     // "busy with LLVM work", we can do a little switcheroo: We give the Token
1100     // of the just finished thread to the LLVM worker thread that is working on
1101     // behalf of the main thread's implicit Token, thus freeing up the main
1102     // thread again. The coordinator can then again decide what the main thread
1103     // should do. This allows the coordinator to make decisions at more points
1104     // in time.
1105     //
1106     // Striking a Balance between Throughput and Memory Consumption
1107     // ------------------------------------------------------------
1108     // Since our two goals, (1) use as many Tokens as possible and (2) keep
1109     // memory consumption as low as possible, are in conflict with each other,
1110     // we have to find a trade off between them. Right now, the goal is to keep
1111     // all workers busy, which means that no worker should find the queue empty
1112     // when it is ready to start.
1113     // How do we do achieve this? Good question :) We actually never know how
1114     // many `Tokens` are potentially available so it's hard to say how much to
1115     // fill up the queue before switching the main thread to LLVM work. Also we
1116     // currently don't have a means to estimate how long a running LLVM worker
1117     // will still be busy with it's current WorkItem. However, we know the
1118     // maximal count of available Tokens that makes sense (=the number of CPU
1119     // cores), so we can take a conservative guess. The heuristic we use here
1120     // is implemented in the `queue_full_enough()` function.
1121     //
1122     // Some Background on Jobservers
1123     // -----------------------------
1124     // It's worth also touching on the management of parallelism here. We don't
1125     // want to just spawn a thread per work item because while that's optimal
1126     // parallelism it may overload a system with too many threads or violate our
1127     // configuration for the maximum amount of cpu to use for this process. To
1128     // manage this we use the `jobserver` crate.
1129     //
1130     // Job servers are an artifact of GNU make and are used to manage
1131     // parallelism between processes. A jobserver is a glorified IPC semaphore
1132     // basically. Whenever we want to run some work we acquire the semaphore,
1133     // and whenever we're done with that work we release the semaphore. In this
1134     // manner we can ensure that the maximum number of parallel workers is
1135     // capped at any one point in time.
1136     //
1137     // LTO and the coordinator thread
1138     // ------------------------------
1139     //
1140     // The final job the coordinator thread is responsible for is managing LTO
1141     // and how that works. When LTO is requested what we'll to is collect all
1142     // optimized LLVM modules into a local vector on the coordinator. Once all
1143     // modules have been codegened and optimized we hand this to the `lto`
1144     // module for further optimization. The `lto` module will return back a list
1145     // of more modules to work on, which the coordinator will continue to spawn
1146     // work for.
1147     //
1148     // Each LLVM module is automatically sent back to the coordinator for LTO if
1149     // necessary. There's already optimizations in place to avoid sending work
1150     // back to the coordinator if LTO isn't requested.
1151     return thread::spawn(move || {
1152         // We pretend to be within the top-level LLVM time-passes task here:
1153         set_time_depth(1);
1154
1155         let max_workers = ::num_cpus::get();
1156         let mut worker_id_counter = 0;
1157         let mut free_worker_ids = Vec::new();
1158         let mut get_worker_id = |free_worker_ids: &mut Vec<usize>| {
1159             if let Some(id) = free_worker_ids.pop() {
1160                 id
1161             } else {
1162                 let id = worker_id_counter;
1163                 worker_id_counter += 1;
1164                 id
1165             }
1166         };
1167
1168         // This is where we collect codegen units that have gone all the way
1169         // through codegen and LLVM.
1170         let mut compiled_modules = vec![];
1171         let mut compiled_metadata_module = None;
1172         let mut compiled_allocator_module = None;
1173         let mut needs_fat_lto = Vec::new();
1174         let mut needs_thin_lto = Vec::new();
1175         let mut lto_import_only_modules = Vec::new();
1176         let mut started_lto = false;
1177         let mut codegen_aborted = false;
1178
1179         // This flag tracks whether all items have gone through codegens
1180         let mut codegen_done = false;
1181
1182         // This is the queue of LLVM work items that still need processing.
1183         let mut work_items = Vec::<(WorkItem<B>, u64)>::new();
1184
1185         // This are the Jobserver Tokens we currently hold. Does not include
1186         // the implicit Token the compiler process owns no matter what.
1187         let mut tokens = Vec::new();
1188
1189         let mut main_thread_worker_state = MainThreadWorkerState::Idle;
1190         let mut running = 0;
1191
1192         let mut llvm_start_time = None;
1193
1194         // Run the message loop while there's still anything that needs message
1195         // processing. Note that as soon as codegen is aborted we simply want to
1196         // wait for all existing work to finish, so many of the conditions here
1197         // only apply if codegen hasn't been aborted as they represent pending
1198         // work to be done.
1199         while !codegen_done ||
1200               running > 0 ||
1201               (!codegen_aborted && (
1202                   work_items.len() > 0 ||
1203                   needs_fat_lto.len() > 0 ||
1204                   needs_thin_lto.len() > 0 ||
1205                   lto_import_only_modules.len() > 0 ||
1206                   main_thread_worker_state != MainThreadWorkerState::Idle
1207               ))
1208         {
1209
1210             // While there are still CGUs to be codegened, the coordinator has
1211             // to decide how to utilize the compiler processes implicit Token:
1212             // For codegenning more CGU or for running them through LLVM.
1213             if !codegen_done {
1214                 if main_thread_worker_state == MainThreadWorkerState::Idle {
1215                     if !queue_full_enough(work_items.len(), running, max_workers) {
1216                         // The queue is not full enough, codegen more items:
1217                         if let Err(_) = codegen_worker_send.send(Message::CodegenItem) {
1218                             panic!("Could not send Message::CodegenItem to main thread")
1219                         }
1220                         main_thread_worker_state = MainThreadWorkerState::Codegenning;
1221                     } else {
1222                         // The queue is full enough to not let the worker
1223                         // threads starve. Use the implicit Token to do some
1224                         // LLVM work too.
1225                         let (item, _) = work_items.pop()
1226                             .expect("queue empty - queue_full_enough() broken?");
1227                         let cgcx = CodegenContext {
1228                             worker: get_worker_id(&mut free_worker_ids),
1229                             .. cgcx.clone()
1230                         };
1231                         maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1232                                                &mut llvm_start_time);
1233                         main_thread_worker_state = MainThreadWorkerState::LLVMing;
1234                         spawn_work(cgcx, item);
1235                     }
1236                 }
1237             } else if codegen_aborted {
1238                 // don't queue up any more work if codegen was aborted, we're
1239                 // just waiting for our existing children to finish
1240             } else {
1241                 // If we've finished everything related to normal codegen
1242                 // then it must be the case that we've got some LTO work to do.
1243                 // Perform the serial work here of figuring out what we're
1244                 // going to LTO and then push a bunch of work items onto our
1245                 // queue to do LTO
1246                 if work_items.len() == 0 &&
1247                    running == 0 &&
1248                    main_thread_worker_state == MainThreadWorkerState::Idle {
1249                     assert!(!started_lto);
1250                     started_lto = true;
1251
1252                     let needs_fat_lto =
1253                         mem::replace(&mut needs_fat_lto, Vec::new());
1254                     let needs_thin_lto =
1255                         mem::replace(&mut needs_thin_lto, Vec::new());
1256                     let import_only_modules =
1257                         mem::replace(&mut lto_import_only_modules, Vec::new());
1258
1259                     for (work, cost) in generate_lto_work(&cgcx, needs_fat_lto,
1260                                                           needs_thin_lto, import_only_modules) {
1261                         let insertion_index = work_items
1262                             .binary_search_by_key(&cost, |&(_, cost)| cost)
1263                             .unwrap_or_else(|e| e);
1264                         work_items.insert(insertion_index, (work, cost));
1265                         if !cgcx.opts.debugging_opts.no_parallel_llvm {
1266                             helper.request_token();
1267                         }
1268                     }
1269                 }
1270
1271                 // In this branch, we know that everything has been codegened,
1272                 // so it's just a matter of determining whether the implicit
1273                 // Token is free to use for LLVM work.
1274                 match main_thread_worker_state {
1275                     MainThreadWorkerState::Idle => {
1276                         if let Some((item, _)) = work_items.pop() {
1277                             let cgcx = CodegenContext {
1278                                 worker: get_worker_id(&mut free_worker_ids),
1279                                 .. cgcx.clone()
1280                             };
1281                             maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1282                                                    &mut llvm_start_time);
1283                             main_thread_worker_state = MainThreadWorkerState::LLVMing;
1284                             spawn_work(cgcx, item);
1285                         } else {
1286                             // There is no unstarted work, so let the main thread
1287                             // take over for a running worker. Otherwise the
1288                             // implicit token would just go to waste.
1289                             // We reduce the `running` counter by one. The
1290                             // `tokens.truncate()` below will take care of
1291                             // giving the Token back.
1292                             debug_assert!(running > 0);
1293                             running -= 1;
1294                             main_thread_worker_state = MainThreadWorkerState::LLVMing;
1295                         }
1296                     }
1297                     MainThreadWorkerState::Codegenning => {
1298                         bug!("codegen worker should not be codegenning after \
1299                               codegen was already completed")
1300                     }
1301                     MainThreadWorkerState::LLVMing => {
1302                         // Already making good use of that token
1303                     }
1304                 }
1305             }
1306
1307             // Spin up what work we can, only doing this while we've got available
1308             // parallelism slots and work left to spawn.
1309             while !codegen_aborted && work_items.len() > 0 && running < tokens.len() {
1310                 let (item, _) = work_items.pop().unwrap();
1311
1312                 maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1313                                        &mut llvm_start_time);
1314
1315                 let cgcx = CodegenContext {
1316                     worker: get_worker_id(&mut free_worker_ids),
1317                     .. cgcx.clone()
1318                 };
1319
1320                 spawn_work(cgcx, item);
1321                 running += 1;
1322             }
1323
1324             // Relinquish accidentally acquired extra tokens
1325             tokens.truncate(running);
1326
1327             // If a thread exits successfully then we drop a token associated
1328             // with that worker and update our `running` count. We may later
1329             // re-acquire a token to continue running more work. We may also not
1330             // actually drop a token here if the worker was running with an
1331             // "ephemeral token"
1332             let mut free_worker = |worker_id| {
1333                 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1334                     main_thread_worker_state = MainThreadWorkerState::Idle;
1335                 } else {
1336                     running -= 1;
1337                 }
1338
1339                 free_worker_ids.push(worker_id);
1340             };
1341
1342             let msg = coordinator_receive.recv().unwrap();
1343             match *msg.downcast::<Message<B>>().ok().unwrap() {
1344                 // Save the token locally and the next turn of the loop will use
1345                 // this to spawn a new unit of work, or it may get dropped
1346                 // immediately if we have no more work to spawn.
1347                 Message::Token(token) => {
1348                     match token {
1349                         Ok(token) => {
1350                             tokens.push(token);
1351
1352                             if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1353                                 // If the main thread token is used for LLVM work
1354                                 // at the moment, we turn that thread into a regular
1355                                 // LLVM worker thread, so the main thread is free
1356                                 // to react to codegen demand.
1357                                 main_thread_worker_state = MainThreadWorkerState::Idle;
1358                                 running += 1;
1359                             }
1360                         }
1361                         Err(e) => {
1362                             let msg = &format!("failed to acquire jobserver token: {}", e);
1363                             shared_emitter.fatal(msg);
1364                             // Exit the coordinator thread
1365                             panic!("{}", msg)
1366                         }
1367                     }
1368                 }
1369
1370                 Message::CodegenDone { llvm_work_item, cost } => {
1371                     // We keep the queue sorted by estimated processing cost,
1372                     // so that more expensive items are processed earlier. This
1373                     // is good for throughput as it gives the main thread more
1374                     // time to fill up the queue and it avoids scheduling
1375                     // expensive items to the end.
1376                     // Note, however, that this is not ideal for memory
1377                     // consumption, as LLVM module sizes are not evenly
1378                     // distributed.
1379                     let insertion_index =
1380                         work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1381                     let insertion_index = match insertion_index {
1382                         Ok(idx) | Err(idx) => idx
1383                     };
1384                     work_items.insert(insertion_index, (llvm_work_item, cost));
1385
1386                     if !cgcx.opts.debugging_opts.no_parallel_llvm {
1387                         helper.request_token();
1388                     }
1389                     assert!(!codegen_aborted);
1390                     assert_eq!(main_thread_worker_state,
1391                                MainThreadWorkerState::Codegenning);
1392                     main_thread_worker_state = MainThreadWorkerState::Idle;
1393                 }
1394
1395                 Message::CodegenComplete => {
1396                     codegen_done = true;
1397                     assert!(!codegen_aborted);
1398                     assert_eq!(main_thread_worker_state,
1399                                MainThreadWorkerState::Codegenning);
1400                     main_thread_worker_state = MainThreadWorkerState::Idle;
1401                 }
1402
1403                 // If codegen is aborted that means translation was aborted due
1404                 // to some normal-ish compiler error. In this situation we want
1405                 // to exit as soon as possible, but we want to make sure all
1406                 // existing work has finished. Flag codegen as being done, and
1407                 // then conditions above will ensure no more work is spawned but
1408                 // we'll keep executing this loop until `running` hits 0.
1409                 Message::CodegenAborted => {
1410                     assert!(!codegen_aborted);
1411                     codegen_done = true;
1412                     codegen_aborted = true;
1413                     assert_eq!(main_thread_worker_state,
1414                                MainThreadWorkerState::Codegenning);
1415                 }
1416                 Message::Done { result: Ok(compiled_module), worker_id } => {
1417                     free_worker(worker_id);
1418                     match compiled_module.kind {
1419                         ModuleKind::Regular => {
1420                             compiled_modules.push(compiled_module);
1421                         }
1422                         ModuleKind::Metadata => {
1423                             assert!(compiled_metadata_module.is_none());
1424                             compiled_metadata_module = Some(compiled_module);
1425                         }
1426                         ModuleKind::Allocator => {
1427                             assert!(compiled_allocator_module.is_none());
1428                             compiled_allocator_module = Some(compiled_module);
1429                         }
1430                     }
1431                 }
1432                 Message::NeedsFatLTO { result, worker_id } => {
1433                     assert!(!started_lto);
1434                     free_worker(worker_id);
1435                     needs_fat_lto.push(result);
1436                 }
1437                 Message::NeedsThinLTO { name, thin_buffer, worker_id } => {
1438                     assert!(!started_lto);
1439                     free_worker(worker_id);
1440                     needs_thin_lto.push((name, thin_buffer));
1441                 }
1442                 Message::AddImportOnlyModule { module_data, work_product } => {
1443                     assert!(!started_lto);
1444                     assert!(!codegen_done);
1445                     assert_eq!(main_thread_worker_state,
1446                                MainThreadWorkerState::Codegenning);
1447                     lto_import_only_modules.push((module_data, work_product));
1448                     main_thread_worker_state = MainThreadWorkerState::Idle;
1449                 }
1450                 // If the thread failed that means it panicked, so we abort immediately.
1451                 Message::Done { result: Err(()), worker_id: _ } => {
1452                     bug!("worker thread panicked");
1453                 }
1454                 Message::CodegenItem => {
1455                     bug!("the coordinator should not receive codegen requests")
1456                 }
1457             }
1458         }
1459
1460         if let Some(llvm_start_time) = llvm_start_time {
1461             let total_llvm_time = Instant::now().duration_since(llvm_start_time);
1462             // This is the top-level timing for all of LLVM, set the time-depth
1463             // to zero.
1464             set_time_depth(0);
1465             print_time_passes_entry(cgcx.time_passes,
1466                                     "LLVM passes",
1467                                     total_llvm_time);
1468         }
1469
1470         // Regardless of what order these modules completed in, report them to
1471         // the backend in the same order every time to ensure that we're handing
1472         // out deterministic results.
1473         compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
1474
1475         let compiled_metadata_module = compiled_metadata_module
1476             .expect("Metadata module not compiled?");
1477
1478         Ok(CompiledModules {
1479             modules: compiled_modules,
1480             metadata_module: compiled_metadata_module,
1481             allocator_module: compiled_allocator_module,
1482         })
1483     });
1484
1485     // A heuristic that determines if we have enough LLVM WorkItems in the
1486     // queue so that the main thread can do LLVM work instead of codegen
1487     fn queue_full_enough(items_in_queue: usize,
1488                          workers_running: usize,
1489                          max_workers: usize) -> bool {
1490         // Tune me, plz.
1491         items_in_queue > 0 &&
1492         items_in_queue >= max_workers.saturating_sub(workers_running / 2)
1493     }
1494
1495     fn maybe_start_llvm_timer(config: &ModuleConfig,
1496                               llvm_start_time: &mut Option<Instant>) {
1497         // We keep track of the -Ztime-passes output manually,
1498         // since the closure-based interface does not fit well here.
1499         if config.time_passes {
1500             if llvm_start_time.is_none() {
1501                 *llvm_start_time = Some(Instant::now());
1502             }
1503         }
1504     }
1505 }
1506
1507 pub const CODEGEN_WORKER_ID: usize = ::std::usize::MAX;
1508 pub const CODEGEN_WORKER_TIMELINE: time_graph::TimelineId =
1509     time_graph::TimelineId(CODEGEN_WORKER_ID);
1510 pub const CODEGEN_WORK_PACKAGE_KIND: time_graph::WorkPackageKind =
1511     time_graph::WorkPackageKind(&["#DE9597", "#FED1D3", "#FDC5C7", "#B46668", "#88494B"]);
1512 const LLVM_WORK_PACKAGE_KIND: time_graph::WorkPackageKind =
1513     time_graph::WorkPackageKind(&["#7DB67A", "#C6EEC4", "#ACDAAA", "#579354", "#3E6F3C"]);
1514
1515 fn spawn_work<B: ExtraBackendMethods>(
1516     cgcx: CodegenContext<B>,
1517     work: WorkItem<B>
1518 ) {
1519     let depth = time_depth();
1520
1521     thread::spawn(move || {
1522         set_time_depth(depth);
1523
1524         // Set up a destructor which will fire off a message that we're done as
1525         // we exit.
1526         struct Bomb<B: ExtraBackendMethods> {
1527             coordinator_send: Sender<Box<dyn Any + Send>>,
1528             result: Option<WorkItemResult<B>>,
1529             worker_id: usize,
1530         }
1531         impl<B: ExtraBackendMethods> Drop for Bomb<B> {
1532             fn drop(&mut self) {
1533                 let worker_id = self.worker_id;
1534                 let msg = match self.result.take() {
1535                     Some(WorkItemResult::Compiled(m)) => {
1536                         Message::Done::<B> { result: Ok(m), worker_id }
1537                     }
1538                     Some(WorkItemResult::NeedsFatLTO(m)) => {
1539                         Message::NeedsFatLTO::<B> { result: m, worker_id }
1540                     }
1541                     Some(WorkItemResult::NeedsThinLTO(name, thin_buffer)) => {
1542                         Message::NeedsThinLTO::<B> { name, thin_buffer, worker_id }
1543                     }
1544                     None => Message::Done::<B> { result: Err(()), worker_id }
1545                 };
1546                 drop(self.coordinator_send.send(Box::new(msg)));
1547             }
1548         }
1549
1550         let mut bomb = Bomb::<B> {
1551             coordinator_send: cgcx.coordinator_send.clone(),
1552             result: None,
1553             worker_id: cgcx.worker,
1554         };
1555
1556         // Execute the work itself, and if it finishes successfully then flag
1557         // ourselves as a success as well.
1558         //
1559         // Note that we ignore any `FatalError` coming out of `execute_work_item`,
1560         // as a diagnostic was already sent off to the main thread - just
1561         // surface that there was an error in this worker.
1562         bomb.result = {
1563             let timeline = cgcx.time_graph.as_ref().map(|tg| {
1564                 tg.start(time_graph::TimelineId(cgcx.worker),
1565                          LLVM_WORK_PACKAGE_KIND,
1566                          &work.name())
1567             });
1568             let mut timeline = timeline.unwrap_or(Timeline::noop());
1569             execute_work_item(&cgcx, work, &mut timeline).ok()
1570         };
1571     });
1572 }
1573
1574 pub fn run_assembler<B: ExtraBackendMethods>(
1575     cgcx: &CodegenContext<B>,
1576     handler: &Handler,
1577     assembly: &Path,
1578     object: &Path
1579 ) {
1580     let assembler = cgcx.assembler_cmd
1581         .as_ref()
1582         .expect("cgcx.assembler_cmd is missing?");
1583
1584     let pname = &assembler.name;
1585     let mut cmd = assembler.cmd.clone();
1586     cmd.arg("-c").arg("-o").arg(object).arg(assembly);
1587     debug!("{:?}", cmd);
1588
1589     match cmd.output() {
1590         Ok(prog) => {
1591             if !prog.status.success() {
1592                 let mut note = prog.stderr.clone();
1593                 note.extend_from_slice(&prog.stdout);
1594
1595                 handler.struct_err(&format!("linking with `{}` failed: {}",
1596                                             pname.display(),
1597                                             prog.status))
1598                     .note(&format!("{:?}", &cmd))
1599                     .note(str::from_utf8(&note[..]).unwrap())
1600                     .emit();
1601                 handler.abort_if_errors();
1602             }
1603         },
1604         Err(e) => {
1605             handler.err(&format!("could not exec the linker `{}`: {}", pname.display(), e));
1606             handler.abort_if_errors();
1607         }
1608     }
1609 }
1610
1611
1612 enum SharedEmitterMessage {
1613     Diagnostic(Diagnostic),
1614     InlineAsmError(u32, String),
1615     AbortIfErrors,
1616     Fatal(String),
1617 }
1618
1619 #[derive(Clone)]
1620 pub struct SharedEmitter {
1621     sender: Sender<SharedEmitterMessage>,
1622 }
1623
1624 pub struct SharedEmitterMain {
1625     receiver: Receiver<SharedEmitterMessage>,
1626 }
1627
1628 impl SharedEmitter {
1629     pub fn new() -> (SharedEmitter, SharedEmitterMain) {
1630         let (sender, receiver) = channel();
1631
1632         (SharedEmitter { sender }, SharedEmitterMain { receiver })
1633     }
1634
1635     pub fn inline_asm_error(&self, cookie: u32, msg: String) {
1636         drop(self.sender.send(SharedEmitterMessage::InlineAsmError(cookie, msg)));
1637     }
1638
1639     pub fn fatal(&self, msg: &str) {
1640         drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1641     }
1642 }
1643
1644 impl Emitter for SharedEmitter {
1645     fn emit(&mut self, db: &DiagnosticBuilder) {
1646         drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1647             msg: db.message(),
1648             code: db.code.clone(),
1649             lvl: db.level,
1650         })));
1651         for child in &db.children {
1652             drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1653                 msg: child.message(),
1654                 code: None,
1655                 lvl: child.level,
1656             })));
1657         }
1658         drop(self.sender.send(SharedEmitterMessage::AbortIfErrors));
1659     }
1660 }
1661
1662 impl SharedEmitterMain {
1663     pub fn check(&self, sess: &Session, blocking: bool) {
1664         loop {
1665             let message = if blocking {
1666                 match self.receiver.recv() {
1667                     Ok(message) => Ok(message),
1668                     Err(_) => Err(()),
1669                 }
1670             } else {
1671                 match self.receiver.try_recv() {
1672                     Ok(message) => Ok(message),
1673                     Err(_) => Err(()),
1674                 }
1675             };
1676
1677             match message {
1678                 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
1679                     let handler = sess.diagnostic();
1680                     match diag.code {
1681                         Some(ref code) => {
1682                             handler.emit_with_code(&MultiSpan::new(),
1683                                                    &diag.msg,
1684                                                    code.clone(),
1685                                                    diag.lvl);
1686                         }
1687                         None => {
1688                             handler.emit(&MultiSpan::new(),
1689                                          &diag.msg,
1690                                          diag.lvl);
1691                         }
1692                     }
1693                 }
1694                 Ok(SharedEmitterMessage::InlineAsmError(cookie, msg)) => {
1695                     match Mark::from_u32(cookie).expn_info() {
1696                         Some(ei) => sess.span_err(ei.call_site, &msg),
1697                         None     => sess.err(&msg),
1698                     }
1699                 }
1700                 Ok(SharedEmitterMessage::AbortIfErrors) => {
1701                     sess.abort_if_errors();
1702                 }
1703                 Ok(SharedEmitterMessage::Fatal(msg)) => {
1704                     sess.fatal(&msg);
1705                 }
1706                 Err(_) => {
1707                     break;
1708                 }
1709             }
1710
1711         }
1712     }
1713 }
1714
1715 pub struct OngoingCodegen<B: ExtraBackendMethods> {
1716     pub backend: B,
1717     pub crate_name: Symbol,
1718     pub crate_hash: Svh,
1719     pub metadata: EncodedMetadata,
1720     pub windows_subsystem: Option<String>,
1721     pub linker_info: LinkerInfo,
1722     pub crate_info: CrateInfo,
1723     pub time_graph: Option<TimeGraph>,
1724     pub coordinator_send: Sender<Box<dyn Any + Send>>,
1725     pub codegen_worker_receive: Receiver<Message<B>>,
1726     pub shared_emitter_main: SharedEmitterMain,
1727     pub future: thread::JoinHandle<Result<CompiledModules, ()>>,
1728     pub output_filenames: Arc<OutputFilenames>,
1729 }
1730
1731 impl<B: ExtraBackendMethods> OngoingCodegen<B> {
1732     pub fn join(
1733         self,
1734         sess: &Session
1735     ) -> (CodegenResults, FxHashMap<WorkProductId, WorkProduct>) {
1736         self.shared_emitter_main.check(sess, true);
1737         let compiled_modules = match self.future.join() {
1738             Ok(Ok(compiled_modules)) => compiled_modules,
1739             Ok(Err(())) => {
1740                 sess.abort_if_errors();
1741                 panic!("expected abort due to worker thread errors")
1742             },
1743             Err(_) => {
1744                 bug!("panic during codegen/LLVM phase");
1745             }
1746         };
1747
1748         sess.cgu_reuse_tracker.check_expected_reuse(sess);
1749
1750         sess.abort_if_errors();
1751
1752         if let Some(time_graph) = self.time_graph {
1753             time_graph.dump(&format!("{}-timings", self.crate_name));
1754         }
1755
1756         let work_products =
1757             copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess,
1758                                                              &compiled_modules);
1759         produce_final_output_artifacts(sess,
1760                                        &compiled_modules,
1761                                        &self.output_filenames);
1762
1763         // FIXME: time_llvm_passes support - does this use a global context or
1764         // something?
1765         if sess.codegen_units() == 1 && sess.time_llvm_passes() {
1766             self.backend.print_pass_timings()
1767         }
1768
1769         (CodegenResults {
1770             crate_name: self.crate_name,
1771             crate_hash: self.crate_hash,
1772             metadata: self.metadata,
1773             windows_subsystem: self.windows_subsystem,
1774             linker_info: self.linker_info,
1775             crate_info: self.crate_info,
1776
1777             modules: compiled_modules.modules,
1778             allocator_module: compiled_modules.allocator_module,
1779             metadata_module: compiled_modules.metadata_module,
1780         }, work_products)
1781     }
1782
1783     pub fn submit_pre_codegened_module_to_llvm(&self,
1784                                                        tcx: TyCtxt,
1785                                                        module: ModuleCodegen<B::Module>) {
1786         self.wait_for_signal_to_codegen_item();
1787         self.check_for_errors(tcx.sess);
1788
1789         // These are generally cheap and won't through off scheduling.
1790         let cost = 0;
1791         submit_codegened_module_to_llvm(&self.backend, tcx, module, cost);
1792     }
1793
1794     pub fn codegen_finished(&self, tcx: TyCtxt) {
1795         self.wait_for_signal_to_codegen_item();
1796         self.check_for_errors(tcx.sess);
1797         drop(self.coordinator_send.send(Box::new(Message::CodegenComplete::<B>)));
1798     }
1799
1800     /// Consumes this context indicating that codegen was entirely aborted, and
1801     /// we need to exit as quickly as possible.
1802     ///
1803     /// This method blocks the current thread until all worker threads have
1804     /// finished, and all worker threads should have exited or be real close to
1805     /// exiting at this point.
1806     pub fn codegen_aborted(self) {
1807         // Signal to the coordinator it should spawn no more work and start
1808         // shutdown.
1809         drop(self.coordinator_send.send(Box::new(Message::CodegenAborted::<B>)));
1810         drop(self.future.join());
1811     }
1812
1813     pub fn check_for_errors(&self, sess: &Session) {
1814         self.shared_emitter_main.check(sess, false);
1815     }
1816
1817     pub fn wait_for_signal_to_codegen_item(&self) {
1818         match self.codegen_worker_receive.recv() {
1819             Ok(Message::CodegenItem) => {
1820                 // Nothing to do
1821             }
1822             Ok(_) => panic!("unexpected message"),
1823             Err(_) => {
1824                 // One of the LLVM threads must have panicked, fall through so
1825                 // error handling can be reached.
1826             }
1827         }
1828     }
1829 }
1830
1831 pub fn submit_codegened_module_to_llvm<B: ExtraBackendMethods>(
1832     _backend: &B,
1833     tcx: TyCtxt,
1834     module: ModuleCodegen<B::Module>,
1835     cost: u64
1836 ) {
1837     let llvm_work_item = WorkItem::Optimize(module);
1838     drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::CodegenDone::<B> {
1839         llvm_work_item,
1840         cost,
1841     })));
1842 }
1843
1844 pub fn submit_post_lto_module_to_llvm<B: ExtraBackendMethods>(
1845     _backend: &B,
1846     tcx: TyCtxt,
1847     module: CachedModuleCodegen
1848 ) {
1849     let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
1850     drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::CodegenDone::<B> {
1851         llvm_work_item,
1852         cost: 0,
1853     })));
1854 }
1855
1856 pub fn submit_pre_lto_module_to_llvm<B: ExtraBackendMethods>(
1857     _backend: &B,
1858     tcx: TyCtxt,
1859     module: CachedModuleCodegen
1860 ) {
1861     let filename = pre_lto_bitcode_filename(&module.name);
1862     let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
1863     let file = fs::File::open(&bc_path).unwrap_or_else(|e| {
1864         panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e)
1865     });
1866
1867     let mmap = unsafe {
1868         memmap::Mmap::map(&file).unwrap_or_else(|e| {
1869             panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
1870         })
1871     };
1872     // Schedule the module to be loaded
1873     drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::AddImportOnlyModule::<B> {
1874         module_data: SerializedModule::FromUncompressedFile(mmap),
1875         work_product: module.source,
1876     })));
1877 }
1878
1879 pub fn pre_lto_bitcode_filename(module_name: &str) -> String {
1880     format!("{}.{}", module_name, PRE_THIN_LTO_BC_EXT)
1881 }
1882
1883 fn msvc_imps_needed(tcx: TyCtxt) -> bool {
1884     // This should never be true (because it's not supported). If it is true,
1885     // something is wrong with commandline arg validation.
1886     assert!(!(tcx.sess.opts.cg.linker_plugin_lto.enabled() &&
1887               tcx.sess.target.target.options.is_like_msvc &&
1888               tcx.sess.opts.cg.prefer_dynamic));
1889
1890     tcx.sess.target.target.options.is_like_msvc &&
1891         tcx.sess.crate_types.borrow().iter().any(|ct| *ct == config::CrateType::Rlib) &&
1892     // ThinLTO can't handle this workaround in all cases, so we don't
1893     // emit the `__imp_` symbols. Instead we make them unnecessary by disallowing
1894     // dynamic linking when linker plugin LTO is enabled.
1895     !tcx.sess.opts.cg.linker_plugin_lto.enabled()
1896 }