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, PgoGenerate};
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: PgoGenerate,
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: PgoGenerate::Disabled,
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_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 debuginfo: config::DebugInfo,
253 // Number of cgus excluding the allocator/metadata modules
254 pub total_cgus: usize,
255 // Handler to use for diagnostics produced during codegen.
256 pub diag_emitter: SharedEmitter,
257 // LLVM passes added by plugins.
258 pub plugin_passes: Vec<String>,
259 // LLVM optimizations for which we want to print remarks.
261 // Worker thread number
263 // The incremental compilation session directory, or None if we are not
264 // compiling incrementally
265 pub incr_comp_session_dir: Option<PathBuf>,
266 // Used to update CGU re-use information during the thinlto phase.
267 pub cgu_reuse_tracker: CguReuseTracker,
268 // Channel back to the main control thread to send messages to
269 pub coordinator_send: Sender<Box<dyn Any + Send>>,
270 // The assembler command if no_integrated_as option is enabled, None otherwise
271 pub assembler_cmd: Option<Arc<AssemblerCommand>>
274 impl<B: WriteBackendMethods> CodegenContext<B> {
275 pub fn create_diag_handler(&self) -> Handler {
276 Handler::with_emitter(true, None, Box::new(self.diag_emitter.clone()))
279 pub fn config(&self, kind: ModuleKind) -> &ModuleConfig {
281 ModuleKind::Regular => &self.regular_module_config,
282 ModuleKind::Metadata => &self.metadata_module_config,
283 ModuleKind::Allocator => &self.allocator_module_config,
289 fn profiler_active<F: FnOnce(&SelfProfiler) -> ()>(&self, f: F) {
290 match &self.profiler {
291 None => bug!("profiler_active() called but there was no profiler active"),
299 pub fn profile<F: FnOnce(&SelfProfiler) -> ()>(&self, f: F) {
300 if unlikely!(self.profiler.is_some()) {
301 self.profiler_active(f)
305 pub fn profile_activity(
307 label: impl Into<Cow<'static, str>>,
308 ) -> ProfileGenericActivityTimer {
309 ProfileGenericActivityTimer::start(self.profiler.clone(), label.into())
313 fn generate_lto_work<B: ExtraBackendMethods>(
314 cgcx: &CodegenContext<B>,
315 needs_fat_lto: Vec<FatLTOInput<B>>,
316 needs_thin_lto: Vec<(String, B::ThinBuffer)>,
317 import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>
318 ) -> Vec<(WorkItem<B>, u64)> {
319 cgcx.profile(|p| p.start_activity("codegen_run_lto"));
321 let (lto_modules, copy_jobs) = if !needs_fat_lto.is_empty() {
322 assert!(needs_thin_lto.is_empty());
323 let lto_module = B::run_fat_lto(
328 .unwrap_or_else(|e| e.raise());
329 (vec![lto_module], vec![])
331 assert!(needs_fat_lto.is_empty());
332 B::run_thin_lto(cgcx, needs_thin_lto, import_only_modules)
333 .unwrap_or_else(|e| e.raise())
336 let result = lto_modules.into_iter().map(|module| {
337 let cost = module.cost();
338 (WorkItem::LTO(module), cost)
339 }).chain(copy_jobs.into_iter().map(|wp| {
340 (WorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
341 name: wp.cgu_name.clone(),
346 cgcx.profile(|p| p.end_activity("codegen_run_lto"));
351 pub struct CompiledModules {
352 pub modules: Vec<CompiledModule>,
353 pub metadata_module: Option<CompiledModule>,
354 pub allocator_module: Option<CompiledModule>,
357 fn need_crate_bitcode_for_rlib(sess: &Session) -> bool {
358 sess.crate_types.borrow().contains(&config::CrateType::Rlib) &&
359 sess.opts.output_types.contains_key(&OutputType::Exe)
362 fn need_pre_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
363 if sess.opts.incremental.is_none() {
371 Lto::ThinLocal => true,
375 pub fn start_async_codegen<B: ExtraBackendMethods>(
377 tcx: TyCtxt<'_, '_, '_>,
378 metadata: EncodedMetadata,
379 coordinator_receive: Receiver<Box<dyn Any + Send>>,
381 ) -> OngoingCodegen<B> {
383 let crate_name = tcx.crate_name(LOCAL_CRATE);
384 let crate_hash = tcx.crate_hash(LOCAL_CRATE);
385 let no_builtins = attr::contains_name(&tcx.hir().krate().attrs, sym::no_builtins);
386 let subsystem = attr::first_attr_value_str_by_name(&tcx.hir().krate().attrs,
387 sym::windows_subsystem);
388 let windows_subsystem = subsystem.map(|subsystem| {
389 if subsystem != sym::windows && subsystem != sym::console {
390 tcx.sess.fatal(&format!("invalid windows subsystem `{}`, only \
391 `windows` and `console` are allowed",
394 subsystem.to_string()
397 let linker_info = LinkerInfo::new(tcx);
398 let crate_info = CrateInfo::new(tcx);
400 // Figure out what we actually need to build.
401 let mut modules_config = ModuleConfig::new(sess.opts.cg.passes.clone());
402 let mut metadata_config = ModuleConfig::new(vec![]);
403 let mut allocator_config = ModuleConfig::new(vec![]);
405 if let Some(ref sanitizer) = sess.opts.debugging_opts.sanitizer {
407 Sanitizer::Address => {
408 modules_config.passes.push("asan".to_owned());
409 modules_config.passes.push("asan-module".to_owned());
411 Sanitizer::Memory => {
412 modules_config.passes.push("msan".to_owned())
414 Sanitizer::Thread => {
415 modules_config.passes.push("tsan".to_owned())
421 if sess.opts.debugging_opts.profile {
422 modules_config.passes.push("insert-gcov-profiling".to_owned())
425 modules_config.pgo_gen = sess.opts.debugging_opts.pgo_gen.clone();
426 modules_config.pgo_use = sess.opts.debugging_opts.pgo_use.clone();
428 modules_config.opt_level = Some(sess.opts.optimize);
429 modules_config.opt_size = Some(sess.opts.optimize);
431 // Save all versions of the bytecode if we're saving our temporaries.
432 if sess.opts.cg.save_temps {
433 modules_config.emit_no_opt_bc = true;
434 modules_config.emit_pre_lto_bc = true;
435 modules_config.emit_bc = true;
436 modules_config.emit_lto_bc = true;
437 metadata_config.emit_bc = true;
438 allocator_config.emit_bc = true;
441 // Emit compressed bitcode files for the crate if we're emitting an rlib.
442 // Whenever an rlib is created, the bitcode is inserted into the archive in
443 // order to allow LTO against it.
444 if need_crate_bitcode_for_rlib(sess) {
445 modules_config.emit_bc_compressed = true;
446 allocator_config.emit_bc_compressed = true;
449 modules_config.emit_pre_lto_bc =
450 need_pre_lto_bitcode_for_incr_comp(sess);
452 modules_config.no_integrated_as = tcx.sess.opts.cg.no_integrated_as ||
453 tcx.sess.target.target.options.no_integrated_as;
455 for output_type in sess.opts.output_types.keys() {
457 OutputType::Bitcode => { modules_config.emit_bc = true; }
458 OutputType::LlvmAssembly => { modules_config.emit_ir = true; }
459 OutputType::Assembly => {
460 modules_config.emit_asm = true;
461 // If we're not using the LLVM assembler, this function
462 // could be invoked specially with output_type_assembly, so
463 // in this case we still want the metadata object file.
464 if !sess.opts.output_types.contains_key(&OutputType::Assembly) {
465 metadata_config.emit_obj = true;
466 allocator_config.emit_obj = true;
469 OutputType::Object => { modules_config.emit_obj = true; }
470 OutputType::Metadata => { metadata_config.emit_obj = true; }
472 modules_config.emit_obj = true;
473 metadata_config.emit_obj = true;
474 allocator_config.emit_obj = true;
476 OutputType::Mir => {}
477 OutputType::DepInfo => {}
481 modules_config.set_flags(sess, no_builtins);
482 metadata_config.set_flags(sess, no_builtins);
483 allocator_config.set_flags(sess, no_builtins);
485 // Exclude metadata and allocator modules from time_passes output, since
486 // they throw off the "LLVM passes" measurement.
487 metadata_config.time_passes = false;
488 allocator_config.time_passes = false;
490 let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
491 let (codegen_worker_send, codegen_worker_receive) = channel();
493 let coordinator_thread = start_executing_work(backend.clone(),
500 sess.jobserver.clone(),
501 Arc::new(modules_config),
502 Arc::new(metadata_config),
503 Arc::new(allocator_config));
514 coordinator_send: tcx.tx_to_llvm_workers.lock().clone(),
515 codegen_worker_receive,
517 future: coordinator_thread,
518 output_filenames: tcx.output_filenames(LOCAL_CRATE),
522 fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
524 compiled_modules: &CompiledModules,
525 ) -> FxHashMap<WorkProductId, WorkProduct> {
526 let mut work_products = FxHashMap::default();
528 if sess.opts.incremental.is_none() {
529 return work_products;
532 for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
533 let mut files = vec![];
535 if let Some(ref path) = module.object {
536 files.push((WorkProductFileKind::Object, path.clone()));
538 if let Some(ref path) = module.bytecode {
539 files.push((WorkProductFileKind::Bytecode, path.clone()));
541 if let Some(ref path) = module.bytecode_compressed {
542 files.push((WorkProductFileKind::BytecodeCompressed, path.clone()));
545 if let Some((id, product)) =
546 copy_cgu_workproducts_to_incr_comp_cache_dir(sess, &module.name, &files) {
547 work_products.insert(id, product);
554 fn produce_final_output_artifacts(sess: &Session,
555 compiled_modules: &CompiledModules,
556 crate_output: &OutputFilenames) {
557 let mut user_wants_bitcode = false;
558 let mut user_wants_objects = false;
560 // Produce final compile outputs.
561 let copy_gracefully = |from: &Path, to: &Path| {
562 if let Err(e) = fs::copy(from, to) {
563 sess.err(&format!("could not copy {:?} to {:?}: {}", from, to, e));
567 let copy_if_one_unit = |output_type: OutputType,
568 keep_numbered: bool| {
569 if compiled_modules.modules.len() == 1 {
570 // 1) Only one codegen unit. In this case it's no difficulty
571 // to copy `foo.0.x` to `foo.x`.
572 let module_name = Some(&compiled_modules.modules[0].name[..]);
573 let path = crate_output.temp_path(output_type, module_name);
574 copy_gracefully(&path,
575 &crate_output.path(output_type));
576 if !sess.opts.cg.save_temps && !keep_numbered {
577 // The user just wants `foo.x`, not `foo.#module-name#.x`.
581 let ext = crate_output.temp_path(output_type, None)
588 if crate_output.outputs.contains_key(&output_type) {
589 // 2) Multiple codegen units, with `--emit foo=some_name`. We have
590 // no good solution for this case, so warn the user.
591 sess.warn(&format!("ignoring emit path because multiple .{} files \
592 were produced", ext));
593 } else if crate_output.single_output_file.is_some() {
594 // 3) Multiple codegen units, with `-o some_name`. We have
595 // no good solution for this case, so warn the user.
596 sess.warn(&format!("ignoring -o because multiple .{} files \
597 were produced", ext));
599 // 4) Multiple codegen units, but no explicit name. We
600 // just leave the `foo.0.x` files in place.
601 // (We don't have to do any work in this case.)
606 // Flag to indicate whether the user explicitly requested bitcode.
607 // Otherwise, we produced it only as a temporary output, and will need
609 for output_type in crate_output.outputs.keys() {
611 OutputType::Bitcode => {
612 user_wants_bitcode = true;
613 // Copy to .bc, but always keep the .0.bc. There is a later
614 // check to figure out if we should delete .0.bc files, or keep
615 // them for making an rlib.
616 copy_if_one_unit(OutputType::Bitcode, true);
618 OutputType::LlvmAssembly => {
619 copy_if_one_unit(OutputType::LlvmAssembly, false);
621 OutputType::Assembly => {
622 copy_if_one_unit(OutputType::Assembly, false);
624 OutputType::Object => {
625 user_wants_objects = true;
626 copy_if_one_unit(OutputType::Object, true);
629 OutputType::Metadata |
631 OutputType::DepInfo => {}
635 // Clean up unwanted temporary files.
637 // We create the following files by default:
638 // - #crate#.#module-name#.bc
639 // - #crate#.#module-name#.o
640 // - #crate#.crate.metadata.bc
641 // - #crate#.crate.metadata.o
642 // - #crate#.o (linked from crate.##.o)
643 // - #crate#.bc (copied from crate.##.bc)
644 // We may create additional files if requested by the user (through
645 // `-C save-temps` or `--emit=` flags).
647 if !sess.opts.cg.save_temps {
648 // Remove the temporary .#module-name#.o objects. If the user didn't
649 // explicitly request bitcode (with --emit=bc), and the bitcode is not
650 // needed for building an rlib, then we must remove .#module-name#.bc as
653 // Specific rules for keeping .#module-name#.bc:
654 // - If the user requested bitcode (`user_wants_bitcode`), and
655 // codegen_units > 1, then keep it.
656 // - If the user requested bitcode but codegen_units == 1, then we
657 // can toss .#module-name#.bc because we copied it to .bc earlier.
658 // - If we're not building an rlib and the user didn't request
659 // bitcode, then delete .#module-name#.bc.
660 // If you change how this works, also update back::link::link_rlib,
661 // where .#module-name#.bc files are (maybe) deleted after making an
663 let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
665 let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units() > 1;
667 let keep_numbered_objects = needs_crate_object ||
668 (user_wants_objects && sess.codegen_units() > 1);
670 for module in compiled_modules.modules.iter() {
671 if let Some(ref path) = module.object {
672 if !keep_numbered_objects {
677 if let Some(ref path) = module.bytecode {
678 if !keep_numbered_bitcode {
684 if !user_wants_bitcode {
685 if let Some(ref metadata_module) = compiled_modules.metadata_module {
686 if let Some(ref path) = metadata_module.bytecode {
691 if let Some(ref allocator_module) = compiled_modules.allocator_module {
692 if let Some(ref path) = allocator_module.bytecode {
699 // We leave the following files around by default:
701 // - #crate#.crate.metadata.o
703 // These are used in linking steps and will be cleaned up afterward.
706 pub fn dump_incremental_data(_codegen_results: &CodegenResults) {
707 // FIXME(mw): This does not work at the moment because the situation has
708 // become more complicated due to incremental LTO. Now a CGU
709 // can have more than two caching states.
710 // println!("[incremental] Re-using {} out of {} modules",
711 // codegen_results.modules.iter().filter(|m| m.pre_existing).count(),
712 // codegen_results.modules.len());
715 pub enum WorkItem<B: WriteBackendMethods> {
716 /// Optimize a newly codegened, totally unoptimized module.
717 Optimize(ModuleCodegen<B::Module>),
718 /// Copy the post-LTO artifacts from the incremental cache to the output
720 CopyPostLtoArtifacts(CachedModuleCodegen),
721 /// Performs (Thin)LTO on the given module.
722 LTO(lto::LtoModuleCodegen<B>),
725 impl<B: WriteBackendMethods> WorkItem<B> {
726 pub fn module_kind(&self) -> ModuleKind {
728 WorkItem::Optimize(ref m) => m.kind,
729 WorkItem::CopyPostLtoArtifacts(_) |
730 WorkItem::LTO(_) => ModuleKind::Regular,
734 pub fn name(&self) -> String {
736 WorkItem::Optimize(ref m) => format!("optimize: {}", m.name),
737 WorkItem::CopyPostLtoArtifacts(ref m) => format!("copy post LTO artifacts: {}", m.name),
738 WorkItem::LTO(ref m) => format!("lto: {}", m.name()),
743 enum WorkItemResult<B: WriteBackendMethods> {
744 Compiled(CompiledModule),
745 NeedsFatLTO(FatLTOInput<B>),
746 NeedsThinLTO(String, B::ThinBuffer),
749 pub enum FatLTOInput<B: WriteBackendMethods> {
752 buffer: B::ModuleBuffer,
754 InMemory(ModuleCodegen<B::Module>),
757 fn execute_work_item<B: ExtraBackendMethods>(
758 cgcx: &CodegenContext<B>,
759 work_item: WorkItem<B>,
760 ) -> Result<WorkItemResult<B>, FatalError> {
761 let module_config = cgcx.config(work_item.module_kind());
764 WorkItem::Optimize(module) => {
765 execute_optimize_work_item(cgcx, module, module_config)
767 WorkItem::CopyPostLtoArtifacts(module) => {
768 execute_copy_from_cache_work_item(cgcx, module, module_config)
770 WorkItem::LTO(module) => {
771 execute_lto_work_item(cgcx, module, module_config)
776 // Actual LTO type we end up chosing based on multiple factors.
777 enum ComputedLtoType {
783 fn execute_optimize_work_item<B: ExtraBackendMethods>(
784 cgcx: &CodegenContext<B>,
785 module: ModuleCodegen<B::Module>,
786 module_config: &ModuleConfig,
787 ) -> Result<WorkItemResult<B>, FatalError> {
788 let diag_handler = cgcx.create_diag_handler();
791 B::optimize(cgcx, &diag_handler, &module, module_config)?;
794 // After we've done the initial round of optimizations we need to
795 // decide whether to synchronously codegen this module or ship it
796 // back to the coordinator thread for further LTO processing (which
797 // has to wait for all the initial modules to be optimized).
799 // If the linker does LTO, we don't have to do it. Note that we
800 // keep doing full LTO, if it is requested, as not to break the
801 // assumption that the output will be a single module.
802 let linker_does_lto = cgcx.opts.cg.linker_plugin_lto.enabled();
804 // When we're automatically doing ThinLTO for multi-codegen-unit
805 // builds we don't actually want to LTO the allocator modules if
806 // it shows up. This is due to various linker shenanigans that
807 // we'll encounter later.
808 let is_allocator = module.kind == ModuleKind::Allocator;
810 // We ignore a request for full crate grath LTO if the cate type
811 // is only an rlib, as there is no full crate graph to process,
812 // that'll happen later.
814 // This use case currently comes up primarily for targets that
815 // require LTO so the request for LTO is always unconditionally
816 // passed down to the backend, but we don't actually want to do
817 // anything about it yet until we've got a final product.
818 let is_rlib = cgcx.crate_types.len() == 1
819 && cgcx.crate_types[0] == config::CrateType::Rlib;
821 // Metadata modules never participate in LTO regardless of the lto
823 let lto_type = if module.kind == ModuleKind::Metadata {
827 Lto::ThinLocal if !linker_does_lto && !is_allocator
828 => ComputedLtoType::Thin,
829 Lto::Thin if !linker_does_lto && !is_rlib
830 => ComputedLtoType::Thin,
831 Lto::Fat if !is_rlib => ComputedLtoType::Fat,
832 _ => ComputedLtoType::No,
836 // If we're doing some form of incremental LTO then we need to be sure to
837 // save our module to disk first.
838 let bitcode = if cgcx.config(module.kind).emit_pre_lto_bc {
839 let filename = pre_lto_bitcode_filename(&module.name);
840 cgcx.incr_comp_session_dir.as_ref().map(|path| path.join(&filename))
846 ComputedLtoType::No => {
847 let module = unsafe {
848 B::codegen(cgcx, &diag_handler, module, module_config)?
850 WorkItemResult::Compiled(module)
852 ComputedLtoType::Thin => {
853 let (name, thin_buffer) = B::prepare_thin(module);
854 if let Some(path) = bitcode {
855 fs::write(&path, thin_buffer.data()).unwrap_or_else(|e| {
856 panic!("Error writing pre-lto-bitcode file `{}`: {}",
861 WorkItemResult::NeedsThinLTO(name, thin_buffer)
863 ComputedLtoType::Fat => {
866 let (name, buffer) = B::serialize_module(module);
867 fs::write(&path, buffer.data()).unwrap_or_else(|e| {
868 panic!("Error writing pre-lto-bitcode file `{}`: {}",
872 WorkItemResult::NeedsFatLTO(FatLTOInput::Serialized { name, buffer })
874 None => WorkItemResult::NeedsFatLTO(FatLTOInput::InMemory(module)),
880 fn execute_copy_from_cache_work_item<B: ExtraBackendMethods>(
881 cgcx: &CodegenContext<B>,
882 module: CachedModuleCodegen,
883 module_config: &ModuleConfig,
884 ) -> Result<WorkItemResult<B>, FatalError> {
885 let incr_comp_session_dir = cgcx.incr_comp_session_dir
888 let mut object = None;
889 let mut bytecode = None;
890 let mut bytecode_compressed = None;
891 for (kind, saved_file) in &module.source.saved_files {
892 let obj_out = match kind {
893 WorkProductFileKind::Object => {
894 let path = cgcx.output_filenames.temp_path(OutputType::Object,
896 object = Some(path.clone());
899 WorkProductFileKind::Bytecode => {
900 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode,
902 bytecode = Some(path.clone());
905 WorkProductFileKind::BytecodeCompressed => {
906 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode,
908 .with_extension(RLIB_BYTECODE_EXTENSION);
909 bytecode_compressed = Some(path.clone());
913 let source_file = in_incr_comp_dir(&incr_comp_session_dir,
915 debug!("copying pre-existing module `{}` from {:?} to {}",
919 if let Err(err) = link_or_copy(&source_file, &obj_out) {
920 let diag_handler = cgcx.create_diag_handler();
921 diag_handler.err(&format!("unable to copy {} to {}: {}",
922 source_file.display(),
928 assert_eq!(object.is_some(), module_config.emit_obj);
929 assert_eq!(bytecode.is_some(), module_config.emit_bc);
930 assert_eq!(bytecode_compressed.is_some(), module_config.emit_bc_compressed);
932 Ok(WorkItemResult::Compiled(CompiledModule {
934 kind: ModuleKind::Regular,
941 fn execute_lto_work_item<B: ExtraBackendMethods>(
942 cgcx: &CodegenContext<B>,
943 mut module: lto::LtoModuleCodegen<B>,
944 module_config: &ModuleConfig,
945 ) -> Result<WorkItemResult<B>, FatalError> {
946 let diag_handler = cgcx.create_diag_handler();
949 let module = module.optimize(cgcx)?;
950 let module = B::codegen(cgcx, &diag_handler, module, module_config)?;
951 Ok(WorkItemResult::Compiled(module))
955 pub enum Message<B: WriteBackendMethods> {
956 Token(io::Result<Acquired>),
958 result: FatLTOInput<B>,
963 thin_buffer: B::ThinBuffer,
967 result: Result<CompiledModule, ()>,
971 llvm_work_item: WorkItem<B>,
974 AddImportOnlyModule {
975 module_data: SerializedModule<B::ModuleBuffer>,
976 work_product: WorkProduct,
985 code: Option<DiagnosticId>,
989 #[derive(PartialEq, Clone, Copy, Debug)]
990 enum MainThreadWorkerState {
996 fn start_executing_work<B: ExtraBackendMethods>(
998 tcx: TyCtxt<'_, '_, '_>,
999 crate_info: &CrateInfo,
1000 shared_emitter: SharedEmitter,
1001 codegen_worker_send: Sender<Message<B>>,
1002 coordinator_receive: Receiver<Box<dyn Any + Send>>,
1005 modules_config: Arc<ModuleConfig>,
1006 metadata_config: Arc<ModuleConfig>,
1007 allocator_config: Arc<ModuleConfig>
1008 ) -> thread::JoinHandle<Result<CompiledModules, ()>> {
1009 let coordinator_send = tcx.tx_to_llvm_workers.lock().clone();
1010 let sess = tcx.sess;
1012 // Compute the set of symbols we need to retain when doing LTO (if we need to)
1013 let exported_symbols = {
1014 let mut exported_symbols = FxHashMap::default();
1016 let copy_symbols = |cnum| {
1017 let symbols = tcx.exported_symbols(cnum)
1019 .map(|&(s, lvl)| (s.symbol_name(tcx).to_string(), lvl))
1027 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1028 Some(Arc::new(exported_symbols))
1030 Lto::Fat | Lto::Thin => {
1031 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1032 for &cnum in tcx.crates().iter() {
1033 exported_symbols.insert(cnum, copy_symbols(cnum));
1035 Some(Arc::new(exported_symbols))
1040 // First up, convert our jobserver into a helper thread so we can use normal
1041 // mpsc channels to manage our messages and such.
1042 // After we've requested tokens then we'll, when we can,
1043 // get tokens on `coordinator_receive` which will
1044 // get managed in the main loop below.
1045 let coordinator_send2 = coordinator_send.clone();
1046 let helper = jobserver.into_helper_thread(move |token| {
1047 drop(coordinator_send2.send(Box::new(Message::Token::<B>(token))));
1048 }).expect("failed to spawn helper thread");
1050 let mut each_linked_rlib_for_lto = Vec::new();
1051 drop(link::each_linked_rlib(sess, crate_info, &mut |cnum, path| {
1052 if link::ignored_for_lto(sess, crate_info, cnum) {
1055 each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
1058 let assembler_cmd = if modules_config.no_integrated_as {
1059 // HACK: currently we use linker (gcc) as our assembler
1060 let (linker, flavor) = link::linker_and_flavor(sess);
1062 let (name, mut cmd) = get_linker(sess, &linker, flavor);
1063 cmd.args(&sess.target.target.options.asm_args);
1064 Some(Arc::new(AssemblerCommand {
1072 let ol = if tcx.sess.opts.debugging_opts.no_codegen
1073 || !tcx.sess.opts.output_types.should_codegen() {
1074 // If we know that we won’t be doing codegen, create target machines without optimisation.
1075 config::OptLevel::No
1077 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_extended(),
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 Ok(CompiledModules {
1570 modules: compiled_modules,
1571 metadata_module: compiled_metadata_module,
1572 allocator_module: compiled_allocator_module,
1576 // A heuristic that determines if we have enough LLVM WorkItems in the
1577 // queue so that the main thread can do LLVM work instead of codegen
1578 fn queue_full_enough(items_in_queue: usize,
1579 workers_running: usize,
1580 max_workers: usize) -> bool {
1582 items_in_queue > 0 &&
1583 items_in_queue >= max_workers.saturating_sub(workers_running / 2)
1586 fn maybe_start_llvm_timer(config: &ModuleConfig,
1587 llvm_start_time: &mut Option<Instant>) {
1588 // We keep track of the -Ztime-passes output manually,
1589 // since the closure-based interface does not fit well here.
1590 if config.time_passes {
1591 if llvm_start_time.is_none() {
1592 *llvm_start_time = Some(Instant::now());
1598 pub const CODEGEN_WORKER_ID: usize = ::std::usize::MAX;
1600 fn spawn_work<B: ExtraBackendMethods>(
1601 cgcx: CodegenContext<B>,
1604 let depth = time_depth();
1606 thread::spawn(move || {
1607 set_time_depth(depth);
1609 // Set up a destructor which will fire off a message that we're done as
1611 struct Bomb<B: ExtraBackendMethods> {
1612 coordinator_send: Sender<Box<dyn Any + Send>>,
1613 result: Option<WorkItemResult<B>>,
1616 impl<B: ExtraBackendMethods> Drop for Bomb<B> {
1617 fn drop(&mut self) {
1618 let worker_id = self.worker_id;
1619 let msg = match self.result.take() {
1620 Some(WorkItemResult::Compiled(m)) => {
1621 Message::Done::<B> { result: Ok(m), worker_id }
1623 Some(WorkItemResult::NeedsFatLTO(m)) => {
1624 Message::NeedsFatLTO::<B> { result: m, worker_id }
1626 Some(WorkItemResult::NeedsThinLTO(name, thin_buffer)) => {
1627 Message::NeedsThinLTO::<B> { name, thin_buffer, worker_id }
1629 None => Message::Done::<B> { result: Err(()), worker_id }
1631 drop(self.coordinator_send.send(Box::new(msg)));
1635 let mut bomb = Bomb::<B> {
1636 coordinator_send: cgcx.coordinator_send.clone(),
1638 worker_id: cgcx.worker,
1641 // Execute the work itself, and if it finishes successfully then flag
1642 // ourselves as a success as well.
1644 // Note that we ignore any `FatalError` coming out of `execute_work_item`,
1645 // as a diagnostic was already sent off to the main thread - just
1646 // surface that there was an error in this worker.
1648 let label = work.name();
1649 cgcx.profile(|p| p.start_activity(label.clone()));
1650 let result = execute_work_item(&cgcx, work).ok();
1651 cgcx.profile(|p| p.end_activity(label));
1658 pub fn run_assembler<B: ExtraBackendMethods>(
1659 cgcx: &CodegenContext<B>,
1664 let assembler = cgcx.assembler_cmd
1666 .expect("cgcx.assembler_cmd is missing?");
1668 let pname = &assembler.name;
1669 let mut cmd = assembler.cmd.clone();
1670 cmd.arg("-c").arg("-o").arg(object).arg(assembly);
1671 debug!("{:?}", cmd);
1673 match cmd.output() {
1675 if !prog.status.success() {
1676 let mut note = prog.stderr.clone();
1677 note.extend_from_slice(&prog.stdout);
1679 handler.struct_err(&format!("linking with `{}` failed: {}",
1682 .note(&format!("{:?}", &cmd))
1683 .note(str::from_utf8(¬e[..]).unwrap())
1685 handler.abort_if_errors();
1689 handler.err(&format!("could not exec the linker `{}`: {}", pname.display(), e));
1690 handler.abort_if_errors();
1696 enum SharedEmitterMessage {
1697 Diagnostic(Diagnostic),
1698 InlineAsmError(u32, String),
1704 pub struct SharedEmitter {
1705 sender: Sender<SharedEmitterMessage>,
1708 pub struct SharedEmitterMain {
1709 receiver: Receiver<SharedEmitterMessage>,
1712 impl SharedEmitter {
1713 pub fn new() -> (SharedEmitter, SharedEmitterMain) {
1714 let (sender, receiver) = channel();
1716 (SharedEmitter { sender }, SharedEmitterMain { receiver })
1719 pub fn inline_asm_error(&self, cookie: u32, msg: String) {
1720 drop(self.sender.send(SharedEmitterMessage::InlineAsmError(cookie, msg)));
1723 pub fn fatal(&self, msg: &str) {
1724 drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1728 impl Emitter for SharedEmitter {
1729 fn emit_diagnostic(&mut self, db: &DiagnosticBuilder<'_>) {
1730 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1732 code: db.code.clone(),
1735 for child in &db.children {
1736 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1737 msg: child.message(),
1742 drop(self.sender.send(SharedEmitterMessage::AbortIfErrors));
1746 impl SharedEmitterMain {
1747 pub fn check(&self, sess: &Session, blocking: bool) {
1749 let message = if blocking {
1750 match self.receiver.recv() {
1751 Ok(message) => Ok(message),
1755 match self.receiver.try_recv() {
1756 Ok(message) => Ok(message),
1762 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
1763 let handler = sess.diagnostic();
1766 handler.emit_with_code(&MultiSpan::new(),
1772 handler.emit(&MultiSpan::new(),
1778 Ok(SharedEmitterMessage::InlineAsmError(cookie, msg)) => {
1779 match Mark::from_u32(cookie).expn_info() {
1780 Some(ei) => sess.span_err(ei.call_site, &msg),
1781 None => sess.err(&msg),
1784 Ok(SharedEmitterMessage::AbortIfErrors) => {
1785 sess.abort_if_errors();
1787 Ok(SharedEmitterMessage::Fatal(msg)) => {
1799 pub struct OngoingCodegen<B: ExtraBackendMethods> {
1801 pub crate_name: Symbol,
1802 pub crate_hash: Svh,
1803 pub metadata: EncodedMetadata,
1804 pub windows_subsystem: Option<String>,
1805 pub linker_info: LinkerInfo,
1806 pub crate_info: CrateInfo,
1807 pub coordinator_send: Sender<Box<dyn Any + Send>>,
1808 pub codegen_worker_receive: Receiver<Message<B>>,
1809 pub shared_emitter_main: SharedEmitterMain,
1810 pub future: thread::JoinHandle<Result<CompiledModules, ()>>,
1811 pub output_filenames: Arc<OutputFilenames>,
1814 impl<B: ExtraBackendMethods> OngoingCodegen<B> {
1818 ) -> (CodegenResults, FxHashMap<WorkProductId, WorkProduct>) {
1819 self.shared_emitter_main.check(sess, true);
1820 let compiled_modules = match self.future.join() {
1821 Ok(Ok(compiled_modules)) => compiled_modules,
1823 sess.abort_if_errors();
1824 panic!("expected abort due to worker thread errors")
1827 bug!("panic during codegen/LLVM phase");
1831 sess.cgu_reuse_tracker.check_expected_reuse(sess);
1833 sess.abort_if_errors();
1836 copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess,
1838 produce_final_output_artifacts(sess,
1840 &self.output_filenames);
1842 // FIXME: time_llvm_passes support - does this use a global context or
1844 if sess.codegen_units() == 1 && sess.time_llvm_passes() {
1845 self.backend.print_pass_timings()
1849 crate_name: self.crate_name,
1850 crate_hash: self.crate_hash,
1851 metadata: self.metadata,
1852 windows_subsystem: self.windows_subsystem,
1853 linker_info: self.linker_info,
1854 crate_info: self.crate_info,
1856 modules: compiled_modules.modules,
1857 allocator_module: compiled_modules.allocator_module,
1858 metadata_module: compiled_modules.metadata_module,
1862 pub fn submit_pre_codegened_module_to_llvm(&self,
1863 tcx: TyCtxt<'_, '_, '_>,
1864 module: ModuleCodegen<B::Module>) {
1865 self.wait_for_signal_to_codegen_item();
1866 self.check_for_errors(tcx.sess);
1868 // These are generally cheap and won't throw off scheduling.
1870 submit_codegened_module_to_llvm(&self.backend, tcx, module, cost);
1873 pub fn codegen_finished(&self, tcx: TyCtxt<'_, '_, '_>) {
1874 self.wait_for_signal_to_codegen_item();
1875 self.check_for_errors(tcx.sess);
1876 drop(self.coordinator_send.send(Box::new(Message::CodegenComplete::<B>)));
1879 /// Consumes this context indicating that codegen was entirely aborted, and
1880 /// we need to exit as quickly as possible.
1882 /// This method blocks the current thread until all worker threads have
1883 /// finished, and all worker threads should have exited or be real close to
1884 /// exiting at this point.
1885 pub fn codegen_aborted(self) {
1886 // Signal to the coordinator it should spawn no more work and start
1888 drop(self.coordinator_send.send(Box::new(Message::CodegenAborted::<B>)));
1889 drop(self.future.join());
1892 pub fn check_for_errors(&self, sess: &Session) {
1893 self.shared_emitter_main.check(sess, false);
1896 pub fn wait_for_signal_to_codegen_item(&self) {
1897 match self.codegen_worker_receive.recv() {
1898 Ok(Message::CodegenItem) => {
1901 Ok(_) => panic!("unexpected message"),
1903 // One of the LLVM threads must have panicked, fall through so
1904 // error handling can be reached.
1910 pub fn submit_codegened_module_to_llvm<B: ExtraBackendMethods>(
1912 tcx: TyCtxt<'_, '_, '_>,
1913 module: ModuleCodegen<B::Module>,
1916 let llvm_work_item = WorkItem::Optimize(module);
1917 drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::CodegenDone::<B> {
1923 pub fn submit_post_lto_module_to_llvm<B: ExtraBackendMethods>(
1925 tcx: TyCtxt<'_, '_, '_>,
1926 module: CachedModuleCodegen
1928 let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
1929 drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::CodegenDone::<B> {
1935 pub fn submit_pre_lto_module_to_llvm<B: ExtraBackendMethods>(
1937 tcx: TyCtxt<'_, '_, '_>,
1938 module: CachedModuleCodegen
1940 let filename = pre_lto_bitcode_filename(&module.name);
1941 let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
1942 let file = fs::File::open(&bc_path).unwrap_or_else(|e| {
1943 panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e)
1947 memmap::Mmap::map(&file).unwrap_or_else(|e| {
1948 panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
1951 // Schedule the module to be loaded
1952 drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::AddImportOnlyModule::<B> {
1953 module_data: SerializedModule::FromUncompressedFile(mmap),
1954 work_product: module.source,
1958 pub fn pre_lto_bitcode_filename(module_name: &str) -> String {
1959 format!("{}.{}", module_name, PRE_LTO_BC_EXT)
1962 fn msvc_imps_needed(tcx: TyCtxt<'_, '_, '_>) -> bool {
1963 // This should never be true (because it's not supported). If it is true,
1964 // something is wrong with commandline arg validation.
1965 assert!(!(tcx.sess.opts.cg.linker_plugin_lto.enabled() &&
1966 tcx.sess.target.target.options.is_like_msvc &&
1967 tcx.sess.opts.cg.prefer_dynamic));
1969 tcx.sess.target.target.options.is_like_msvc &&
1970 tcx.sess.crate_types.borrow().iter().any(|ct| *ct == config::CrateType::Rlib) &&
1971 // ThinLTO can't handle this workaround in all cases, so we don't
1972 // emit the `__imp_` symbols. Instead we make them unnecessary by disallowing
1973 // dynamic linking when linker plugin LTO is enabled.
1974 !tcx.sess.opts.cg.linker_plugin_lto.enabled()