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, DiagnosticBuilder, FatalError, DiagnosticId};
26 use rustc_errors::emitter::{Emitter};
27 use rustc_target::spec::MergeFunctions;
29 use syntax::ext::hygiene::Mark;
30 use syntax_pos::MultiSpan;
31 use syntax_pos::symbol::{Symbol, sym};
32 use jobserver::{Client, Acquired};
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: SwitchWithOptPath,
60 pub pgo_use: Option<PathBuf>,
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 {
97 pgo_gen: SwitchWithOptPath::Disabled,
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_extended();
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<SelfProfiler>>,
202 label: Cow<'static, str>,
205 impl ProfileGenericActivityTimer {
207 profiler: Option<Arc<SelfProfiler>>,
208 label: Cow<'static, str>,
209 ) -> ProfileGenericActivityTimer {
210 if let Some(profiler) = &profiler {
211 profiler.start_activity(label.clone());
214 ProfileGenericActivityTimer {
221 impl Drop for ProfileGenericActivityTimer {
223 if let Some(profiler) = &self.profiler {
224 profiler.end_activity(self.label.clone());
229 /// Additional resources used by optimize_and_codegen (not module specific)
231 pub struct CodegenContext<B: WriteBackendMethods> {
232 // Resources needed when running LTO
234 pub time_passes: bool,
235 pub profiler: Option<Arc<SelfProfiler>>,
237 pub no_landing_pads: bool,
238 pub save_temps: bool,
239 pub fewer_names: bool,
240 pub exported_symbols: Option<Arc<ExportedSymbols>>,
241 pub opts: Arc<config::Options>,
242 pub crate_types: Vec<config::CrateType>,
243 pub each_linked_rlib_for_lto: Vec<(CrateNum, PathBuf)>,
244 pub output_filenames: Arc<OutputFilenames>,
245 pub regular_module_config: Arc<ModuleConfig>,
246 pub metadata_module_config: Arc<ModuleConfig>,
247 pub allocator_module_config: Arc<ModuleConfig>,
248 pub tm_factory: TargetMachineFactory<B>,
249 pub msvc_imps_needed: bool,
250 pub target_pointer_width: String,
251 pub target_arch: String,
252 pub debuginfo: config::DebugInfo,
254 // Number of cgus excluding the allocator/metadata modules
255 pub total_cgus: usize,
256 // Handler to use for diagnostics produced during codegen.
257 pub diag_emitter: SharedEmitter,
258 // LLVM passes added by plugins.
259 pub plugin_passes: Vec<String>,
260 // LLVM optimizations for which we want to print remarks.
262 // Worker thread number
264 // The incremental compilation session directory, or None if we are not
265 // compiling incrementally
266 pub incr_comp_session_dir: Option<PathBuf>,
267 // Used to update CGU re-use information during the thinlto phase.
268 pub cgu_reuse_tracker: CguReuseTracker,
269 // Channel back to the main control thread to send messages to
270 pub coordinator_send: Sender<Box<dyn Any + Send>>,
271 // The assembler command if no_integrated_as option is enabled, None otherwise
272 pub assembler_cmd: Option<Arc<AssemblerCommand>>
275 impl<B: WriteBackendMethods> CodegenContext<B> {
276 pub fn create_diag_handler(&self) -> Handler {
277 Handler::with_emitter(true, None, Box::new(self.diag_emitter.clone()))
280 pub fn config(&self, kind: ModuleKind) -> &ModuleConfig {
282 ModuleKind::Regular => &self.regular_module_config,
283 ModuleKind::Metadata => &self.metadata_module_config,
284 ModuleKind::Allocator => &self.allocator_module_config,
290 fn profiler_active<F: FnOnce(&SelfProfiler) -> ()>(&self, f: F) {
291 match &self.profiler {
292 None => bug!("profiler_active() called but there was no profiler active"),
300 pub fn profile<F: FnOnce(&SelfProfiler) -> ()>(&self, f: F) {
301 if unlikely!(self.profiler.is_some()) {
302 self.profiler_active(f)
306 pub fn profile_activity(
308 label: impl Into<Cow<'static, str>>,
309 ) -> ProfileGenericActivityTimer {
310 ProfileGenericActivityTimer::start(self.profiler.clone(), label.into())
314 fn generate_lto_work<B: ExtraBackendMethods>(
315 cgcx: &CodegenContext<B>,
316 needs_fat_lto: Vec<FatLTOInput<B>>,
317 needs_thin_lto: Vec<(String, B::ThinBuffer)>,
318 import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>
319 ) -> Vec<(WorkItem<B>, u64)> {
320 cgcx.profile(|p| p.start_activity("codegen_run_lto"));
322 let (lto_modules, copy_jobs) = if !needs_fat_lto.is_empty() {
323 assert!(needs_thin_lto.is_empty());
324 let lto_module = B::run_fat_lto(
329 .unwrap_or_else(|e| e.raise());
330 (vec![lto_module], vec![])
332 assert!(needs_fat_lto.is_empty());
333 B::run_thin_lto(cgcx, needs_thin_lto, import_only_modules)
334 .unwrap_or_else(|e| e.raise())
337 let result = lto_modules.into_iter().map(|module| {
338 let cost = module.cost();
339 (WorkItem::LTO(module), cost)
340 }).chain(copy_jobs.into_iter().map(|wp| {
341 (WorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
342 name: wp.cgu_name.clone(),
347 cgcx.profile(|p| p.end_activity("codegen_run_lto"));
352 pub struct CompiledModules {
353 pub modules: Vec<CompiledModule>,
354 pub metadata_module: Option<CompiledModule>,
355 pub allocator_module: Option<CompiledModule>,
358 fn need_crate_bitcode_for_rlib(sess: &Session) -> bool {
359 sess.crate_types.borrow().contains(&config::CrateType::Rlib) &&
360 sess.opts.output_types.contains_key(&OutputType::Exe)
363 fn need_pre_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
364 if sess.opts.incremental.is_none() {
372 Lto::ThinLocal => true,
376 pub fn start_async_codegen<B: ExtraBackendMethods>(
379 metadata: EncodedMetadata,
380 coordinator_receive: Receiver<Box<dyn Any + Send>>,
382 ) -> OngoingCodegen<B> {
384 let crate_name = tcx.crate_name(LOCAL_CRATE);
385 let crate_hash = tcx.crate_hash(LOCAL_CRATE);
386 let no_builtins = attr::contains_name(&tcx.hir().krate().attrs, sym::no_builtins);
387 let subsystem = attr::first_attr_value_str_by_name(&tcx.hir().krate().attrs,
388 sym::windows_subsystem);
389 let windows_subsystem = subsystem.map(|subsystem| {
390 if subsystem != sym::windows && subsystem != sym::console {
391 tcx.sess.fatal(&format!("invalid windows subsystem `{}`, only \
392 `windows` and `console` are allowed",
395 subsystem.to_string()
398 let linker_info = LinkerInfo::new(tcx);
399 let crate_info = CrateInfo::new(tcx);
401 // Figure out what we actually need to build.
402 let mut modules_config = ModuleConfig::new(sess.opts.cg.passes.clone());
403 let mut metadata_config = ModuleConfig::new(vec![]);
404 let mut allocator_config = ModuleConfig::new(vec![]);
406 if let Some(ref sanitizer) = sess.opts.debugging_opts.sanitizer {
408 Sanitizer::Address => {
409 modules_config.passes.push("asan".to_owned());
410 modules_config.passes.push("asan-module".to_owned());
412 Sanitizer::Memory => {
413 modules_config.passes.push("msan".to_owned())
415 Sanitizer::Thread => {
416 modules_config.passes.push("tsan".to_owned())
422 if sess.opts.debugging_opts.profile {
423 modules_config.passes.push("insert-gcov-profiling".to_owned())
426 modules_config.pgo_gen = sess.opts.debugging_opts.pgo_gen.clone();
427 modules_config.pgo_use = sess.opts.debugging_opts.pgo_use.clone();
429 modules_config.opt_level = Some(sess.opts.optimize);
430 modules_config.opt_size = Some(sess.opts.optimize);
432 // Save all versions of the bytecode if we're saving our temporaries.
433 if sess.opts.cg.save_temps {
434 modules_config.emit_no_opt_bc = true;
435 modules_config.emit_pre_lto_bc = true;
436 modules_config.emit_bc = true;
437 modules_config.emit_lto_bc = true;
438 metadata_config.emit_bc = true;
439 allocator_config.emit_bc = true;
442 // Emit compressed bitcode files for the crate if we're emitting an rlib.
443 // Whenever an rlib is created, the bitcode is inserted into the archive in
444 // order to allow LTO against it.
445 if need_crate_bitcode_for_rlib(sess) {
446 modules_config.emit_bc_compressed = true;
447 allocator_config.emit_bc_compressed = true;
450 modules_config.emit_pre_lto_bc =
451 need_pre_lto_bitcode_for_incr_comp(sess);
453 modules_config.no_integrated_as = tcx.sess.opts.cg.no_integrated_as ||
454 tcx.sess.target.target.options.no_integrated_as;
456 for output_type in sess.opts.output_types.keys() {
458 OutputType::Bitcode => { modules_config.emit_bc = true; }
459 OutputType::LlvmAssembly => { modules_config.emit_ir = true; }
460 OutputType::Assembly => {
461 modules_config.emit_asm = true;
462 // If we're not using the LLVM assembler, this function
463 // could be invoked specially with output_type_assembly, so
464 // in this case we still want the metadata object file.
465 if !sess.opts.output_types.contains_key(&OutputType::Assembly) {
466 metadata_config.emit_obj = true;
467 allocator_config.emit_obj = true;
470 OutputType::Object => { modules_config.emit_obj = true; }
471 OutputType::Metadata => { metadata_config.emit_obj = true; }
473 modules_config.emit_obj = true;
474 metadata_config.emit_obj = true;
475 allocator_config.emit_obj = true;
477 OutputType::Mir => {}
478 OutputType::DepInfo => {}
482 modules_config.set_flags(sess, no_builtins);
483 metadata_config.set_flags(sess, no_builtins);
484 allocator_config.set_flags(sess, no_builtins);
486 // Exclude metadata and allocator modules from time_passes output, since
487 // they throw off the "LLVM passes" measurement.
488 metadata_config.time_passes = false;
489 allocator_config.time_passes = false;
491 let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
492 let (codegen_worker_send, codegen_worker_receive) = channel();
494 let coordinator_thread = start_executing_work(backend.clone(),
501 sess.jobserver.clone(),
502 Arc::new(modules_config),
503 Arc::new(metadata_config),
504 Arc::new(allocator_config));
515 coordinator_send: tcx.tx_to_llvm_workers.lock().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 ) -> thread::JoinHandle<Result<CompiledModules, ()>> {
1010 let coordinator_send = tcx.tx_to_llvm_workers.lock().clone();
1011 let sess = tcx.sess;
1013 // Compute the set of symbols we need to retain when doing LTO (if we need to)
1014 let exported_symbols = {
1015 let mut exported_symbols = FxHashMap::default();
1017 let copy_symbols = |cnum| {
1018 let symbols = tcx.exported_symbols(cnum)
1020 .map(|&(s, lvl)| (s.symbol_name(tcx).to_string(), lvl))
1028 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1029 Some(Arc::new(exported_symbols))
1031 Lto::Fat | Lto::Thin => {
1032 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1033 for &cnum in tcx.crates().iter() {
1034 exported_symbols.insert(cnum, copy_symbols(cnum));
1036 Some(Arc::new(exported_symbols))
1041 // First up, convert our jobserver into a helper thread so we can use normal
1042 // mpsc channels to manage our messages and such.
1043 // After we've requested tokens then we'll, when we can,
1044 // get tokens on `coordinator_receive` which will
1045 // get managed in the main loop below.
1046 let coordinator_send2 = coordinator_send.clone();
1047 let helper = jobserver.into_helper_thread(move |token| {
1048 drop(coordinator_send2.send(Box::new(Message::Token::<B>(token))));
1049 }).expect("failed to spawn helper thread");
1051 let mut each_linked_rlib_for_lto = Vec::new();
1052 drop(link::each_linked_rlib(sess, crate_info, &mut |cnum, path| {
1053 if link::ignored_for_lto(sess, crate_info, cnum) {
1056 each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
1059 let assembler_cmd = if modules_config.no_integrated_as {
1060 // HACK: currently we use linker (gcc) as our assembler
1061 let (linker, flavor) = link::linker_and_flavor(sess);
1063 let (name, mut cmd) = get_linker(sess, &linker, flavor);
1064 cmd.args(&sess.target.target.options.asm_args);
1065 Some(Arc::new(AssemblerCommand {
1073 let ol = if tcx.sess.opts.debugging_opts.no_codegen
1074 || !tcx.sess.opts.output_types.should_codegen() {
1075 // If we know that we won’t be doing codegen, create target machines without optimisation.
1076 config::OptLevel::No
1078 tcx.backend_optimization_level(LOCAL_CRATE)
1080 let cgcx = CodegenContext::<B> {
1081 backend: backend.clone(),
1082 crate_types: sess.crate_types.borrow().clone(),
1083 each_linked_rlib_for_lto,
1085 no_landing_pads: sess.no_landing_pads(),
1086 fewer_names: sess.fewer_names(),
1087 save_temps: sess.opts.cg.save_temps,
1088 opts: Arc::new(sess.opts.clone()),
1089 time_passes: sess.time_extended(),
1090 profiler: sess.self_profiling.clone(),
1092 plugin_passes: sess.plugin_llvm_passes.borrow().clone(),
1093 remark: sess.opts.cg.remark.clone(),
1095 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1096 cgu_reuse_tracker: sess.cgu_reuse_tracker.clone(),
1098 diag_emitter: shared_emitter.clone(),
1099 output_filenames: tcx.output_filenames(LOCAL_CRATE),
1100 regular_module_config: modules_config,
1101 metadata_module_config: metadata_config,
1102 allocator_module_config: allocator_config,
1103 tm_factory: TargetMachineFactory(backend.target_machine_factory(tcx.sess, ol, false)),
1105 msvc_imps_needed: msvc_imps_needed(tcx),
1106 target_pointer_width: tcx.sess.target.target.target_pointer_width.clone(),
1107 target_arch: tcx.sess.target.target.arch.clone(),
1108 debuginfo: tcx.sess.opts.debuginfo,
1112 // This is the "main loop" of parallel work happening for parallel codegen.
1113 // It's here that we manage parallelism, schedule work, and work with
1114 // messages coming from clients.
1116 // There are a few environmental pre-conditions that shape how the system
1119 // - Error reporting only can happen on the main thread because that's the
1120 // only place where we have access to the compiler `Session`.
1121 // - LLVM work can be done on any thread.
1122 // - Codegen can only happen on the main thread.
1123 // - Each thread doing substantial work most be in possession of a `Token`
1124 // from the `Jobserver`.
1125 // - The compiler process always holds one `Token`. Any additional `Tokens`
1126 // have to be requested from the `Jobserver`.
1130 // The error reporting restriction is handled separately from the rest: We
1131 // set up a `SharedEmitter` the holds an open channel to the main thread.
1132 // When an error occurs on any thread, the shared emitter will send the
1133 // error message to the receiver main thread (`SharedEmitterMain`). The
1134 // main thread will periodically query this error message queue and emit
1135 // any error messages it has received. It might even abort compilation if
1136 // has received a fatal error. In this case we rely on all other threads
1137 // being torn down automatically with the main thread.
1138 // Since the main thread will often be busy doing codegen work, error
1139 // reporting will be somewhat delayed, since the message queue can only be
1140 // checked in between to work packages.
1142 // Work Processing Infrastructure
1143 // ==============================
1144 // The work processing infrastructure knows three major actors:
1146 // - the coordinator thread,
1147 // - the main thread, and
1148 // - LLVM worker threads
1150 // The coordinator thread is running a message loop. It instructs the main
1151 // thread about what work to do when, and it will spawn off LLVM worker
1152 // threads as open LLVM WorkItems become available.
1154 // The job of the main thread is to codegen CGUs into LLVM work package
1155 // (since the main thread is the only thread that can do this). The main
1156 // thread will block until it receives a message from the coordinator, upon
1157 // which it will codegen one CGU, send it to the coordinator and block
1158 // again. This way the coordinator can control what the main thread is
1161 // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1162 // available, it will spawn off a new LLVM worker thread and let it process
1163 // that a WorkItem. When a LLVM worker thread is done with its WorkItem,
1164 // it will just shut down, which also frees all resources associated with
1165 // the given LLVM module, and sends a message to the coordinator that the
1166 // has been completed.
1170 // The scheduler's goal is to minimize the time it takes to complete all
1171 // work there is, however, we also want to keep memory consumption low
1172 // if possible. These two goals are at odds with each other: If memory
1173 // consumption were not an issue, we could just let the main thread produce
1174 // LLVM WorkItems at full speed, assuring maximal utilization of
1175 // Tokens/LLVM worker threads. However, since codegen usual is faster
1176 // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1177 // WorkItem potentially holds on to a substantial amount of memory.
1179 // So the actual goal is to always produce just enough LLVM WorkItems as
1180 // not to starve our LLVM worker threads. That means, once we have enough
1181 // WorkItems in our queue, we can block the main thread, so it does not
1182 // produce more until we need them.
1184 // Doing LLVM Work on the Main Thread
1185 // ----------------------------------
1186 // Since the main thread owns the compiler processes implicit `Token`, it is
1187 // wasteful to keep it blocked without doing any work. Therefore, what we do
1188 // in this case is: We spawn off an additional LLVM worker thread that helps
1189 // reduce the queue. The work it is doing corresponds to the implicit
1190 // `Token`. The coordinator will mark the main thread as being busy with
1191 // LLVM work. (The actual work happens on another OS thread but we just care
1192 // about `Tokens`, not actual threads).
1194 // When any LLVM worker thread finishes while the main thread is marked as
1195 // "busy with LLVM work", we can do a little switcheroo: We give the Token
1196 // of the just finished thread to the LLVM worker thread that is working on
1197 // behalf of the main thread's implicit Token, thus freeing up the main
1198 // thread again. The coordinator can then again decide what the main thread
1199 // should do. This allows the coordinator to make decisions at more points
1202 // Striking a Balance between Throughput and Memory Consumption
1203 // ------------------------------------------------------------
1204 // Since our two goals, (1) use as many Tokens as possible and (2) keep
1205 // memory consumption as low as possible, are in conflict with each other,
1206 // we have to find a trade off between them. Right now, the goal is to keep
1207 // all workers busy, which means that no worker should find the queue empty
1208 // when it is ready to start.
1209 // How do we do achieve this? Good question :) We actually never know how
1210 // many `Tokens` are potentially available so it's hard to say how much to
1211 // fill up the queue before switching the main thread to LLVM work. Also we
1212 // currently don't have a means to estimate how long a running LLVM worker
1213 // will still be busy with it's current WorkItem. However, we know the
1214 // maximal count of available Tokens that makes sense (=the number of CPU
1215 // cores), so we can take a conservative guess. The heuristic we use here
1216 // is implemented in the `queue_full_enough()` function.
1218 // Some Background on Jobservers
1219 // -----------------------------
1220 // It's worth also touching on the management of parallelism here. We don't
1221 // want to just spawn a thread per work item because while that's optimal
1222 // parallelism it may overload a system with too many threads or violate our
1223 // configuration for the maximum amount of cpu to use for this process. To
1224 // manage this we use the `jobserver` crate.
1226 // Job servers are an artifact of GNU make and are used to manage
1227 // parallelism between processes. A jobserver is a glorified IPC semaphore
1228 // basically. Whenever we want to run some work we acquire the semaphore,
1229 // and whenever we're done with that work we release the semaphore. In this
1230 // manner we can ensure that the maximum number of parallel workers is
1231 // capped at any one point in time.
1233 // LTO and the coordinator thread
1234 // ------------------------------
1236 // The final job the coordinator thread is responsible for is managing LTO
1237 // and how that works. When LTO is requested what we'll to is collect all
1238 // optimized LLVM modules into a local vector on the coordinator. Once all
1239 // modules have been codegened and optimized we hand this to the `lto`
1240 // module for further optimization. The `lto` module will return back a list
1241 // of more modules to work on, which the coordinator will continue to spawn
1244 // Each LLVM module is automatically sent back to the coordinator for LTO if
1245 // necessary. There's already optimizations in place to avoid sending work
1246 // back to the coordinator if LTO isn't requested.
1247 return thread::spawn(move || {
1248 // We pretend to be within the top-level LLVM time-passes task here:
1251 let max_workers = ::num_cpus::get();
1252 let mut worker_id_counter = 0;
1253 let mut free_worker_ids = Vec::new();
1254 let mut get_worker_id = |free_worker_ids: &mut Vec<usize>| {
1255 if let Some(id) = free_worker_ids.pop() {
1258 let id = worker_id_counter;
1259 worker_id_counter += 1;
1264 // This is where we collect codegen units that have gone all the way
1265 // through codegen and LLVM.
1266 let mut compiled_modules = vec![];
1267 let mut compiled_metadata_module = None;
1268 let mut compiled_allocator_module = None;
1269 let mut needs_fat_lto = Vec::new();
1270 let mut needs_thin_lto = Vec::new();
1271 let mut lto_import_only_modules = Vec::new();
1272 let mut started_lto = false;
1273 let mut codegen_aborted = false;
1275 // This flag tracks whether all items have gone through codegens
1276 let mut codegen_done = false;
1278 // This is the queue of LLVM work items that still need processing.
1279 let mut work_items = Vec::<(WorkItem<B>, u64)>::new();
1281 // This are the Jobserver Tokens we currently hold. Does not include
1282 // the implicit Token the compiler process owns no matter what.
1283 let mut tokens = Vec::new();
1285 let mut main_thread_worker_state = MainThreadWorkerState::Idle;
1286 let mut running = 0;
1288 let mut llvm_start_time = None;
1290 // Run the message loop while there's still anything that needs message
1291 // processing. Note that as soon as codegen is aborted we simply want to
1292 // wait for all existing work to finish, so many of the conditions here
1293 // only apply if codegen hasn't been aborted as they represent pending
1295 while !codegen_done ||
1297 (!codegen_aborted && (
1298 work_items.len() > 0 ||
1299 needs_fat_lto.len() > 0 ||
1300 needs_thin_lto.len() > 0 ||
1301 lto_import_only_modules.len() > 0 ||
1302 main_thread_worker_state != MainThreadWorkerState::Idle
1306 // While there are still CGUs to be codegened, the coordinator has
1307 // to decide how to utilize the compiler processes implicit Token:
1308 // For codegenning more CGU or for running them through LLVM.
1310 if main_thread_worker_state == MainThreadWorkerState::Idle {
1311 if !queue_full_enough(work_items.len(), running, max_workers) {
1312 // The queue is not full enough, codegen more items:
1313 if let Err(_) = codegen_worker_send.send(Message::CodegenItem) {
1314 panic!("Could not send Message::CodegenItem to main thread")
1316 main_thread_worker_state = MainThreadWorkerState::Codegenning;
1318 // The queue is full enough to not let the worker
1319 // threads starve. Use the implicit Token to do some
1321 let (item, _) = work_items.pop()
1322 .expect("queue empty - queue_full_enough() broken?");
1323 let cgcx = CodegenContext {
1324 worker: get_worker_id(&mut free_worker_ids),
1327 maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1328 &mut llvm_start_time);
1329 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1330 spawn_work(cgcx, item);
1333 } else if codegen_aborted {
1334 // don't queue up any more work if codegen was aborted, we're
1335 // just waiting for our existing children to finish
1337 // If we've finished everything related to normal codegen
1338 // then it must be the case that we've got some LTO work to do.
1339 // Perform the serial work here of figuring out what we're
1340 // going to LTO and then push a bunch of work items onto our
1342 if work_items.len() == 0 &&
1344 main_thread_worker_state == MainThreadWorkerState::Idle {
1345 assert!(!started_lto);
1349 mem::replace(&mut needs_fat_lto, Vec::new());
1350 let needs_thin_lto =
1351 mem::replace(&mut needs_thin_lto, Vec::new());
1352 let import_only_modules =
1353 mem::replace(&mut lto_import_only_modules, Vec::new());
1355 for (work, cost) in generate_lto_work(&cgcx, needs_fat_lto,
1356 needs_thin_lto, import_only_modules) {
1357 let insertion_index = work_items
1358 .binary_search_by_key(&cost, |&(_, cost)| cost)
1359 .unwrap_or_else(|e| e);
1360 work_items.insert(insertion_index, (work, cost));
1361 if !cgcx.opts.debugging_opts.no_parallel_llvm {
1362 helper.request_token();
1367 // In this branch, we know that everything has been codegened,
1368 // so it's just a matter of determining whether the implicit
1369 // Token is free to use for LLVM work.
1370 match main_thread_worker_state {
1371 MainThreadWorkerState::Idle => {
1372 if let Some((item, _)) = work_items.pop() {
1373 let cgcx = CodegenContext {
1374 worker: get_worker_id(&mut free_worker_ids),
1377 maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1378 &mut llvm_start_time);
1379 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1380 spawn_work(cgcx, item);
1382 // There is no unstarted work, so let the main thread
1383 // take over for a running worker. Otherwise the
1384 // implicit token would just go to waste.
1385 // We reduce the `running` counter by one. The
1386 // `tokens.truncate()` below will take care of
1387 // giving the Token back.
1388 debug_assert!(running > 0);
1390 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1393 MainThreadWorkerState::Codegenning => {
1394 bug!("codegen worker should not be codegenning after \
1395 codegen was already completed")
1397 MainThreadWorkerState::LLVMing => {
1398 // Already making good use of that token
1403 // Spin up what work we can, only doing this while we've got available
1404 // parallelism slots and work left to spawn.
1405 while !codegen_aborted && work_items.len() > 0 && running < tokens.len() {
1406 let (item, _) = work_items.pop().unwrap();
1408 maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1409 &mut llvm_start_time);
1411 let cgcx = CodegenContext {
1412 worker: get_worker_id(&mut free_worker_ids),
1416 spawn_work(cgcx, item);
1420 // Relinquish accidentally acquired extra tokens
1421 tokens.truncate(running);
1423 // If a thread exits successfully then we drop a token associated
1424 // with that worker and update our `running` count. We may later
1425 // re-acquire a token to continue running more work. We may also not
1426 // actually drop a token here if the worker was running with an
1427 // "ephemeral token"
1428 let mut free_worker = |worker_id| {
1429 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1430 main_thread_worker_state = MainThreadWorkerState::Idle;
1435 free_worker_ids.push(worker_id);
1438 let msg = coordinator_receive.recv().unwrap();
1439 match *msg.downcast::<Message<B>>().ok().unwrap() {
1440 // Save the token locally and the next turn of the loop will use
1441 // this to spawn a new unit of work, or it may get dropped
1442 // immediately if we have no more work to spawn.
1443 Message::Token(token) => {
1448 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1449 // If the main thread token is used for LLVM work
1450 // at the moment, we turn that thread into a regular
1451 // LLVM worker thread, so the main thread is free
1452 // to react to codegen demand.
1453 main_thread_worker_state = MainThreadWorkerState::Idle;
1458 let msg = &format!("failed to acquire jobserver token: {}", e);
1459 shared_emitter.fatal(msg);
1460 // Exit the coordinator thread
1466 Message::CodegenDone { llvm_work_item, cost } => {
1467 // We keep the queue sorted by estimated processing cost,
1468 // so that more expensive items are processed earlier. This
1469 // is good for throughput as it gives the main thread more
1470 // time to fill up the queue and it avoids scheduling
1471 // expensive items to the end.
1472 // Note, however, that this is not ideal for memory
1473 // consumption, as LLVM module sizes are not evenly
1475 let insertion_index =
1476 work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1477 let insertion_index = match insertion_index {
1478 Ok(idx) | Err(idx) => idx
1480 work_items.insert(insertion_index, (llvm_work_item, cost));
1482 if !cgcx.opts.debugging_opts.no_parallel_llvm {
1483 helper.request_token();
1485 assert!(!codegen_aborted);
1486 assert_eq!(main_thread_worker_state,
1487 MainThreadWorkerState::Codegenning);
1488 main_thread_worker_state = MainThreadWorkerState::Idle;
1491 Message::CodegenComplete => {
1492 codegen_done = true;
1493 assert!(!codegen_aborted);
1494 assert_eq!(main_thread_worker_state,
1495 MainThreadWorkerState::Codegenning);
1496 main_thread_worker_state = MainThreadWorkerState::Idle;
1499 // If codegen is aborted that means translation was aborted due
1500 // to some normal-ish compiler error. In this situation we want
1501 // to exit as soon as possible, but we want to make sure all
1502 // existing work has finished. Flag codegen as being done, and
1503 // then conditions above will ensure no more work is spawned but
1504 // we'll keep executing this loop until `running` hits 0.
1505 Message::CodegenAborted => {
1506 assert!(!codegen_aborted);
1507 codegen_done = true;
1508 codegen_aborted = true;
1509 assert_eq!(main_thread_worker_state,
1510 MainThreadWorkerState::Codegenning);
1512 Message::Done { result: Ok(compiled_module), worker_id } => {
1513 free_worker(worker_id);
1514 match compiled_module.kind {
1515 ModuleKind::Regular => {
1516 compiled_modules.push(compiled_module);
1518 ModuleKind::Metadata => {
1519 assert!(compiled_metadata_module.is_none());
1520 compiled_metadata_module = Some(compiled_module);
1522 ModuleKind::Allocator => {
1523 assert!(compiled_allocator_module.is_none());
1524 compiled_allocator_module = Some(compiled_module);
1528 Message::NeedsFatLTO { result, worker_id } => {
1529 assert!(!started_lto);
1530 free_worker(worker_id);
1531 needs_fat_lto.push(result);
1533 Message::NeedsThinLTO { name, thin_buffer, worker_id } => {
1534 assert!(!started_lto);
1535 free_worker(worker_id);
1536 needs_thin_lto.push((name, thin_buffer));
1538 Message::AddImportOnlyModule { module_data, work_product } => {
1539 assert!(!started_lto);
1540 assert!(!codegen_done);
1541 assert_eq!(main_thread_worker_state,
1542 MainThreadWorkerState::Codegenning);
1543 lto_import_only_modules.push((module_data, work_product));
1544 main_thread_worker_state = MainThreadWorkerState::Idle;
1546 // If the thread failed that means it panicked, so we abort immediately.
1547 Message::Done { result: Err(()), worker_id: _ } => {
1548 bug!("worker thread panicked");
1550 Message::CodegenItem => {
1551 bug!("the coordinator should not receive codegen requests")
1556 if let Some(llvm_start_time) = llvm_start_time {
1557 let total_llvm_time = Instant::now().duration_since(llvm_start_time);
1558 // This is the top-level timing for all of LLVM, set the time-depth
1561 print_time_passes_entry(cgcx.time_passes,
1566 // Regardless of what order these modules completed in, report them to
1567 // the backend in the same order every time to ensure that we're handing
1568 // out deterministic results.
1569 compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
1571 Ok(CompiledModules {
1572 modules: compiled_modules,
1573 metadata_module: compiled_metadata_module,
1574 allocator_module: compiled_allocator_module,
1578 // A heuristic that determines if we have enough LLVM WorkItems in the
1579 // queue so that the main thread can do LLVM work instead of codegen
1580 fn queue_full_enough(items_in_queue: usize,
1581 workers_running: usize,
1582 max_workers: usize) -> bool {
1584 items_in_queue > 0 &&
1585 items_in_queue >= max_workers.saturating_sub(workers_running / 2)
1588 fn maybe_start_llvm_timer(config: &ModuleConfig,
1589 llvm_start_time: &mut Option<Instant>) {
1590 // We keep track of the -Ztime-passes output manually,
1591 // since the closure-based interface does not fit well here.
1592 if config.time_passes {
1593 if llvm_start_time.is_none() {
1594 *llvm_start_time = Some(Instant::now());
1600 pub const CODEGEN_WORKER_ID: usize = ::std::usize::MAX;
1602 fn spawn_work<B: ExtraBackendMethods>(
1603 cgcx: CodegenContext<B>,
1606 let depth = time_depth();
1608 thread::spawn(move || {
1609 set_time_depth(depth);
1611 // Set up a destructor which will fire off a message that we're done as
1613 struct Bomb<B: ExtraBackendMethods> {
1614 coordinator_send: Sender<Box<dyn Any + Send>>,
1615 result: Option<WorkItemResult<B>>,
1618 impl<B: ExtraBackendMethods> Drop for Bomb<B> {
1619 fn drop(&mut self) {
1620 let worker_id = self.worker_id;
1621 let msg = match self.result.take() {
1622 Some(WorkItemResult::Compiled(m)) => {
1623 Message::Done::<B> { result: Ok(m), worker_id }
1625 Some(WorkItemResult::NeedsFatLTO(m)) => {
1626 Message::NeedsFatLTO::<B> { result: m, worker_id }
1628 Some(WorkItemResult::NeedsThinLTO(name, thin_buffer)) => {
1629 Message::NeedsThinLTO::<B> { name, thin_buffer, worker_id }
1631 None => Message::Done::<B> { result: Err(()), worker_id }
1633 drop(self.coordinator_send.send(Box::new(msg)));
1637 let mut bomb = Bomb::<B> {
1638 coordinator_send: cgcx.coordinator_send.clone(),
1640 worker_id: cgcx.worker,
1643 // Execute the work itself, and if it finishes successfully then flag
1644 // ourselves as a success as well.
1646 // Note that we ignore any `FatalError` coming out of `execute_work_item`,
1647 // as a diagnostic was already sent off to the main thread - just
1648 // surface that there was an error in this worker.
1650 let label = work.name();
1651 cgcx.profile(|p| p.start_activity(label.clone()));
1652 let result = execute_work_item(&cgcx, work).ok();
1653 cgcx.profile(|p| p.end_activity(label));
1660 pub fn run_assembler<B: ExtraBackendMethods>(
1661 cgcx: &CodegenContext<B>,
1666 let assembler = cgcx.assembler_cmd
1668 .expect("cgcx.assembler_cmd is missing?");
1670 let pname = &assembler.name;
1671 let mut cmd = assembler.cmd.clone();
1672 cmd.arg("-c").arg("-o").arg(object).arg(assembly);
1673 debug!("{:?}", cmd);
1675 match cmd.output() {
1677 if !prog.status.success() {
1678 let mut note = prog.stderr.clone();
1679 note.extend_from_slice(&prog.stdout);
1681 handler.struct_err(&format!("linking with `{}` failed: {}",
1684 .note(&format!("{:?}", &cmd))
1685 .note(str::from_utf8(¬e[..]).unwrap())
1687 handler.abort_if_errors();
1691 handler.err(&format!("could not exec the linker `{}`: {}", pname.display(), e));
1692 handler.abort_if_errors();
1698 enum SharedEmitterMessage {
1699 Diagnostic(Diagnostic),
1700 InlineAsmError(u32, String),
1706 pub struct SharedEmitter {
1707 sender: Sender<SharedEmitterMessage>,
1710 pub struct SharedEmitterMain {
1711 receiver: Receiver<SharedEmitterMessage>,
1714 impl SharedEmitter {
1715 pub fn new() -> (SharedEmitter, SharedEmitterMain) {
1716 let (sender, receiver) = channel();
1718 (SharedEmitter { sender }, SharedEmitterMain { receiver })
1721 pub fn inline_asm_error(&self, cookie: u32, msg: String) {
1722 drop(self.sender.send(SharedEmitterMessage::InlineAsmError(cookie, msg)));
1725 pub fn fatal(&self, msg: &str) {
1726 drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1730 impl Emitter for SharedEmitter {
1731 fn emit_diagnostic(&mut self, db: &DiagnosticBuilder<'_>) {
1732 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1734 code: db.code.clone(),
1737 for child in &db.children {
1738 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1739 msg: child.message(),
1744 drop(self.sender.send(SharedEmitterMessage::AbortIfErrors));
1748 impl SharedEmitterMain {
1749 pub fn check(&self, sess: &Session, blocking: bool) {
1751 let message = if blocking {
1752 match self.receiver.recv() {
1753 Ok(message) => Ok(message),
1757 match self.receiver.try_recv() {
1758 Ok(message) => Ok(message),
1764 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
1765 let handler = sess.diagnostic();
1768 handler.emit_with_code(&MultiSpan::new(),
1774 handler.emit(&MultiSpan::new(),
1780 Ok(SharedEmitterMessage::InlineAsmError(cookie, msg)) => {
1781 match Mark::from_u32(cookie).expn_info() {
1782 Some(ei) => sess.span_err(ei.call_site, &msg),
1783 None => sess.err(&msg),
1786 Ok(SharedEmitterMessage::AbortIfErrors) => {
1787 sess.abort_if_errors();
1789 Ok(SharedEmitterMessage::Fatal(msg)) => {
1801 pub struct OngoingCodegen<B: ExtraBackendMethods> {
1803 pub crate_name: Symbol,
1804 pub crate_hash: Svh,
1805 pub metadata: EncodedMetadata,
1806 pub windows_subsystem: Option<String>,
1807 pub linker_info: LinkerInfo,
1808 pub crate_info: CrateInfo,
1809 pub coordinator_send: Sender<Box<dyn Any + Send>>,
1810 pub codegen_worker_receive: Receiver<Message<B>>,
1811 pub shared_emitter_main: SharedEmitterMain,
1812 pub future: thread::JoinHandle<Result<CompiledModules, ()>>,
1813 pub output_filenames: Arc<OutputFilenames>,
1816 impl<B: ExtraBackendMethods> OngoingCodegen<B> {
1820 ) -> (CodegenResults, FxHashMap<WorkProductId, WorkProduct>) {
1821 self.shared_emitter_main.check(sess, true);
1822 let compiled_modules = match self.future.join() {
1823 Ok(Ok(compiled_modules)) => compiled_modules,
1825 sess.abort_if_errors();
1826 panic!("expected abort due to worker thread errors")
1829 bug!("panic during codegen/LLVM phase");
1833 sess.cgu_reuse_tracker.check_expected_reuse(sess);
1835 sess.abort_if_errors();
1838 copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess,
1840 produce_final_output_artifacts(sess,
1842 &self.output_filenames);
1844 // FIXME: time_llvm_passes support - does this use a global context or
1846 if sess.codegen_units() == 1 && sess.time_llvm_passes() {
1847 self.backend.print_pass_timings()
1851 crate_name: self.crate_name,
1852 crate_hash: self.crate_hash,
1853 metadata: self.metadata,
1854 windows_subsystem: self.windows_subsystem,
1855 linker_info: self.linker_info,
1856 crate_info: self.crate_info,
1858 modules: compiled_modules.modules,
1859 allocator_module: compiled_modules.allocator_module,
1860 metadata_module: compiled_modules.metadata_module,
1864 pub fn submit_pre_codegened_module_to_llvm(&self,
1865 tcx: TyCtxt<'_, '_>,
1866 module: ModuleCodegen<B::Module>) {
1867 self.wait_for_signal_to_codegen_item();
1868 self.check_for_errors(tcx.sess);
1870 // These are generally cheap and won't throw off scheduling.
1872 submit_codegened_module_to_llvm(&self.backend, tcx, module, cost);
1875 pub fn codegen_finished(&self, tcx: TyCtxt<'_, '_>) {
1876 self.wait_for_signal_to_codegen_item();
1877 self.check_for_errors(tcx.sess);
1878 drop(self.coordinator_send.send(Box::new(Message::CodegenComplete::<B>)));
1881 /// Consumes this context indicating that codegen was entirely aborted, and
1882 /// we need to exit as quickly as possible.
1884 /// This method blocks the current thread until all worker threads have
1885 /// finished, and all worker threads should have exited or be real close to
1886 /// exiting at this point.
1887 pub fn codegen_aborted(self) {
1888 // Signal to the coordinator it should spawn no more work and start
1890 drop(self.coordinator_send.send(Box::new(Message::CodegenAborted::<B>)));
1891 drop(self.future.join());
1894 pub fn check_for_errors(&self, sess: &Session) {
1895 self.shared_emitter_main.check(sess, false);
1898 pub fn wait_for_signal_to_codegen_item(&self) {
1899 match self.codegen_worker_receive.recv() {
1900 Ok(Message::CodegenItem) => {
1903 Ok(_) => panic!("unexpected message"),
1905 // One of the LLVM threads must have panicked, fall through so
1906 // error handling can be reached.
1912 pub fn submit_codegened_module_to_llvm<B: ExtraBackendMethods>(
1914 tcx: TyCtxt<'_, '_>,
1915 module: ModuleCodegen<B::Module>,
1918 let llvm_work_item = WorkItem::Optimize(module);
1919 drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::CodegenDone::<B> {
1925 pub fn submit_post_lto_module_to_llvm<B: ExtraBackendMethods>(
1927 tcx: TyCtxt<'_, '_>,
1928 module: CachedModuleCodegen
1930 let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
1931 drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::CodegenDone::<B> {
1937 pub fn submit_pre_lto_module_to_llvm<B: ExtraBackendMethods>(
1939 tcx: TyCtxt<'_, '_>,
1940 module: CachedModuleCodegen
1942 let filename = pre_lto_bitcode_filename(&module.name);
1943 let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
1944 let file = fs::File::open(&bc_path).unwrap_or_else(|e| {
1945 panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e)
1949 memmap::Mmap::map(&file).unwrap_or_else(|e| {
1950 panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
1953 // Schedule the module to be loaded
1954 drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::AddImportOnlyModule::<B> {
1955 module_data: SerializedModule::FromUncompressedFile(mmap),
1956 work_product: module.source,
1960 pub fn pre_lto_bitcode_filename(module_name: &str) -> String {
1961 format!("{}.{}", module_name, PRE_LTO_BC_EXT)
1964 fn msvc_imps_needed(tcx: TyCtxt<'_, '_>) -> bool {
1965 // This should never be true (because it's not supported). If it is true,
1966 // something is wrong with commandline arg validation.
1967 assert!(!(tcx.sess.opts.cg.linker_plugin_lto.enabled() &&
1968 tcx.sess.target.target.options.is_like_msvc &&
1969 tcx.sess.opts.cg.prefer_dynamic));
1971 tcx.sess.target.target.options.is_like_msvc &&
1972 tcx.sess.crate_types.borrow().iter().any(|ct| *ct == config::CrateType::Rlib) &&
1973 // ThinLTO can't handle this workaround in all cases, so we don't
1974 // emit the `__imp_` symbols. Instead we make them unnecessary by disallowing
1975 // dynamic linking when linker plugin LTO is enabled.
1976 !tcx.sess.opts.cg.linker_plugin_lto.enabled()