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;
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;
29 use syntax::ext::hygiene::ExpnId;
30 use syntax_pos::symbol::{Symbol, sym};
31 use jobserver::{Client, Acquired};
38 use std::path::{Path, PathBuf};
41 use std::sync::mpsc::{channel, Sender, Receiver};
42 use std::time::Instant;
45 const PRE_LTO_BC_EXT: &str = "pre-lto.bc";
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>,
55 /// Some(level) to optimize binary size, or None to not affect program size.
56 pub opt_size: Option<config::OptLevel>,
58 pub pgo_gen: SwitchWithOptPath,
59 pub pgo_use: Option<PathBuf>,
61 // Flags indicating which outputs to produce.
62 pub emit_pre_lto_bc: bool,
63 pub emit_no_opt_bc: bool,
65 pub emit_bc_compressed: bool,
66 pub emit_lto_bc: bool,
70 // Miscellaneous flags. These are mostly copied from command-line
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,
90 fn new(passes: Vec<String>) -> ModuleConfig {
96 pgo_gen: SwitchWithOptPath::Disabled,
99 emit_no_opt_bc: false,
100 emit_pre_lto_bc: false,
102 emit_bc_compressed: false,
107 obj_is_bitcode: false,
108 embed_bitcode: false,
109 embed_bitcode_marker: false,
110 no_integrated_as: false,
112 verify_llvm_ir: false,
113 no_prepopulate_passes: false,
116 vectorize_loop: false,
117 vectorize_slp: false,
118 merge_functions: false,
119 inline_threshold: None
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;
134 match sess.opts.optimize {
135 config::OptLevel::No |
136 config::OptLevel::Less => {
137 self.embed_bitcode_marker = embed_bitcode;
139 _ => self.embed_bitcode = embed_bitcode,
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;
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;
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
176 pub fn bitcode_needed(&self) -> bool {
177 self.emit_bc || self.obj_is_bitcode
178 || self.emit_bc_compressed || self.embed_bitcode
182 /// Assembler name and command used by codegen when no_integrated_as is enabled
183 pub struct AssemblerCommand {
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>,
193 impl<B: WriteBackendMethods> Clone for TargetMachineFactory<B> {
194 fn clone(&self) -> Self {
195 TargetMachineFactory(self.0.clone())
199 pub struct ProfileGenericActivityTimer {
200 profiler: Option<Arc<SelfProfiler>>,
201 label: Cow<'static, str>,
204 impl ProfileGenericActivityTimer {
206 profiler: Option<Arc<SelfProfiler>>,
207 label: Cow<'static, str>,
208 ) -> ProfileGenericActivityTimer {
209 if let Some(profiler) = &profiler {
210 profiler.start_activity(label.clone());
213 ProfileGenericActivityTimer {
220 impl Drop for ProfileGenericActivityTimer {
222 if let Some(profiler) = &self.profiler {
223 profiler.end_activity(self.label.clone());
228 /// Additional resources used by optimize_and_codegen (not module specific)
230 pub struct CodegenContext<B: WriteBackendMethods> {
231 // Resources needed when running LTO
233 pub time_passes: bool,
234 pub profiler: Option<Arc<SelfProfiler>>,
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,
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.
261 // Worker thread number
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>>
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()))
279 pub fn config(&self, kind: ModuleKind) -> &ModuleConfig {
281 ModuleKind::Regular => &self.regular_module_config,
282 ModuleKind::Metadata => &self.metadata_module_config,
283 ModuleKind::Allocator => &self.allocator_module_config,
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"),
299 pub fn profile<F: FnOnce(&SelfProfiler) -> ()>(&self, f: F) {
300 if unlikely!(self.profiler.is_some()) {
301 self.profiler_active(f)
305 pub fn profile_activity(
307 label: impl Into<Cow<'static, str>>,
308 ) -> ProfileGenericActivityTimer {
309 ProfileGenericActivityTimer::start(self.profiler.clone(), label.into())
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"));
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(
328 .unwrap_or_else(|e| e.raise());
329 (vec![lto_module], vec![])
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())
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(),
346 cgcx.profile(|p| p.end_activity("codegen_run_lto"));
351 pub struct CompiledModules {
352 pub modules: Vec<CompiledModule>,
353 pub metadata_module: Option<CompiledModule>,
354 pub allocator_module: Option<CompiledModule>,
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)
362 fn need_pre_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
363 if sess.opts.incremental.is_none() {
371 Lto::ThinLocal => true,
375 pub fn start_async_codegen<B: ExtraBackendMethods>(
378 metadata: EncodedMetadata,
380 ) -> OngoingCodegen<B> {
381 let (coordinator_send, coordinator_receive) = channel();
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",
394 subsystem.to_string()
397 let linker_info = LinkerInfo::new(tcx);
398 let crate_info = CrateInfo::new(tcx);
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![]);
405 if let Some(ref sanitizer) = sess.opts.debugging_opts.sanitizer {
407 Sanitizer::Address => {
408 modules_config.passes.push("asan".to_owned());
409 modules_config.passes.push("asan-module".to_owned());
411 Sanitizer::Memory => {
412 modules_config.passes.push("msan".to_owned())
414 Sanitizer::Thread => {
415 modules_config.passes.push("tsan".to_owned())
421 if sess.opts.debugging_opts.profile {
422 modules_config.passes.push("insert-gcov-profiling".to_owned())
425 modules_config.pgo_gen = sess.opts.cg.profile_generate.clone();
426 modules_config.pgo_use = sess.opts.cg.profile_use.clone();
428 modules_config.opt_level = Some(sess.opts.optimize);
429 modules_config.opt_size = Some(sess.opts.optimize);
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;
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;
449 modules_config.emit_pre_lto_bc =
450 need_pre_lto_bitcode_for_incr_comp(sess);
452 modules_config.no_integrated_as = tcx.sess.opts.cg.no_integrated_as ||
453 tcx.sess.target.target.options.no_integrated_as;
455 for output_type in sess.opts.output_types.keys() {
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;
469 OutputType::Object => { modules_config.emit_obj = true; }
470 OutputType::Metadata => { metadata_config.emit_obj = true; }
472 modules_config.emit_obj = true;
473 metadata_config.emit_obj = true;
474 allocator_config.emit_obj = true;
476 OutputType::Mir => {}
477 OutputType::DepInfo => {}
481 modules_config.set_flags(sess, no_builtins);
482 metadata_config.set_flags(sess, no_builtins);
483 allocator_config.set_flags(sess, no_builtins);
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;
490 let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
491 let (codegen_worker_send, codegen_worker_receive) = channel();
493 let coordinator_thread = start_executing_work(backend.clone(),
500 sess.jobserver.clone(),
501 Arc::new(modules_config),
502 Arc::new(metadata_config),
503 Arc::new(allocator_config),
504 coordinator_send.clone());
516 codegen_worker_receive,
518 future: coordinator_thread,
519 output_filenames: tcx.output_filenames(LOCAL_CRATE),
523 fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
525 compiled_modules: &CompiledModules,
526 ) -> FxHashMap<WorkProductId, WorkProduct> {
527 let mut work_products = FxHashMap::default();
529 if sess.opts.incremental.is_none() {
530 return work_products;
533 for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
534 let mut files = vec![];
536 if let Some(ref path) = module.object {
537 files.push((WorkProductFileKind::Object, path.clone()));
539 if let Some(ref path) = module.bytecode {
540 files.push((WorkProductFileKind::Bytecode, path.clone()));
542 if let Some(ref path) = module.bytecode_compressed {
543 files.push((WorkProductFileKind::BytecodeCompressed, path.clone()));
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);
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;
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));
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`.
582 let ext = crate_output.temp_path(output_type, None)
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));
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.)
607 // Flag to indicate whether the user explicitly requested bitcode.
608 // Otherwise, we produced it only as a temporary output, and will need
610 for output_type in crate_output.outputs.keys() {
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);
619 OutputType::LlvmAssembly => {
620 copy_if_one_unit(OutputType::LlvmAssembly, false);
622 OutputType::Assembly => {
623 copy_if_one_unit(OutputType::Assembly, false);
625 OutputType::Object => {
626 user_wants_objects = true;
627 copy_if_one_unit(OutputType::Object, true);
630 OutputType::Metadata |
632 OutputType::DepInfo => {}
636 // Clean up unwanted temporary files.
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).
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
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
664 let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
666 let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units() > 1;
668 let keep_numbered_objects = needs_crate_object ||
669 (user_wants_objects && sess.codegen_units() > 1);
671 for module in compiled_modules.modules.iter() {
672 if let Some(ref path) = module.object {
673 if !keep_numbered_objects {
678 if let Some(ref path) = module.bytecode {
679 if !keep_numbered_bitcode {
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 {
692 if let Some(ref allocator_module) = compiled_modules.allocator_module {
693 if let Some(ref path) = allocator_module.bytecode {
700 // We leave the following files around by default:
702 // - #crate#.crate.metadata.o
704 // These are used in linking steps and will be cleaned up afterward.
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());
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
721 CopyPostLtoArtifacts(CachedModuleCodegen),
722 /// Performs (Thin)LTO on the given module.
723 LTO(lto::LtoModuleCodegen<B>),
726 impl<B: WriteBackendMethods> WorkItem<B> {
727 pub fn module_kind(&self) -> ModuleKind {
729 WorkItem::Optimize(ref m) => m.kind,
730 WorkItem::CopyPostLtoArtifacts(_) |
731 WorkItem::LTO(_) => ModuleKind::Regular,
735 pub fn name(&self) -> String {
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()),
744 enum WorkItemResult<B: WriteBackendMethods> {
745 Compiled(CompiledModule),
746 NeedsFatLTO(FatLTOInput<B>),
747 NeedsThinLTO(String, B::ThinBuffer),
750 pub enum FatLTOInput<B: WriteBackendMethods> {
753 buffer: B::ModuleBuffer,
755 InMemory(ModuleCodegen<B::Module>),
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());
765 WorkItem::Optimize(module) => {
766 execute_optimize_work_item(cgcx, module, module_config)
768 WorkItem::CopyPostLtoArtifacts(module) => {
769 execute_copy_from_cache_work_item(cgcx, module, module_config)
771 WorkItem::LTO(module) => {
772 execute_lto_work_item(cgcx, module, module_config)
777 // Actual LTO type we end up chosing based on multiple factors.
778 enum ComputedLtoType {
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();
792 B::optimize(cgcx, &diag_handler, &module, module_config)?;
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).
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();
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;
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.
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;
822 // Metadata modules never participate in LTO regardless of the lto
824 let lto_type = if module.kind == ModuleKind::Metadata {
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,
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))
847 ComputedLtoType::No => {
848 let module = unsafe {
849 B::codegen(cgcx, &diag_handler, module, module_config)?
851 WorkItemResult::Compiled(module)
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 `{}`: {}",
862 WorkItemResult::NeedsThinLTO(name, thin_buffer)
864 ComputedLtoType::Fat => {
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 `{}`: {}",
873 WorkItemResult::NeedsFatLTO(FatLTOInput::Serialized { name, buffer })
875 None => WorkItemResult::NeedsFatLTO(FatLTOInput::InMemory(module)),
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
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,
897 object = Some(path.clone());
900 WorkProductFileKind::Bytecode => {
901 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode,
903 bytecode = Some(path.clone());
906 WorkProductFileKind::BytecodeCompressed => {
907 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode,
909 .with_extension(RLIB_BYTECODE_EXTENSION);
910 bytecode_compressed = Some(path.clone());
914 let source_file = in_incr_comp_dir(&incr_comp_session_dir,
916 debug!("copying pre-existing module `{}` from {:?} to {}",
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(),
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);
933 Ok(WorkItemResult::Compiled(CompiledModule {
935 kind: ModuleKind::Regular,
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();
950 let module = module.optimize(cgcx)?;
951 let module = B::codegen(cgcx, &diag_handler, module, module_config)?;
952 Ok(WorkItemResult::Compiled(module))
956 pub enum Message<B: WriteBackendMethods> {
957 Token(io::Result<Acquired>),
959 result: FatLTOInput<B>,
964 thin_buffer: B::ThinBuffer,
968 result: Result<CompiledModule, ()>,
972 llvm_work_item: WorkItem<B>,
975 AddImportOnlyModule {
976 module_data: SerializedModule<B::ModuleBuffer>,
977 work_product: WorkProduct,
986 code: Option<DiagnosticId>,
990 #[derive(PartialEq, Clone, Copy, Debug)]
991 enum MainThreadWorkerState {
997 fn start_executing_work<B: ExtraBackendMethods>(
1000 crate_info: &CrateInfo,
1001 shared_emitter: SharedEmitter,
1002 codegen_worker_send: Sender<Message<B>>,
1003 coordinator_receive: Receiver<Box<dyn Any + Send>>,
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;
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();
1018 let copy_symbols = |cnum| {
1019 let symbols = tcx.exported_symbols(cnum)
1021 .map(|&(s, lvl)| (s.symbol_name(tcx).to_string(), lvl))
1029 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1030 Some(Arc::new(exported_symbols))
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));
1037 Some(Arc::new(exported_symbols))
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");
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) {
1057 each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
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);
1064 let (name, mut cmd) = get_linker(sess, &linker, flavor);
1065 cmd.args(&sess.target.target.options.asm_args);
1066 Some(Arc::new(AssemblerCommand {
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
1079 tcx.backend_optimization_level(LOCAL_CRATE)
1081 let cgcx = CodegenContext::<B> {
1082 backend: backend.clone(),
1083 crate_types: sess.crate_types.borrow().clone(),
1084 each_linked_rlib_for_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(),
1093 plugin_passes: sess.plugin_llvm_passes.borrow().clone(),
1094 remark: sess.opts.cg.remark.clone(),
1096 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1097 cgu_reuse_tracker: sess.cgu_reuse_tracker.clone(),
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)),
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,
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.
1117 // There are a few environmental pre-conditions that shape how the system
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`.
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.
1143 // Work Processing Infrastructure
1144 // ==============================
1145 // The work processing infrastructure knows three major actors:
1147 // - the coordinator thread,
1148 // - the main thread, and
1149 // - LLVM worker threads
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.
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
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.
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.
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.
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).
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
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.
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.
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.
1234 // LTO and the coordinator thread
1235 // ------------------------------
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
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:
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() {
1259 let id = worker_id_counter;
1260 worker_id_counter += 1;
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;
1276 // This flag tracks whether all items have gone through codegens
1277 let mut codegen_done = false;
1279 // This is the queue of LLVM work items that still need processing.
1280 let mut work_items = Vec::<(WorkItem<B>, u64)>::new();
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();
1286 let mut main_thread_worker_state = MainThreadWorkerState::Idle;
1287 let mut running = 0;
1289 let mut llvm_start_time = None;
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
1296 while !codegen_done ||
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
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.
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")
1317 main_thread_worker_state = MainThreadWorkerState::Codegenning;
1319 // The queue is full enough to not let the worker
1320 // threads starve. Use the implicit Token to do some
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),
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);
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
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
1343 if work_items.len() == 0 &&
1345 main_thread_worker_state == MainThreadWorkerState::Idle {
1346 assert!(!started_lto);
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);
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();
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),
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);
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);
1388 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1391 MainThreadWorkerState::Codegenning => {
1392 bug!("codegen worker should not be codegenning after \
1393 codegen was already completed")
1395 MainThreadWorkerState::LLVMing => {
1396 // Already making good use of that token
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();
1406 maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1407 &mut llvm_start_time);
1409 let cgcx = CodegenContext {
1410 worker: get_worker_id(&mut free_worker_ids),
1414 spawn_work(cgcx, item);
1418 // Relinquish accidentally acquired extra tokens
1419 tokens.truncate(running);
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;
1433 free_worker_ids.push(worker_id);
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) => {
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;
1456 let msg = &format!("failed to acquire jobserver token: {}", e);
1457 shared_emitter.fatal(msg);
1458 // Exit the coordinator thread
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
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
1478 work_items.insert(insertion_index, (llvm_work_item, cost));
1480 if !cgcx.opts.debugging_opts.no_parallel_llvm {
1481 helper.request_token();
1483 assert!(!codegen_aborted);
1484 assert_eq!(main_thread_worker_state,
1485 MainThreadWorkerState::Codegenning);
1486 main_thread_worker_state = MainThreadWorkerState::Idle;
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;
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);
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);
1516 ModuleKind::Metadata => {
1517 assert!(compiled_metadata_module.is_none());
1518 compiled_metadata_module = Some(compiled_module);
1520 ModuleKind::Allocator => {
1521 assert!(compiled_allocator_module.is_none());
1522 compiled_allocator_module = Some(compiled_module);
1526 Message::NeedsFatLTO { result, worker_id } => {
1527 assert!(!started_lto);
1528 free_worker(worker_id);
1529 needs_fat_lto.push(result);
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));
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;
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");
1548 Message::CodegenItem => {
1549 bug!("the coordinator should not receive codegen requests")
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
1559 print_time_passes_entry(cgcx.time_passes,
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));
1569 Ok(CompiledModules {
1570 modules: compiled_modules,
1571 metadata_module: compiled_metadata_module,
1572 allocator_module: compiled_allocator_module,
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 {
1582 items_in_queue > 0 &&
1583 items_in_queue >= max_workers.saturating_sub(workers_running / 2)
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());
1598 pub const CODEGEN_WORKER_ID: usize = ::std::usize::MAX;
1600 fn spawn_work<B: ExtraBackendMethods>(
1601 cgcx: CodegenContext<B>,
1604 let depth = time_depth();
1606 thread::spawn(move || {
1607 set_time_depth(depth);
1609 // Set up a destructor which will fire off a message that we're done as
1611 struct Bomb<B: ExtraBackendMethods> {
1612 coordinator_send: Sender<Box<dyn Any + Send>>,
1613 result: Option<WorkItemResult<B>>,
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 }
1623 Some(WorkItemResult::NeedsFatLTO(m)) => {
1624 Message::NeedsFatLTO::<B> { result: m, worker_id }
1626 Some(WorkItemResult::NeedsThinLTO(name, thin_buffer)) => {
1627 Message::NeedsThinLTO::<B> { name, thin_buffer, worker_id }
1629 None => Message::Done::<B> { result: Err(()), worker_id }
1631 drop(self.coordinator_send.send(Box::new(msg)));
1635 let mut bomb = Bomb::<B> {
1636 coordinator_send: cgcx.coordinator_send.clone(),
1638 worker_id: cgcx.worker,
1641 // Execute the work itself, and if it finishes successfully then flag
1642 // ourselves as a success as well.
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.
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));
1658 pub fn run_assembler<B: ExtraBackendMethods>(
1659 cgcx: &CodegenContext<B>,
1664 let assembler = cgcx.assembler_cmd
1666 .expect("cgcx.assembler_cmd is missing?");
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);
1673 match cmd.output() {
1675 if !prog.status.success() {
1676 let mut note = prog.stderr.clone();
1677 note.extend_from_slice(&prog.stdout);
1679 handler.struct_err(&format!("linking with `{}` failed: {}",
1682 .note(&format!("{:?}", &cmd))
1683 .note(str::from_utf8(¬e[..]).unwrap())
1685 handler.abort_if_errors();
1689 handler.err(&format!("could not exec the linker `{}`: {}", pname.display(), e));
1690 handler.abort_if_errors();
1696 enum SharedEmitterMessage {
1697 Diagnostic(Diagnostic),
1698 InlineAsmError(u32, String),
1704 pub struct SharedEmitter {
1705 sender: Sender<SharedEmitterMessage>,
1708 pub struct SharedEmitterMain {
1709 receiver: Receiver<SharedEmitterMessage>,
1712 impl SharedEmitter {
1713 pub fn new() -> (SharedEmitter, SharedEmitterMain) {
1714 let (sender, receiver) = channel();
1716 (SharedEmitter { sender }, SharedEmitterMain { receiver })
1719 pub fn inline_asm_error(&self, cookie: u32, msg: String) {
1720 drop(self.sender.send(SharedEmitterMessage::InlineAsmError(cookie, msg)));
1723 pub fn fatal(&self, msg: &str) {
1724 drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1728 impl Emitter for SharedEmitter {
1729 fn emit_diagnostic(&mut self, db: &rustc_errors::Diagnostic) {
1730 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1732 code: db.code.clone(),
1735 for child in &db.children {
1736 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1737 msg: child.message(),
1742 drop(self.sender.send(SharedEmitterMessage::AbortIfErrors));
1746 impl SharedEmitterMain {
1747 pub fn check(&self, sess: &Session, blocking: bool) {
1749 let message = if blocking {
1750 match self.receiver.recv() {
1751 Ok(message) => Ok(message),
1755 match self.receiver.try_recv() {
1756 Ok(message) => Ok(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 {
1768 handler.emit_diagnostic(&d);
1769 handler.abort_if_errors_and_should_abort();
1771 Ok(SharedEmitterMessage::InlineAsmError(cookie, msg)) => {
1772 sess.span_err(ExpnId::from_u32(cookie).expn_data().call_site, &msg)
1774 Ok(SharedEmitterMessage::AbortIfErrors) => {
1775 sess.abort_if_errors();
1777 Ok(SharedEmitterMessage::Fatal(msg)) => {
1789 pub struct OngoingCodegen<B: ExtraBackendMethods> {
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>,
1804 impl<B: ExtraBackendMethods> OngoingCodegen<B> {
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,
1813 sess.abort_if_errors();
1814 panic!("expected abort due to worker thread errors")
1817 bug!("panic during codegen/LLVM phase");
1821 sess.cgu_reuse_tracker.check_expected_reuse(sess);
1823 sess.abort_if_errors();
1826 copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess,
1828 produce_final_output_artifacts(sess,
1830 &self.output_filenames);
1832 // FIXME: time_llvm_passes support - does this use a global context or
1834 if sess.codegen_units() == 1 && sess.time_llvm_passes() {
1835 self.backend.print_pass_timings()
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,
1846 modules: compiled_modules.modules,
1847 allocator_module: compiled_modules.allocator_module,
1848 metadata_module: compiled_modules.metadata_module,
1852 pub fn submit_pre_codegened_module_to_llvm(
1855 module: ModuleCodegen<B::Module>,
1857 self.wait_for_signal_to_codegen_item();
1858 self.check_for_errors(tcx.sess);
1860 // These are generally cheap and won't throw off scheduling.
1862 submit_codegened_module_to_llvm(&self.backend, &self.coordinator_send, module, cost);
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>)));
1871 /// Consumes this context indicating that codegen was entirely aborted, and
1872 /// we need to exit as quickly as possible.
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
1880 drop(self.coordinator_send.send(Box::new(Message::CodegenAborted::<B>)));
1881 drop(self.future.join());
1884 pub fn check_for_errors(&self, sess: &Session) {
1885 self.shared_emitter_main.check(sess, false);
1888 pub fn wait_for_signal_to_codegen_item(&self) {
1889 match self.codegen_worker_receive.recv() {
1890 Ok(Message::CodegenItem) => {
1893 Ok(_) => panic!("unexpected message"),
1895 // One of the LLVM threads must have panicked, fall through so
1896 // error handling can be reached.
1902 pub fn submit_codegened_module_to_llvm<B: ExtraBackendMethods>(
1904 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
1905 module: ModuleCodegen<B::Module>,
1908 let llvm_work_item = WorkItem::Optimize(module);
1909 drop(tx_to_llvm_workers.send(Box::new(Message::CodegenDone::<B> {
1915 pub fn submit_post_lto_module_to_llvm<B: ExtraBackendMethods>(
1917 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
1918 module: CachedModuleCodegen,
1920 let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
1921 drop(tx_to_llvm_workers.send(Box::new(Message::CodegenDone::<B> {
1927 pub fn submit_pre_lto_module_to_llvm<B: ExtraBackendMethods>(
1930 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
1931 module: CachedModuleCodegen,
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)
1940 memmap::Mmap::map(&file).unwrap_or_else(|e| {
1941 panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
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,
1951 pub fn pre_lto_bitcode_filename(module_name: &str) -> String {
1952 format!("{}.{}", module_name, PRE_LTO_BC_EXT)
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));
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()