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