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, Sanitizer, Lto};
16 use rustc::session::Session;
17 use rustc::util::nodemap::FxHashMap;
18 use rustc::hir::def_id::{CrateNum, LOCAL_CRATE};
19 use rustc::ty::TyCtxt;
20 use rustc::util::common::{time_depth, set_time_depth, print_time_passes_entry};
21 use rustc::util::profiling::{ProfileCategory, SelfProfiler};
22 use rustc_fs_util::link_or_copy;
23 use rustc_data_structures::svh::Svh;
24 use rustc_errors::{Handler, Level, DiagnosticBuilder, FatalError, DiagnosticId};
25 use rustc_errors::emitter::{Emitter};
26 use rustc_target::spec::MergeFunctions;
28 use syntax::ext::hygiene::Mark;
29 use syntax_pos::MultiSpan;
30 use syntax_pos::symbol::Symbol;
31 use jobserver::{Client, Acquired};
32 use parking_lot::Mutex as PlMutex;
39 use std::path::{Path, PathBuf};
42 use std::sync::mpsc::{channel, Sender, Receiver};
43 use std::time::Instant;
46 const PRE_LTO_BC_EXT: &str = "pre-lto.bc";
48 /// Module-specific configuration for `optimize_and_codegen`.
49 pub struct ModuleConfig {
50 /// Names of additional optimization passes to run.
51 pub passes: Vec<String>,
52 /// Some(level) to optimize at a certain level, or None to run
53 /// absolutely no optimizations (used for the metadata module).
54 pub opt_level: Option<config::OptLevel>,
56 /// Some(level) to optimize binary size, or None to not affect program size.
57 pub opt_size: Option<config::OptLevel>,
59 pub pgo_gen: Option<String>,
62 // Flags indicating which outputs to produce.
63 pub emit_pre_lto_bc: bool,
64 pub emit_no_opt_bc: bool,
66 pub emit_bc_compressed: bool,
67 pub emit_lto_bc: bool,
71 // Miscellaneous flags. These are mostly copied from command-line
73 pub verify_llvm_ir: bool,
74 pub no_prepopulate_passes: bool,
75 pub no_builtins: bool,
76 pub time_passes: bool,
77 pub vectorize_loop: bool,
78 pub vectorize_slp: bool,
79 pub merge_functions: bool,
80 pub inline_threshold: Option<usize>,
81 // Instead of creating an object file by doing LLVM codegen, just
82 // make the object file bitcode. Provides easy compatibility with
83 // emscripten's ecc compiler, when used as the linker.
84 pub obj_is_bitcode: bool,
85 pub no_integrated_as: bool,
86 pub embed_bitcode: bool,
87 pub embed_bitcode_marker: bool,
91 fn new(passes: Vec<String>) -> ModuleConfig {
98 pgo_use: String::new(),
100 emit_no_opt_bc: false,
101 emit_pre_lto_bc: false,
103 emit_bc_compressed: false,
108 obj_is_bitcode: false,
109 embed_bitcode: false,
110 embed_bitcode_marker: false,
111 no_integrated_as: false,
113 verify_llvm_ir: false,
114 no_prepopulate_passes: false,
117 vectorize_loop: false,
118 vectorize_slp: false,
119 merge_functions: false,
120 inline_threshold: None
124 fn set_flags(&mut self, sess: &Session, no_builtins: bool) {
125 self.verify_llvm_ir = sess.verify_llvm_ir();
126 self.no_prepopulate_passes = sess.opts.cg.no_prepopulate_passes;
127 self.no_builtins = no_builtins || sess.target.target.options.no_builtins;
128 self.time_passes = sess.time_passes();
129 self.inline_threshold = sess.opts.cg.inline_threshold;
130 self.obj_is_bitcode = sess.target.target.options.obj_is_bitcode ||
131 sess.opts.cg.linker_plugin_lto.enabled();
132 let embed_bitcode = sess.target.target.options.embed_bitcode ||
133 sess.opts.debugging_opts.embed_bitcode;
135 match sess.opts.optimize {
136 config::OptLevel::No |
137 config::OptLevel::Less => {
138 self.embed_bitcode_marker = embed_bitcode;
140 _ => self.embed_bitcode = embed_bitcode,
144 // Copy what clang does by turning on loop vectorization at O2 and
145 // slp vectorization at O3. Otherwise configure other optimization aspects
146 // of this pass manager builder.
147 // Turn off vectorization for emscripten, as it's not very well supported.
148 self.vectorize_loop = !sess.opts.cg.no_vectorize_loops &&
149 (sess.opts.optimize == config::OptLevel::Default ||
150 sess.opts.optimize == config::OptLevel::Aggressive) &&
151 !sess.target.target.options.is_like_emscripten;
153 self.vectorize_slp = !sess.opts.cg.no_vectorize_slp &&
154 sess.opts.optimize == config::OptLevel::Aggressive &&
155 !sess.target.target.options.is_like_emscripten;
157 // Some targets (namely, NVPTX) interact badly with the MergeFunctions
158 // pass. This is because MergeFunctions can generate new function calls
159 // which may interfere with the target calling convention; e.g. for the
160 // NVPTX target, PTX kernels should not call other PTX kernels.
161 // MergeFunctions can also be configured to generate aliases instead,
162 // but aliases are not supported by some backends (again, NVPTX).
163 // Therefore, allow targets to opt out of the MergeFunctions pass,
164 // but otherwise keep the pass enabled (at O2 and O3) since it can be
165 // useful for reducing code size.
166 self.merge_functions = match sess.opts.debugging_opts.merge_functions
167 .unwrap_or(sess.target.target.options.merge_functions) {
168 MergeFunctions::Disabled => false,
169 MergeFunctions::Trampolines |
170 MergeFunctions::Aliases => {
171 sess.opts.optimize == config::OptLevel::Default ||
172 sess.opts.optimize == config::OptLevel::Aggressive
177 pub fn bitcode_needed(&self) -> bool {
178 self.emit_bc || self.obj_is_bitcode
179 || self.emit_bc_compressed || self.embed_bitcode
183 /// Assembler name and command used by codegen when no_integrated_as is enabled
184 pub struct AssemblerCommand {
189 // HACK(eddyb) work around `#[derive]` producing wrong bounds for `Clone`.
190 pub struct TargetMachineFactory<B: WriteBackendMethods>(
191 pub Arc<dyn Fn() -> Result<B::TargetMachine, String> + Send + Sync>,
194 impl<B: WriteBackendMethods> Clone for TargetMachineFactory<B> {
195 fn clone(&self) -> Self {
196 TargetMachineFactory(self.0.clone())
200 pub struct ProfileGenericActivityTimer {
201 profiler: Option<Arc<PlMutex<SelfProfiler>>>,
202 category: ProfileCategory,
203 label: Cow<'static, str>,
206 impl ProfileGenericActivityTimer {
208 profiler: Option<Arc<PlMutex<SelfProfiler>>>,
209 category: ProfileCategory,
210 label: Cow<'static, str>,
211 ) -> ProfileGenericActivityTimer {
212 if let Some(profiler) = &profiler {
213 let mut p = profiler.lock();
214 p.start_activity(category, label.clone());
217 ProfileGenericActivityTimer {
225 impl Drop for ProfileGenericActivityTimer {
227 if let Some(profiler) = &self.profiler {
228 let mut p = profiler.lock();
229 p.end_activity(self.category, self.label.clone());
234 /// Additional resources used by optimize_and_codegen (not module specific)
236 pub struct CodegenContext<B: WriteBackendMethods> {
237 // Resources needed when running LTO
239 pub time_passes: bool,
240 pub profiler: Option<Arc<PlMutex<SelfProfiler>>>,
242 pub no_landing_pads: bool,
243 pub save_temps: bool,
244 pub fewer_names: bool,
245 pub exported_symbols: Option<Arc<ExportedSymbols>>,
246 pub opts: Arc<config::Options>,
247 pub crate_types: Vec<config::CrateType>,
248 pub each_linked_rlib_for_lto: Vec<(CrateNum, PathBuf)>,
249 pub output_filenames: Arc<OutputFilenames>,
250 pub regular_module_config: Arc<ModuleConfig>,
251 pub metadata_module_config: Arc<ModuleConfig>,
252 pub allocator_module_config: Arc<ModuleConfig>,
253 pub tm_factory: TargetMachineFactory<B>,
254 pub msvc_imps_needed: bool,
255 pub target_pointer_width: String,
256 pub debuginfo: config::DebugInfo,
258 // Number of cgus excluding the allocator/metadata modules
259 pub total_cgus: usize,
260 // Handler to use for diagnostics produced during codegen.
261 pub diag_emitter: SharedEmitter,
262 // LLVM passes added by plugins.
263 pub plugin_passes: Vec<String>,
264 // LLVM optimizations for which we want to print remarks.
266 // Worker thread number
268 // The incremental compilation session directory, or None if we are not
269 // compiling incrementally
270 pub incr_comp_session_dir: Option<PathBuf>,
271 // Used to update CGU re-use information during the thinlto phase.
272 pub cgu_reuse_tracker: CguReuseTracker,
273 // Channel back to the main control thread to send messages to
274 pub coordinator_send: Sender<Box<dyn Any + Send>>,
275 // The assembler command if no_integrated_as option is enabled, None otherwise
276 pub assembler_cmd: Option<Arc<AssemblerCommand>>
279 impl<B: WriteBackendMethods> CodegenContext<B> {
280 pub fn create_diag_handler(&self) -> Handler {
281 Handler::with_emitter(true, None, Box::new(self.diag_emitter.clone()))
284 pub fn config(&self, kind: ModuleKind) -> &ModuleConfig {
286 ModuleKind::Regular => &self.regular_module_config,
287 ModuleKind::Metadata => &self.metadata_module_config,
288 ModuleKind::Allocator => &self.allocator_module_config,
294 fn profiler_active<F: FnOnce(&mut SelfProfiler) -> ()>(&self, f: F) {
295 match &self.profiler {
296 None => bug!("profiler_active() called but there was no profiler active"),
298 let mut p = profiler.lock();
306 pub fn profile<F: FnOnce(&mut SelfProfiler) -> ()>(&self, f: F) {
307 if unlikely!(self.profiler.is_some()) {
308 self.profiler_active(f)
312 pub fn profile_activity(
314 category: ProfileCategory,
315 label: impl Into<Cow<'static, str>>,
316 ) -> ProfileGenericActivityTimer {
317 ProfileGenericActivityTimer::start(self.profiler.clone(), category, label.into())
321 fn generate_lto_work<B: ExtraBackendMethods>(
322 cgcx: &CodegenContext<B>,
323 needs_fat_lto: Vec<FatLTOInput<B>>,
324 needs_thin_lto: Vec<(String, B::ThinBuffer)>,
325 import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>
326 ) -> Vec<(WorkItem<B>, u64)> {
327 cgcx.profile(|p| p.start_activity(ProfileCategory::Linking, "codegen_run_lto"));
329 let (lto_modules, copy_jobs) = if !needs_fat_lto.is_empty() {
330 assert!(needs_thin_lto.is_empty());
331 let lto_module = B::run_fat_lto(
336 .unwrap_or_else(|e| e.raise());
337 (vec![lto_module], vec![])
339 assert!(needs_fat_lto.is_empty());
340 B::run_thin_lto(cgcx, needs_thin_lto, import_only_modules)
341 .unwrap_or_else(|e| e.raise())
344 let result = lto_modules.into_iter().map(|module| {
345 let cost = module.cost();
346 (WorkItem::LTO(module), cost)
347 }).chain(copy_jobs.into_iter().map(|wp| {
348 (WorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
349 name: wp.cgu_name.clone(),
354 cgcx.profile(|p| p.end_activity(ProfileCategory::Linking, "codegen_run_lto"));
359 pub struct CompiledModules {
360 pub modules: Vec<CompiledModule>,
361 pub metadata_module: CompiledModule,
362 pub allocator_module: Option<CompiledModule>,
365 fn need_crate_bitcode_for_rlib(sess: &Session) -> bool {
366 sess.crate_types.borrow().contains(&config::CrateType::Rlib) &&
367 sess.opts.output_types.contains_key(&OutputType::Exe)
370 fn need_pre_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
371 if sess.opts.incremental.is_none() {
379 Lto::ThinLocal => true,
383 pub fn start_async_codegen<B: ExtraBackendMethods>(
385 tcx: TyCtxt<'_, '_, '_>,
386 metadata: EncodedMetadata,
387 coordinator_receive: Receiver<Box<dyn Any + Send>>,
389 ) -> OngoingCodegen<B> {
391 let crate_name = tcx.crate_name(LOCAL_CRATE);
392 let crate_hash = tcx.crate_hash(LOCAL_CRATE);
393 let no_builtins = attr::contains_name(&tcx.hir().krate().attrs, "no_builtins");
394 let subsystem = attr::first_attr_value_str_by_name(&tcx.hir().krate().attrs,
395 "windows_subsystem");
396 let windows_subsystem = subsystem.map(|subsystem| {
397 if subsystem != "windows" && subsystem != "console" {
398 tcx.sess.fatal(&format!("invalid windows subsystem `{}`, only \
399 `windows` and `console` are allowed",
402 subsystem.to_string()
405 let linker_info = LinkerInfo::new(tcx);
406 let crate_info = CrateInfo::new(tcx);
408 // Figure out what we actually need to build.
409 let mut modules_config = ModuleConfig::new(sess.opts.cg.passes.clone());
410 let mut metadata_config = ModuleConfig::new(vec![]);
411 let mut allocator_config = ModuleConfig::new(vec![]);
413 if let Some(ref sanitizer) = sess.opts.debugging_opts.sanitizer {
415 Sanitizer::Address => {
416 modules_config.passes.push("asan".to_owned());
417 modules_config.passes.push("asan-module".to_owned());
419 Sanitizer::Memory => {
420 modules_config.passes.push("msan".to_owned())
422 Sanitizer::Thread => {
423 modules_config.passes.push("tsan".to_owned())
429 if sess.opts.debugging_opts.profile {
430 modules_config.passes.push("insert-gcov-profiling".to_owned())
433 modules_config.pgo_gen = sess.opts.debugging_opts.pgo_gen.clone();
434 modules_config.pgo_use = sess.opts.debugging_opts.pgo_use.clone();
436 modules_config.opt_level = Some(sess.opts.optimize);
437 modules_config.opt_size = Some(sess.opts.optimize);
439 // Save all versions of the bytecode if we're saving our temporaries.
440 if sess.opts.cg.save_temps {
441 modules_config.emit_no_opt_bc = true;
442 modules_config.emit_pre_lto_bc = true;
443 modules_config.emit_bc = true;
444 modules_config.emit_lto_bc = true;
445 metadata_config.emit_bc = true;
446 allocator_config.emit_bc = true;
449 // Emit compressed bitcode files for the crate if we're emitting an rlib.
450 // Whenever an rlib is created, the bitcode is inserted into the archive in
451 // order to allow LTO against it.
452 if need_crate_bitcode_for_rlib(sess) {
453 modules_config.emit_bc_compressed = true;
454 allocator_config.emit_bc_compressed = true;
457 modules_config.emit_pre_lto_bc =
458 need_pre_lto_bitcode_for_incr_comp(sess);
460 modules_config.no_integrated_as = tcx.sess.opts.cg.no_integrated_as ||
461 tcx.sess.target.target.options.no_integrated_as;
463 for output_type in sess.opts.output_types.keys() {
465 OutputType::Bitcode => { modules_config.emit_bc = true; }
466 OutputType::LlvmAssembly => { modules_config.emit_ir = true; }
467 OutputType::Assembly => {
468 modules_config.emit_asm = true;
469 // If we're not using the LLVM assembler, this function
470 // could be invoked specially with output_type_assembly, so
471 // in this case we still want the metadata object file.
472 if !sess.opts.output_types.contains_key(&OutputType::Assembly) {
473 metadata_config.emit_obj = true;
474 allocator_config.emit_obj = true;
477 OutputType::Object => { modules_config.emit_obj = true; }
478 OutputType::Metadata => { metadata_config.emit_obj = true; }
480 modules_config.emit_obj = true;
481 metadata_config.emit_obj = true;
482 allocator_config.emit_obj = true;
484 OutputType::Mir => {}
485 OutputType::DepInfo => {}
489 modules_config.set_flags(sess, no_builtins);
490 metadata_config.set_flags(sess, no_builtins);
491 allocator_config.set_flags(sess, no_builtins);
493 // Exclude metadata and allocator modules from time_passes output, since
494 // they throw off the "LLVM passes" measurement.
495 metadata_config.time_passes = false;
496 allocator_config.time_passes = false;
498 let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
499 let (codegen_worker_send, codegen_worker_receive) = channel();
501 let coordinator_thread = start_executing_work(backend.clone(),
508 sess.jobserver.clone(),
509 Arc::new(modules_config),
510 Arc::new(metadata_config),
511 Arc::new(allocator_config));
522 coordinator_send: tcx.tx_to_llvm_workers.lock().clone(),
523 codegen_worker_receive,
525 future: coordinator_thread,
526 output_filenames: tcx.output_filenames(LOCAL_CRATE),
530 fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
532 compiled_modules: &CompiledModules,
533 ) -> FxHashMap<WorkProductId, WorkProduct> {
534 let mut work_products = FxHashMap::default();
536 if sess.opts.incremental.is_none() {
537 return work_products;
540 for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
541 let mut files = vec![];
543 if let Some(ref path) = module.object {
544 files.push((WorkProductFileKind::Object, path.clone()));
546 if let Some(ref path) = module.bytecode {
547 files.push((WorkProductFileKind::Bytecode, path.clone()));
549 if let Some(ref path) = module.bytecode_compressed {
550 files.push((WorkProductFileKind::BytecodeCompressed, path.clone()));
553 if let Some((id, product)) =
554 copy_cgu_workproducts_to_incr_comp_cache_dir(sess, &module.name, &files) {
555 work_products.insert(id, product);
562 fn produce_final_output_artifacts(sess: &Session,
563 compiled_modules: &CompiledModules,
564 crate_output: &OutputFilenames) {
565 let mut user_wants_bitcode = false;
566 let mut user_wants_objects = false;
568 // Produce final compile outputs.
569 let copy_gracefully = |from: &Path, to: &Path| {
570 if let Err(e) = fs::copy(from, to) {
571 sess.err(&format!("could not copy {:?} to {:?}: {}", from, to, e));
575 let copy_if_one_unit = |output_type: OutputType,
576 keep_numbered: bool| {
577 if compiled_modules.modules.len() == 1 {
578 // 1) Only one codegen unit. In this case it's no difficulty
579 // to copy `foo.0.x` to `foo.x`.
580 let module_name = Some(&compiled_modules.modules[0].name[..]);
581 let path = crate_output.temp_path(output_type, module_name);
582 copy_gracefully(&path,
583 &crate_output.path(output_type));
584 if !sess.opts.cg.save_temps && !keep_numbered {
585 // The user just wants `foo.x`, not `foo.#module-name#.x`.
589 let ext = crate_output.temp_path(output_type, None)
596 if crate_output.outputs.contains_key(&output_type) {
597 // 2) Multiple codegen units, with `--emit foo=some_name`. We have
598 // no good solution for this case, so warn the user.
599 sess.warn(&format!("ignoring emit path because multiple .{} files \
600 were produced", ext));
601 } else if crate_output.single_output_file.is_some() {
602 // 3) Multiple codegen units, with `-o some_name`. We have
603 // no good solution for this case, so warn the user.
604 sess.warn(&format!("ignoring -o because multiple .{} files \
605 were produced", ext));
607 // 4) Multiple codegen units, but no explicit name. We
608 // just leave the `foo.0.x` files in place.
609 // (We don't have to do any work in this case.)
614 // Flag to indicate whether the user explicitly requested bitcode.
615 // Otherwise, we produced it only as a temporary output, and will need
617 for output_type in crate_output.outputs.keys() {
619 OutputType::Bitcode => {
620 user_wants_bitcode = true;
621 // Copy to .bc, but always keep the .0.bc. There is a later
622 // check to figure out if we should delete .0.bc files, or keep
623 // them for making an rlib.
624 copy_if_one_unit(OutputType::Bitcode, true);
626 OutputType::LlvmAssembly => {
627 copy_if_one_unit(OutputType::LlvmAssembly, false);
629 OutputType::Assembly => {
630 copy_if_one_unit(OutputType::Assembly, false);
632 OutputType::Object => {
633 user_wants_objects = true;
634 copy_if_one_unit(OutputType::Object, true);
637 OutputType::Metadata |
639 OutputType::DepInfo => {}
643 // Clean up unwanted temporary files.
645 // We create the following files by default:
646 // - #crate#.#module-name#.bc
647 // - #crate#.#module-name#.o
648 // - #crate#.crate.metadata.bc
649 // - #crate#.crate.metadata.o
650 // - #crate#.o (linked from crate.##.o)
651 // - #crate#.bc (copied from crate.##.bc)
652 // We may create additional files if requested by the user (through
653 // `-C save-temps` or `--emit=` flags).
655 if !sess.opts.cg.save_temps {
656 // Remove the temporary .#module-name#.o objects. If the user didn't
657 // explicitly request bitcode (with --emit=bc), and the bitcode is not
658 // needed for building an rlib, then we must remove .#module-name#.bc as
661 // Specific rules for keeping .#module-name#.bc:
662 // - If the user requested bitcode (`user_wants_bitcode`), and
663 // codegen_units > 1, then keep it.
664 // - If the user requested bitcode but codegen_units == 1, then we
665 // can toss .#module-name#.bc because we copied it to .bc earlier.
666 // - If we're not building an rlib and the user didn't request
667 // bitcode, then delete .#module-name#.bc.
668 // If you change how this works, also update back::link::link_rlib,
669 // where .#module-name#.bc files are (maybe) deleted after making an
671 let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
673 let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units() > 1;
675 let keep_numbered_objects = needs_crate_object ||
676 (user_wants_objects && sess.codegen_units() > 1);
678 for module in compiled_modules.modules.iter() {
679 if let Some(ref path) = module.object {
680 if !keep_numbered_objects {
685 if let Some(ref path) = module.bytecode {
686 if !keep_numbered_bitcode {
692 if !user_wants_bitcode {
693 if let Some(ref path) = compiled_modules.metadata_module.bytecode {
697 if let Some(ref allocator_module) = compiled_modules.allocator_module {
698 if let Some(ref path) = allocator_module.bytecode {
705 // We leave the following files around by default:
707 // - #crate#.crate.metadata.o
709 // These are used in linking steps and will be cleaned up afterward.
712 pub fn dump_incremental_data(_codegen_results: &CodegenResults) {
713 // FIXME(mw): This does not work at the moment because the situation has
714 // become more complicated due to incremental LTO. Now a CGU
715 // can have more than two caching states.
716 // println!("[incremental] Re-using {} out of {} modules",
717 // codegen_results.modules.iter().filter(|m| m.pre_existing).count(),
718 // codegen_results.modules.len());
721 pub enum WorkItem<B: WriteBackendMethods> {
722 /// Optimize a newly codegened, totally unoptimized module.
723 Optimize(ModuleCodegen<B::Module>),
724 /// Copy the post-LTO artifacts from the incremental cache to the output
726 CopyPostLtoArtifacts(CachedModuleCodegen),
727 /// Performs (Thin)LTO on the given module.
728 LTO(lto::LtoModuleCodegen<B>),
731 impl<B: WriteBackendMethods> WorkItem<B> {
732 pub fn module_kind(&self) -> ModuleKind {
734 WorkItem::Optimize(ref m) => m.kind,
735 WorkItem::CopyPostLtoArtifacts(_) |
736 WorkItem::LTO(_) => ModuleKind::Regular,
740 pub fn name(&self) -> String {
742 WorkItem::Optimize(ref m) => format!("optimize: {}", m.name),
743 WorkItem::CopyPostLtoArtifacts(ref m) => format!("copy post LTO artifacts: {}", m.name),
744 WorkItem::LTO(ref m) => format!("lto: {}", m.name()),
749 enum WorkItemResult<B: WriteBackendMethods> {
750 Compiled(CompiledModule),
751 NeedsFatLTO(FatLTOInput<B>),
752 NeedsThinLTO(String, B::ThinBuffer),
755 pub enum FatLTOInput<B: WriteBackendMethods> {
758 buffer: B::ModuleBuffer,
760 InMemory(ModuleCodegen<B::Module>),
763 fn execute_work_item<B: ExtraBackendMethods>(
764 cgcx: &CodegenContext<B>,
765 work_item: WorkItem<B>,
766 ) -> Result<WorkItemResult<B>, FatalError> {
767 let module_config = cgcx.config(work_item.module_kind());
770 WorkItem::Optimize(module) => {
771 execute_optimize_work_item(cgcx, module, module_config)
773 WorkItem::CopyPostLtoArtifacts(module) => {
774 execute_copy_from_cache_work_item(cgcx, module, module_config)
776 WorkItem::LTO(module) => {
777 execute_lto_work_item(cgcx, module, module_config)
782 // Actual LTO type we end up chosing based on multiple factors.
783 enum ComputedLtoType {
789 fn execute_optimize_work_item<B: ExtraBackendMethods>(
790 cgcx: &CodegenContext<B>,
791 module: ModuleCodegen<B::Module>,
792 module_config: &ModuleConfig,
793 ) -> Result<WorkItemResult<B>, FatalError> {
794 let diag_handler = cgcx.create_diag_handler();
797 B::optimize(cgcx, &diag_handler, &module, module_config)?;
800 // After we've done the initial round of optimizations we need to
801 // decide whether to synchronously codegen this module or ship it
802 // back to the coordinator thread for further LTO processing (which
803 // has to wait for all the initial modules to be optimized).
805 // If the linker does LTO, we don't have to do it. Note that we
806 // keep doing full LTO, if it is requested, as not to break the
807 // assumption that the output will be a single module.
808 let linker_does_lto = cgcx.opts.cg.linker_plugin_lto.enabled();
810 // When we're automatically doing ThinLTO for multi-codegen-unit
811 // builds we don't actually want to LTO the allocator modules if
812 // it shows up. This is due to various linker shenanigans that
813 // we'll encounter later.
814 let is_allocator = module.kind == ModuleKind::Allocator;
816 // We ignore a request for full crate grath LTO if the cate type
817 // is only an rlib, as there is no full crate graph to process,
818 // that'll happen later.
820 // This use case currently comes up primarily for targets that
821 // require LTO so the request for LTO is always unconditionally
822 // passed down to the backend, but we don't actually want to do
823 // anything about it yet until we've got a final product.
824 let is_rlib = cgcx.crate_types.len() == 1
825 && cgcx.crate_types[0] == config::CrateType::Rlib;
827 // Metadata modules never participate in LTO regardless of the lto
829 let lto_type = if module.kind == ModuleKind::Metadata {
833 Lto::ThinLocal if !linker_does_lto && !is_allocator
834 => ComputedLtoType::Thin,
835 Lto::Thin if !linker_does_lto && !is_rlib
836 => ComputedLtoType::Thin,
837 Lto::Fat if !is_rlib => ComputedLtoType::Fat,
838 _ => ComputedLtoType::No,
842 // If we're doing some form of incremental LTO then we need to be sure to
843 // save our module to disk first.
844 let bitcode = if cgcx.config(module.kind).emit_pre_lto_bc {
845 let filename = pre_lto_bitcode_filename(&module.name);
846 cgcx.incr_comp_session_dir.as_ref().map(|path| path.join(&filename))
852 ComputedLtoType::No => {
853 let module = unsafe {
854 B::codegen(cgcx, &diag_handler, module, module_config)?
856 WorkItemResult::Compiled(module)
858 ComputedLtoType::Thin => {
859 let (name, thin_buffer) = B::prepare_thin(module);
860 if let Some(path) = bitcode {
861 fs::write(&path, thin_buffer.data()).unwrap_or_else(|e| {
862 panic!("Error writing pre-lto-bitcode file `{}`: {}",
867 WorkItemResult::NeedsThinLTO(name, thin_buffer)
869 ComputedLtoType::Fat => {
872 let (name, buffer) = B::serialize_module(module);
873 fs::write(&path, buffer.data()).unwrap_or_else(|e| {
874 panic!("Error writing pre-lto-bitcode file `{}`: {}",
878 WorkItemResult::NeedsFatLTO(FatLTOInput::Serialized { name, buffer })
880 None => WorkItemResult::NeedsFatLTO(FatLTOInput::InMemory(module)),
886 fn execute_copy_from_cache_work_item<B: ExtraBackendMethods>(
887 cgcx: &CodegenContext<B>,
888 module: CachedModuleCodegen,
889 module_config: &ModuleConfig,
890 ) -> Result<WorkItemResult<B>, FatalError> {
891 let incr_comp_session_dir = cgcx.incr_comp_session_dir
894 let mut object = None;
895 let mut bytecode = None;
896 let mut bytecode_compressed = None;
897 for (kind, saved_file) in &module.source.saved_files {
898 let obj_out = match kind {
899 WorkProductFileKind::Object => {
900 let path = cgcx.output_filenames.temp_path(OutputType::Object,
902 object = Some(path.clone());
905 WorkProductFileKind::Bytecode => {
906 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode,
908 bytecode = Some(path.clone());
911 WorkProductFileKind::BytecodeCompressed => {
912 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode,
914 .with_extension(RLIB_BYTECODE_EXTENSION);
915 bytecode_compressed = Some(path.clone());
919 let source_file = in_incr_comp_dir(&incr_comp_session_dir,
921 debug!("copying pre-existing module `{}` from {:?} to {}",
925 if let Err(err) = link_or_copy(&source_file, &obj_out) {
926 let diag_handler = cgcx.create_diag_handler();
927 diag_handler.err(&format!("unable to copy {} to {}: {}",
928 source_file.display(),
934 assert_eq!(object.is_some(), module_config.emit_obj);
935 assert_eq!(bytecode.is_some(), module_config.emit_bc);
936 assert_eq!(bytecode_compressed.is_some(), module_config.emit_bc_compressed);
938 Ok(WorkItemResult::Compiled(CompiledModule {
940 kind: ModuleKind::Regular,
947 fn execute_lto_work_item<B: ExtraBackendMethods>(
948 cgcx: &CodegenContext<B>,
949 mut module: lto::LtoModuleCodegen<B>,
950 module_config: &ModuleConfig,
951 ) -> Result<WorkItemResult<B>, FatalError> {
952 let diag_handler = cgcx.create_diag_handler();
955 let module = module.optimize(cgcx)?;
956 let module = B::codegen(cgcx, &diag_handler, module, module_config)?;
957 Ok(WorkItemResult::Compiled(module))
961 pub enum Message<B: WriteBackendMethods> {
962 Token(io::Result<Acquired>),
964 result: FatLTOInput<B>,
969 thin_buffer: B::ThinBuffer,
973 result: Result<CompiledModule, ()>,
977 llvm_work_item: WorkItem<B>,
980 AddImportOnlyModule {
981 module_data: SerializedModule<B::ModuleBuffer>,
982 work_product: WorkProduct,
991 code: Option<DiagnosticId>,
995 #[derive(PartialEq, Clone, Copy, Debug)]
996 enum MainThreadWorkerState {
1002 fn start_executing_work<B: ExtraBackendMethods>(
1004 tcx: TyCtxt<'_, '_, '_>,
1005 crate_info: &CrateInfo,
1006 shared_emitter: SharedEmitter,
1007 codegen_worker_send: Sender<Message<B>>,
1008 coordinator_receive: Receiver<Box<dyn Any + Send>>,
1011 modules_config: Arc<ModuleConfig>,
1012 metadata_config: Arc<ModuleConfig>,
1013 allocator_config: Arc<ModuleConfig>
1014 ) -> thread::JoinHandle<Result<CompiledModules, ()>> {
1015 let coordinator_send = tcx.tx_to_llvm_workers.lock().clone();
1016 let sess = tcx.sess;
1018 // Compute the set of symbols we need to retain when doing LTO (if we need to)
1019 let exported_symbols = {
1020 let mut exported_symbols = FxHashMap::default();
1022 let copy_symbols = |cnum| {
1023 let symbols = tcx.exported_symbols(cnum)
1025 .map(|&(s, lvl)| (s.symbol_name(tcx).to_string(), lvl))
1033 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1034 Some(Arc::new(exported_symbols))
1036 Lto::Fat | Lto::Thin => {
1037 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1038 for &cnum in tcx.crates().iter() {
1039 exported_symbols.insert(cnum, copy_symbols(cnum));
1041 Some(Arc::new(exported_symbols))
1046 // First up, convert our jobserver into a helper thread so we can use normal
1047 // mpsc channels to manage our messages and such.
1048 // After we've requested tokens then we'll, when we can,
1049 // get tokens on `coordinator_receive` which will
1050 // get managed in the main loop below.
1051 let coordinator_send2 = coordinator_send.clone();
1052 let helper = jobserver.into_helper_thread(move |token| {
1053 drop(coordinator_send2.send(Box::new(Message::Token::<B>(token))));
1054 }).expect("failed to spawn helper thread");
1056 let mut each_linked_rlib_for_lto = Vec::new();
1057 drop(link::each_linked_rlib(sess, crate_info, &mut |cnum, path| {
1058 if link::ignored_for_lto(sess, crate_info, cnum) {
1061 each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
1064 let assembler_cmd = if modules_config.no_integrated_as {
1065 // HACK: currently we use linker (gcc) as our assembler
1066 let (linker, flavor) = link::linker_and_flavor(sess);
1068 let (name, mut cmd) = get_linker(sess, &linker, flavor);
1069 cmd.args(&sess.target.target.options.asm_args);
1070 Some(Arc::new(AssemblerCommand {
1078 let ol = tcx.backend_optimization_level(LOCAL_CRATE);
1079 let cgcx = CodegenContext::<B> {
1080 backend: backend.clone(),
1081 crate_types: sess.crate_types.borrow().clone(),
1082 each_linked_rlib_for_lto,
1084 no_landing_pads: sess.no_landing_pads(),
1085 fewer_names: sess.fewer_names(),
1086 save_temps: sess.opts.cg.save_temps,
1087 opts: Arc::new(sess.opts.clone()),
1088 time_passes: sess.time_passes(),
1089 profiler: sess.self_profiling.clone(),
1091 plugin_passes: sess.plugin_llvm_passes.borrow().clone(),
1092 remark: sess.opts.cg.remark.clone(),
1094 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1095 cgu_reuse_tracker: sess.cgu_reuse_tracker.clone(),
1097 diag_emitter: shared_emitter.clone(),
1098 output_filenames: tcx.output_filenames(LOCAL_CRATE),
1099 regular_module_config: modules_config,
1100 metadata_module_config: metadata_config,
1101 allocator_module_config: allocator_config,
1102 tm_factory: TargetMachineFactory(backend.target_machine_factory(tcx.sess, ol, false)),
1104 msvc_imps_needed: msvc_imps_needed(tcx),
1105 target_pointer_width: tcx.sess.target.target.target_pointer_width.clone(),
1106 debuginfo: tcx.sess.opts.debuginfo,
1110 // This is the "main loop" of parallel work happening for parallel codegen.
1111 // It's here that we manage parallelism, schedule work, and work with
1112 // messages coming from clients.
1114 // There are a few environmental pre-conditions that shape how the system
1117 // - Error reporting only can happen on the main thread because that's the
1118 // only place where we have access to the compiler `Session`.
1119 // - LLVM work can be done on any thread.
1120 // - Codegen can only happen on the main thread.
1121 // - Each thread doing substantial work most be in possession of a `Token`
1122 // from the `Jobserver`.
1123 // - The compiler process always holds one `Token`. Any additional `Tokens`
1124 // have to be requested from the `Jobserver`.
1128 // The error reporting restriction is handled separately from the rest: We
1129 // set up a `SharedEmitter` the holds an open channel to the main thread.
1130 // When an error occurs on any thread, the shared emitter will send the
1131 // error message to the receiver main thread (`SharedEmitterMain`). The
1132 // main thread will periodically query this error message queue and emit
1133 // any error messages it has received. It might even abort compilation if
1134 // has received a fatal error. In this case we rely on all other threads
1135 // being torn down automatically with the main thread.
1136 // Since the main thread will often be busy doing codegen work, error
1137 // reporting will be somewhat delayed, since the message queue can only be
1138 // checked in between to work packages.
1140 // Work Processing Infrastructure
1141 // ==============================
1142 // The work processing infrastructure knows three major actors:
1144 // - the coordinator thread,
1145 // - the main thread, and
1146 // - LLVM worker threads
1148 // The coordinator thread is running a message loop. It instructs the main
1149 // thread about what work to do when, and it will spawn off LLVM worker
1150 // threads as open LLVM WorkItems become available.
1152 // The job of the main thread is to codegen CGUs into LLVM work package
1153 // (since the main thread is the only thread that can do this). The main
1154 // thread will block until it receives a message from the coordinator, upon
1155 // which it will codegen one CGU, send it to the coordinator and block
1156 // again. This way the coordinator can control what the main thread is
1159 // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1160 // available, it will spawn off a new LLVM worker thread and let it process
1161 // that a WorkItem. When a LLVM worker thread is done with its WorkItem,
1162 // it will just shut down, which also frees all resources associated with
1163 // the given LLVM module, and sends a message to the coordinator that the
1164 // has been completed.
1168 // The scheduler's goal is to minimize the time it takes to complete all
1169 // work there is, however, we also want to keep memory consumption low
1170 // if possible. These two goals are at odds with each other: If memory
1171 // consumption were not an issue, we could just let the main thread produce
1172 // LLVM WorkItems at full speed, assuring maximal utilization of
1173 // Tokens/LLVM worker threads. However, since codegen usual is faster
1174 // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1175 // WorkItem potentially holds on to a substantial amount of memory.
1177 // So the actual goal is to always produce just enough LLVM WorkItems as
1178 // not to starve our LLVM worker threads. That means, once we have enough
1179 // WorkItems in our queue, we can block the main thread, so it does not
1180 // produce more until we need them.
1182 // Doing LLVM Work on the Main Thread
1183 // ----------------------------------
1184 // Since the main thread owns the compiler processes implicit `Token`, it is
1185 // wasteful to keep it blocked without doing any work. Therefore, what we do
1186 // in this case is: We spawn off an additional LLVM worker thread that helps
1187 // reduce the queue. The work it is doing corresponds to the implicit
1188 // `Token`. The coordinator will mark the main thread as being busy with
1189 // LLVM work. (The actual work happens on another OS thread but we just care
1190 // about `Tokens`, not actual threads).
1192 // When any LLVM worker thread finishes while the main thread is marked as
1193 // "busy with LLVM work", we can do a little switcheroo: We give the Token
1194 // of the just finished thread to the LLVM worker thread that is working on
1195 // behalf of the main thread's implicit Token, thus freeing up the main
1196 // thread again. The coordinator can then again decide what the main thread
1197 // should do. This allows the coordinator to make decisions at more points
1200 // Striking a Balance between Throughput and Memory Consumption
1201 // ------------------------------------------------------------
1202 // Since our two goals, (1) use as many Tokens as possible and (2) keep
1203 // memory consumption as low as possible, are in conflict with each other,
1204 // we have to find a trade off between them. Right now, the goal is to keep
1205 // all workers busy, which means that no worker should find the queue empty
1206 // when it is ready to start.
1207 // How do we do achieve this? Good question :) We actually never know how
1208 // many `Tokens` are potentially available so it's hard to say how much to
1209 // fill up the queue before switching the main thread to LLVM work. Also we
1210 // currently don't have a means to estimate how long a running LLVM worker
1211 // will still be busy with it's current WorkItem. However, we know the
1212 // maximal count of available Tokens that makes sense (=the number of CPU
1213 // cores), so we can take a conservative guess. The heuristic we use here
1214 // is implemented in the `queue_full_enough()` function.
1216 // Some Background on Jobservers
1217 // -----------------------------
1218 // It's worth also touching on the management of parallelism here. We don't
1219 // want to just spawn a thread per work item because while that's optimal
1220 // parallelism it may overload a system with too many threads or violate our
1221 // configuration for the maximum amount of cpu to use for this process. To
1222 // manage this we use the `jobserver` crate.
1224 // Job servers are an artifact of GNU make and are used to manage
1225 // parallelism between processes. A jobserver is a glorified IPC semaphore
1226 // basically. Whenever we want to run some work we acquire the semaphore,
1227 // and whenever we're done with that work we release the semaphore. In this
1228 // manner we can ensure that the maximum number of parallel workers is
1229 // capped at any one point in time.
1231 // LTO and the coordinator thread
1232 // ------------------------------
1234 // The final job the coordinator thread is responsible for is managing LTO
1235 // and how that works. When LTO is requested what we'll to is collect all
1236 // optimized LLVM modules into a local vector on the coordinator. Once all
1237 // modules have been codegened and optimized we hand this to the `lto`
1238 // module for further optimization. The `lto` module will return back a list
1239 // of more modules to work on, which the coordinator will continue to spawn
1242 // Each LLVM module is automatically sent back to the coordinator for LTO if
1243 // necessary. There's already optimizations in place to avoid sending work
1244 // back to the coordinator if LTO isn't requested.
1245 return thread::spawn(move || {
1246 // We pretend to be within the top-level LLVM time-passes task here:
1249 let max_workers = ::num_cpus::get();
1250 let mut worker_id_counter = 0;
1251 let mut free_worker_ids = Vec::new();
1252 let mut get_worker_id = |free_worker_ids: &mut Vec<usize>| {
1253 if let Some(id) = free_worker_ids.pop() {
1256 let id = worker_id_counter;
1257 worker_id_counter += 1;
1262 // This is where we collect codegen units that have gone all the way
1263 // through codegen and LLVM.
1264 let mut compiled_modules = vec![];
1265 let mut compiled_metadata_module = None;
1266 let mut compiled_allocator_module = None;
1267 let mut needs_fat_lto = Vec::new();
1268 let mut needs_thin_lto = Vec::new();
1269 let mut lto_import_only_modules = Vec::new();
1270 let mut started_lto = false;
1271 let mut codegen_aborted = false;
1273 // This flag tracks whether all items have gone through codegens
1274 let mut codegen_done = false;
1276 // This is the queue of LLVM work items that still need processing.
1277 let mut work_items = Vec::<(WorkItem<B>, u64)>::new();
1279 // This are the Jobserver Tokens we currently hold. Does not include
1280 // the implicit Token the compiler process owns no matter what.
1281 let mut tokens = Vec::new();
1283 let mut main_thread_worker_state = MainThreadWorkerState::Idle;
1284 let mut running = 0;
1286 let mut llvm_start_time = None;
1288 // Run the message loop while there's still anything that needs message
1289 // processing. Note that as soon as codegen is aborted we simply want to
1290 // wait for all existing work to finish, so many of the conditions here
1291 // only apply if codegen hasn't been aborted as they represent pending
1293 while !codegen_done ||
1295 (!codegen_aborted && (
1296 work_items.len() > 0 ||
1297 needs_fat_lto.len() > 0 ||
1298 needs_thin_lto.len() > 0 ||
1299 lto_import_only_modules.len() > 0 ||
1300 main_thread_worker_state != MainThreadWorkerState::Idle
1304 // While there are still CGUs to be codegened, the coordinator has
1305 // to decide how to utilize the compiler processes implicit Token:
1306 // For codegenning more CGU or for running them through LLVM.
1308 if main_thread_worker_state == MainThreadWorkerState::Idle {
1309 if !queue_full_enough(work_items.len(), running, max_workers) {
1310 // The queue is not full enough, codegen more items:
1311 if let Err(_) = codegen_worker_send.send(Message::CodegenItem) {
1312 panic!("Could not send Message::CodegenItem to main thread")
1314 main_thread_worker_state = MainThreadWorkerState::Codegenning;
1316 // The queue is full enough to not let the worker
1317 // threads starve. Use the implicit Token to do some
1319 let (item, _) = work_items.pop()
1320 .expect("queue empty - queue_full_enough() broken?");
1321 let cgcx = CodegenContext {
1322 worker: get_worker_id(&mut free_worker_ids),
1325 maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1326 &mut llvm_start_time);
1327 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1328 spawn_work(cgcx, item);
1331 } else if codegen_aborted {
1332 // don't queue up any more work if codegen was aborted, we're
1333 // just waiting for our existing children to finish
1335 // If we've finished everything related to normal codegen
1336 // then it must be the case that we've got some LTO work to do.
1337 // Perform the serial work here of figuring out what we're
1338 // going to LTO and then push a bunch of work items onto our
1340 if work_items.len() == 0 &&
1342 main_thread_worker_state == MainThreadWorkerState::Idle {
1343 assert!(!started_lto);
1347 mem::replace(&mut needs_fat_lto, Vec::new());
1348 let needs_thin_lto =
1349 mem::replace(&mut needs_thin_lto, Vec::new());
1350 let import_only_modules =
1351 mem::replace(&mut lto_import_only_modules, Vec::new());
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 let compiled_metadata_module = compiled_metadata_module
1570 .expect("Metadata module not compiled?");
1572 Ok(CompiledModules {
1573 modules: compiled_modules,
1574 metadata_module: compiled_metadata_module,
1575 allocator_module: compiled_allocator_module,
1579 // A heuristic that determines if we have enough LLVM WorkItems in the
1580 // queue so that the main thread can do LLVM work instead of codegen
1581 fn queue_full_enough(items_in_queue: usize,
1582 workers_running: usize,
1583 max_workers: usize) -> bool {
1585 items_in_queue > 0 &&
1586 items_in_queue >= max_workers.saturating_sub(workers_running / 2)
1589 fn maybe_start_llvm_timer(config: &ModuleConfig,
1590 llvm_start_time: &mut Option<Instant>) {
1591 // We keep track of the -Ztime-passes output manually,
1592 // since the closure-based interface does not fit well here.
1593 if config.time_passes {
1594 if llvm_start_time.is_none() {
1595 *llvm_start_time = Some(Instant::now());
1601 pub const CODEGEN_WORKER_ID: usize = ::std::usize::MAX;
1603 fn spawn_work<B: ExtraBackendMethods>(
1604 cgcx: CodegenContext<B>,
1607 let depth = time_depth();
1609 thread::spawn(move || {
1610 set_time_depth(depth);
1612 // Set up a destructor which will fire off a message that we're done as
1614 struct Bomb<B: ExtraBackendMethods> {
1615 coordinator_send: Sender<Box<dyn Any + Send>>,
1616 result: Option<WorkItemResult<B>>,
1619 impl<B: ExtraBackendMethods> Drop for Bomb<B> {
1620 fn drop(&mut self) {
1621 let worker_id = self.worker_id;
1622 let msg = match self.result.take() {
1623 Some(WorkItemResult::Compiled(m)) => {
1624 Message::Done::<B> { result: Ok(m), worker_id }
1626 Some(WorkItemResult::NeedsFatLTO(m)) => {
1627 Message::NeedsFatLTO::<B> { result: m, worker_id }
1629 Some(WorkItemResult::NeedsThinLTO(name, thin_buffer)) => {
1630 Message::NeedsThinLTO::<B> { name, thin_buffer, worker_id }
1632 None => Message::Done::<B> { result: Err(()), worker_id }
1634 drop(self.coordinator_send.send(Box::new(msg)));
1638 let mut bomb = Bomb::<B> {
1639 coordinator_send: cgcx.coordinator_send.clone(),
1641 worker_id: cgcx.worker,
1644 // Execute the work itself, and if it finishes successfully then flag
1645 // ourselves as a success as well.
1647 // Note that we ignore any `FatalError` coming out of `execute_work_item`,
1648 // as a diagnostic was already sent off to the main thread - just
1649 // surface that there was an error in this worker.
1651 let label = work.name();
1652 cgcx.profile(|p| p.start_activity(ProfileCategory::Codegen, label.clone()));
1653 let result = execute_work_item(&cgcx, work).ok();
1654 cgcx.profile(|p| p.end_activity(ProfileCategory::Codegen, label));
1661 pub fn run_assembler<B: ExtraBackendMethods>(
1662 cgcx: &CodegenContext<B>,
1667 let assembler = cgcx.assembler_cmd
1669 .expect("cgcx.assembler_cmd is missing?");
1671 let pname = &assembler.name;
1672 let mut cmd = assembler.cmd.clone();
1673 cmd.arg("-c").arg("-o").arg(object).arg(assembly);
1674 debug!("{:?}", cmd);
1676 match cmd.output() {
1678 if !prog.status.success() {
1679 let mut note = prog.stderr.clone();
1680 note.extend_from_slice(&prog.stdout);
1682 handler.struct_err(&format!("linking with `{}` failed: {}",
1685 .note(&format!("{:?}", &cmd))
1686 .note(str::from_utf8(¬e[..]).unwrap())
1688 handler.abort_if_errors();
1692 handler.err(&format!("could not exec the linker `{}`: {}", pname.display(), e));
1693 handler.abort_if_errors();
1699 enum SharedEmitterMessage {
1700 Diagnostic(Diagnostic),
1701 InlineAsmError(u32, String),
1707 pub struct SharedEmitter {
1708 sender: Sender<SharedEmitterMessage>,
1711 pub struct SharedEmitterMain {
1712 receiver: Receiver<SharedEmitterMessage>,
1715 impl SharedEmitter {
1716 pub fn new() -> (SharedEmitter, SharedEmitterMain) {
1717 let (sender, receiver) = channel();
1719 (SharedEmitter { sender }, SharedEmitterMain { receiver })
1722 pub fn inline_asm_error(&self, cookie: u32, msg: String) {
1723 drop(self.sender.send(SharedEmitterMessage::InlineAsmError(cookie, msg)));
1726 pub fn fatal(&self, msg: &str) {
1727 drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1731 impl Emitter for SharedEmitter {
1732 fn emit(&mut self, db: &DiagnosticBuilder<'_>) {
1733 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1735 code: db.code.clone(),
1738 for child in &db.children {
1739 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1740 msg: child.message(),
1745 drop(self.sender.send(SharedEmitterMessage::AbortIfErrors));
1749 impl SharedEmitterMain {
1750 pub fn check(&self, sess: &Session, blocking: bool) {
1752 let message = if blocking {
1753 match self.receiver.recv() {
1754 Ok(message) => Ok(message),
1758 match self.receiver.try_recv() {
1759 Ok(message) => Ok(message),
1765 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
1766 let handler = sess.diagnostic();
1769 handler.emit_with_code(&MultiSpan::new(),
1775 handler.emit(&MultiSpan::new(),
1781 Ok(SharedEmitterMessage::InlineAsmError(cookie, msg)) => {
1782 match Mark::from_u32(cookie).expn_info() {
1783 Some(ei) => sess.span_err(ei.call_site, &msg),
1784 None => sess.err(&msg),
1787 Ok(SharedEmitterMessage::AbortIfErrors) => {
1788 sess.abort_if_errors();
1790 Ok(SharedEmitterMessage::Fatal(msg)) => {
1802 pub struct OngoingCodegen<B: ExtraBackendMethods> {
1804 pub crate_name: Symbol,
1805 pub crate_hash: Svh,
1806 pub metadata: EncodedMetadata,
1807 pub windows_subsystem: Option<String>,
1808 pub linker_info: LinkerInfo,
1809 pub crate_info: CrateInfo,
1810 pub coordinator_send: Sender<Box<dyn Any + Send>>,
1811 pub codegen_worker_receive: Receiver<Message<B>>,
1812 pub shared_emitter_main: SharedEmitterMain,
1813 pub future: thread::JoinHandle<Result<CompiledModules, ()>>,
1814 pub output_filenames: Arc<OutputFilenames>,
1817 impl<B: ExtraBackendMethods> OngoingCodegen<B> {
1821 ) -> (CodegenResults, FxHashMap<WorkProductId, WorkProduct>) {
1822 self.shared_emitter_main.check(sess, true);
1823 let compiled_modules = match self.future.join() {
1824 Ok(Ok(compiled_modules)) => compiled_modules,
1826 sess.abort_if_errors();
1827 panic!("expected abort due to worker thread errors")
1830 bug!("panic during codegen/LLVM phase");
1834 sess.cgu_reuse_tracker.check_expected_reuse(sess);
1836 sess.abort_if_errors();
1839 copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess,
1841 produce_final_output_artifacts(sess,
1843 &self.output_filenames);
1845 // FIXME: time_llvm_passes support - does this use a global context or
1847 if sess.codegen_units() == 1 && sess.time_llvm_passes() {
1848 self.backend.print_pass_timings()
1852 crate_name: self.crate_name,
1853 crate_hash: self.crate_hash,
1854 metadata: self.metadata,
1855 windows_subsystem: self.windows_subsystem,
1856 linker_info: self.linker_info,
1857 crate_info: self.crate_info,
1859 modules: compiled_modules.modules,
1860 allocator_module: compiled_modules.allocator_module,
1861 metadata_module: compiled_modules.metadata_module,
1865 pub fn submit_pre_codegened_module_to_llvm(&self,
1866 tcx: TyCtxt<'_, '_, '_>,
1867 module: ModuleCodegen<B::Module>) {
1868 self.wait_for_signal_to_codegen_item();
1869 self.check_for_errors(tcx.sess);
1871 // These are generally cheap and won't through off scheduling.
1873 submit_codegened_module_to_llvm(&self.backend, tcx, module, cost);
1876 pub fn codegen_finished(&self, tcx: TyCtxt<'_, '_, '_>) {
1877 self.wait_for_signal_to_codegen_item();
1878 self.check_for_errors(tcx.sess);
1879 drop(self.coordinator_send.send(Box::new(Message::CodegenComplete::<B>)));
1882 /// Consumes this context indicating that codegen was entirely aborted, and
1883 /// we need to exit as quickly as possible.
1885 /// This method blocks the current thread until all worker threads have
1886 /// finished, and all worker threads should have exited or be real close to
1887 /// exiting at this point.
1888 pub fn codegen_aborted(self) {
1889 // Signal to the coordinator it should spawn no more work and start
1891 drop(self.coordinator_send.send(Box::new(Message::CodegenAborted::<B>)));
1892 drop(self.future.join());
1895 pub fn check_for_errors(&self, sess: &Session) {
1896 self.shared_emitter_main.check(sess, false);
1899 pub fn wait_for_signal_to_codegen_item(&self) {
1900 match self.codegen_worker_receive.recv() {
1901 Ok(Message::CodegenItem) => {
1904 Ok(_) => panic!("unexpected message"),
1906 // One of the LLVM threads must have panicked, fall through so
1907 // error handling can be reached.
1913 pub fn submit_codegened_module_to_llvm<B: ExtraBackendMethods>(
1915 tcx: TyCtxt<'_, '_, '_>,
1916 module: ModuleCodegen<B::Module>,
1919 let llvm_work_item = WorkItem::Optimize(module);
1920 drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::CodegenDone::<B> {
1926 pub fn submit_post_lto_module_to_llvm<B: ExtraBackendMethods>(
1928 tcx: TyCtxt<'_, '_, '_>,
1929 module: CachedModuleCodegen
1931 let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
1932 drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::CodegenDone::<B> {
1938 pub fn submit_pre_lto_module_to_llvm<B: ExtraBackendMethods>(
1940 tcx: TyCtxt<'_, '_, '_>,
1941 module: CachedModuleCodegen
1943 let filename = pre_lto_bitcode_filename(&module.name);
1944 let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
1945 let file = fs::File::open(&bc_path).unwrap_or_else(|e| {
1946 panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e)
1950 memmap::Mmap::map(&file).unwrap_or_else(|e| {
1951 panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
1954 // Schedule the module to be loaded
1955 drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::AddImportOnlyModule::<B> {
1956 module_data: SerializedModule::FromUncompressedFile(mmap),
1957 work_product: module.source,
1961 pub fn pre_lto_bitcode_filename(module_name: &str) -> String {
1962 format!("{}.{}", module_name, PRE_LTO_BC_EXT)
1965 fn msvc_imps_needed(tcx: TyCtxt<'_, '_, '_>) -> bool {
1966 // This should never be true (because it's not supported). If it is true,
1967 // something is wrong with commandline arg validation.
1968 assert!(!(tcx.sess.opts.cg.linker_plugin_lto.enabled() &&
1969 tcx.sess.target.target.options.is_like_msvc &&
1970 tcx.sess.opts.cg.prefer_dynamic));
1972 tcx.sess.target.target.options.is_like_msvc &&
1973 tcx.sess.crate_types.borrow().iter().any(|ct| *ct == config::CrateType::Rlib) &&
1974 // ThinLTO can't handle this workaround in all cases, so we don't
1975 // emit the `__imp_` symbols. Instead we make them unnecessary by disallowing
1976 // dynamic linking when linker plugin LTO is enabled.
1977 !tcx.sess.opts.cg.linker_plugin_lto.enabled()