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