1 use super::command::Command;
2 use super::link::{self, get_linker, remove};
3 use super::linker::LinkerInfo;
4 use super::lto::{self, SerializedModule};
5 use super::symbol_export::ExportedSymbols;
7 CachedModuleCodegen, CodegenResults, CompiledModule, CrateInfo, ModuleCodegen, ModuleKind,
8 RLIB_BYTECODE_EXTENSION,
12 use jobserver::{Acquired, Client};
13 use rustc::dep_graph::{WorkProduct, WorkProductFileKind, WorkProductId};
14 use rustc::hir::def_id::{CrateNum, LOCAL_CRATE};
15 use rustc::middle::cstore::EncodedMetadata;
16 use rustc::session::config::{
17 self, Lto, OutputFilenames, OutputType, Passes, Sanitizer, SwitchWithOptPath,
19 use rustc::session::Session;
20 use rustc::ty::TyCtxt;
21 use rustc::util::common::{print_time_passes_entry, set_time_depth, time_depth};
22 use rustc::util::nodemap::FxHashMap;
23 use rustc_data_structures::profiling::SelfProfilerRef;
24 use rustc_data_structures::svh::Svh;
25 use rustc_data_structures::sync::Lrc;
26 use rustc_errors::emitter::Emitter;
27 use rustc_errors::{DiagnosticId, FatalError, Handler, Level};
28 use rustc_fs_util::link_or_copy;
29 use rustc_incremental::{
30 copy_cgu_workproducts_to_incr_comp_cache_dir, in_incr_comp_dir, in_incr_comp_dir_sess,
32 use rustc_session::cgu_reuse_tracker::CguReuseTracker;
33 use rustc_span::hygiene::ExpnId;
34 use rustc_span::source_map::SourceMap;
35 use rustc_span::symbol::{sym, Symbol};
36 use rustc_target::spec::MergeFunctions;
43 use std::path::{Path, PathBuf};
45 use std::sync::mpsc::{channel, Receiver, Sender};
48 use std::time::Instant;
50 const PRE_LTO_BC_EXT: &str = "pre-lto.bc";
52 /// Module-specific configuration for `optimize_and_codegen`.
53 pub struct ModuleConfig {
54 /// Names of additional optimization passes to run.
55 pub passes: Vec<String>,
56 /// Some(level) to optimize at a certain level, or None to run
57 /// absolutely no optimizations (used for the metadata module).
58 pub opt_level: Option<config::OptLevel>,
60 /// Some(level) to optimize binary size, or None to not affect program size.
61 pub opt_size: Option<config::OptLevel>,
63 pub pgo_gen: SwitchWithOptPath,
64 pub pgo_use: Option<PathBuf>,
66 pub sanitizer: Option<Sanitizer>,
67 pub sanitizer_recover: Vec<Sanitizer>,
68 pub sanitizer_memory_track_origins: usize,
70 // Flags indicating which outputs to produce.
71 pub emit_pre_lto_bc: bool,
72 pub emit_no_opt_bc: bool,
74 pub emit_bc_compressed: bool,
75 pub emit_lto_bc: bool,
79 // Miscellaneous flags. These are mostly copied from command-line
81 pub verify_llvm_ir: bool,
82 pub no_prepopulate_passes: bool,
83 pub no_builtins: bool,
84 pub time_passes: bool,
85 pub vectorize_loop: bool,
86 pub vectorize_slp: bool,
87 pub merge_functions: bool,
88 pub inline_threshold: Option<usize>,
89 // Instead of creating an object file by doing LLVM codegen, just
90 // make the object file bitcode. Provides easy compatibility with
91 // emscripten's ecc compiler, when used as the linker.
92 pub obj_is_bitcode: bool,
93 pub no_integrated_as: bool,
94 pub embed_bitcode: bool,
95 pub embed_bitcode_marker: bool,
99 fn new(passes: Vec<String>) -> ModuleConfig {
105 pgo_gen: SwitchWithOptPath::Disabled,
109 sanitizer_recover: Default::default(),
110 sanitizer_memory_track_origins: 0,
112 emit_no_opt_bc: false,
113 emit_pre_lto_bc: false,
115 emit_bc_compressed: false,
120 obj_is_bitcode: false,
121 embed_bitcode: false,
122 embed_bitcode_marker: false,
123 no_integrated_as: false,
125 verify_llvm_ir: false,
126 no_prepopulate_passes: false,
129 vectorize_loop: false,
130 vectorize_slp: false,
131 merge_functions: false,
132 inline_threshold: None,
136 fn set_flags(&mut self, sess: &Session, no_builtins: bool) {
137 self.verify_llvm_ir = sess.verify_llvm_ir();
138 self.no_prepopulate_passes = sess.opts.cg.no_prepopulate_passes;
139 self.no_builtins = no_builtins || sess.target.target.options.no_builtins;
140 self.time_passes = sess.time_extended();
141 self.inline_threshold = sess.opts.cg.inline_threshold;
142 self.obj_is_bitcode =
143 sess.target.target.options.obj_is_bitcode || sess.opts.cg.linker_plugin_lto.enabled();
145 sess.target.target.options.embed_bitcode || sess.opts.debugging_opts.embed_bitcode;
147 match sess.opts.optimize {
148 config::OptLevel::No | config::OptLevel::Less => {
149 self.embed_bitcode_marker = embed_bitcode;
151 _ => self.embed_bitcode = embed_bitcode,
155 // Copy what clang does by turning on loop vectorization at O2 and
156 // slp vectorization at O3. Otherwise configure other optimization aspects
157 // of this pass manager builder.
158 self.vectorize_loop = !sess.opts.cg.no_vectorize_loops
159 && (sess.opts.optimize == config::OptLevel::Default
160 || sess.opts.optimize == config::OptLevel::Aggressive);
163 !sess.opts.cg.no_vectorize_slp && sess.opts.optimize == config::OptLevel::Aggressive;
165 // Some targets (namely, NVPTX) interact badly with the MergeFunctions
166 // pass. This is because MergeFunctions can generate new function calls
167 // which may interfere with the target calling convention; e.g. for the
168 // NVPTX target, PTX kernels should not call other PTX kernels.
169 // MergeFunctions can also be configured to generate aliases instead,
170 // but aliases are not supported by some backends (again, NVPTX).
171 // Therefore, allow targets to opt out of the MergeFunctions pass,
172 // but otherwise keep the pass enabled (at O2 and O3) since it can be
173 // useful for reducing code size.
174 self.merge_functions = match sess
178 .unwrap_or(sess.target.target.options.merge_functions)
180 MergeFunctions::Disabled => false,
181 MergeFunctions::Trampolines | MergeFunctions::Aliases => {
182 sess.opts.optimize == config::OptLevel::Default
183 || sess.opts.optimize == config::OptLevel::Aggressive
188 pub fn bitcode_needed(&self) -> bool {
189 self.emit_bc || self.obj_is_bitcode || self.emit_bc_compressed || self.embed_bitcode
193 /// Assembler name and command used by codegen when no_integrated_as is enabled
194 pub struct AssemblerCommand {
199 // HACK(eddyb) work around `#[derive]` producing wrong bounds for `Clone`.
200 pub struct TargetMachineFactory<B: WriteBackendMethods>(
201 pub Arc<dyn Fn() -> Result<B::TargetMachine, String> + Send + Sync>,
204 impl<B: WriteBackendMethods> Clone for TargetMachineFactory<B> {
205 fn clone(&self) -> Self {
206 TargetMachineFactory(self.0.clone())
210 /// Additional resources used by optimize_and_codegen (not module specific)
212 pub struct CodegenContext<B: WriteBackendMethods> {
213 // Resources needed when running LTO
215 pub time_passes: bool,
216 pub prof: SelfProfilerRef,
218 pub no_landing_pads: bool,
219 pub save_temps: bool,
220 pub fewer_names: bool,
221 pub exported_symbols: Option<Arc<ExportedSymbols>>,
222 pub opts: Arc<config::Options>,
223 pub crate_types: Vec<config::CrateType>,
224 pub each_linked_rlib_for_lto: Vec<(CrateNum, PathBuf)>,
225 pub output_filenames: Arc<OutputFilenames>,
226 pub regular_module_config: Arc<ModuleConfig>,
227 pub metadata_module_config: Arc<ModuleConfig>,
228 pub allocator_module_config: Arc<ModuleConfig>,
229 pub tm_factory: TargetMachineFactory<B>,
230 pub msvc_imps_needed: bool,
231 pub target_pointer_width: String,
232 pub target_arch: String,
233 pub debuginfo: config::DebugInfo,
235 // Number of cgus excluding the allocator/metadata modules
236 pub total_cgus: usize,
237 // Handler to use for diagnostics produced during codegen.
238 pub diag_emitter: SharedEmitter,
239 // LLVM optimizations for which we want to print remarks.
241 // Worker thread number
243 // The incremental compilation session directory, or None if we are not
244 // compiling incrementally
245 pub incr_comp_session_dir: Option<PathBuf>,
246 // Used to update CGU re-use information during the thinlto phase.
247 pub cgu_reuse_tracker: CguReuseTracker,
248 // Channel back to the main control thread to send messages to
249 pub coordinator_send: Sender<Box<dyn Any + Send>>,
250 // The assembler command if no_integrated_as option is enabled, None otherwise
251 pub assembler_cmd: Option<Arc<AssemblerCommand>>,
254 impl<B: WriteBackendMethods> CodegenContext<B> {
255 pub fn create_diag_handler(&self) -> Handler {
256 Handler::with_emitter(true, None, Box::new(self.diag_emitter.clone()))
259 pub fn config(&self, kind: ModuleKind) -> &ModuleConfig {
261 ModuleKind::Regular => &self.regular_module_config,
262 ModuleKind::Metadata => &self.metadata_module_config,
263 ModuleKind::Allocator => &self.allocator_module_config,
268 fn generate_lto_work<B: ExtraBackendMethods>(
269 cgcx: &CodegenContext<B>,
270 needs_fat_lto: Vec<FatLTOInput<B>>,
271 needs_thin_lto: Vec<(String, B::ThinBuffer)>,
272 import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>,
273 ) -> Vec<(WorkItem<B>, u64)> {
274 let _prof_timer = cgcx.prof.generic_activity("codegen_generate_lto_work");
276 let (lto_modules, copy_jobs) = if !needs_fat_lto.is_empty() {
277 assert!(needs_thin_lto.is_empty());
279 B::run_fat_lto(cgcx, needs_fat_lto, import_only_modules).unwrap_or_else(|e| e.raise());
280 (vec![lto_module], vec![])
282 assert!(needs_fat_lto.is_empty());
283 B::run_thin_lto(cgcx, needs_thin_lto, import_only_modules).unwrap_or_else(|e| e.raise())
286 let result = lto_modules
289 let cost = module.cost();
290 (WorkItem::LTO(module), cost)
292 .chain(copy_jobs.into_iter().map(|wp| {
294 WorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
295 name: wp.cgu_name.clone(),
306 pub struct CompiledModules {
307 pub modules: Vec<CompiledModule>,
308 pub metadata_module: Option<CompiledModule>,
309 pub allocator_module: Option<CompiledModule>,
312 fn need_crate_bitcode_for_rlib(sess: &Session) -> bool {
313 sess.crate_types.borrow().contains(&config::CrateType::Rlib)
314 && sess.opts.output_types.contains_key(&OutputType::Exe)
317 fn need_pre_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
318 if sess.opts.incremental.is_none() {
324 Lto::Fat | Lto::Thin | Lto::ThinLocal => true,
328 pub fn start_async_codegen<B: ExtraBackendMethods>(
331 metadata: EncodedMetadata,
333 ) -> OngoingCodegen<B> {
334 let (coordinator_send, coordinator_receive) = channel();
337 let crate_name = tcx.crate_name(LOCAL_CRATE);
338 let crate_hash = tcx.crate_hash(LOCAL_CRATE);
339 let no_builtins = attr::contains_name(&tcx.hir().krate().attrs, sym::no_builtins);
341 attr::first_attr_value_str_by_name(&tcx.hir().krate().attrs, sym::windows_subsystem);
342 let windows_subsystem = subsystem.map(|subsystem| {
343 if subsystem != sym::windows && subsystem != sym::console {
344 tcx.sess.fatal(&format!(
345 "invalid windows subsystem `{}`, only \
346 `windows` and `console` are allowed",
350 subsystem.to_string()
353 let linker_info = LinkerInfo::new(tcx);
354 let crate_info = CrateInfo::new(tcx);
356 // Figure out what we actually need to build.
357 let mut modules_config = ModuleConfig::new(sess.opts.cg.passes.clone());
358 let mut metadata_config = ModuleConfig::new(vec![]);
359 let mut allocator_config = ModuleConfig::new(vec![]);
361 if sess.opts.debugging_opts.profile {
362 modules_config.passes.push("insert-gcov-profiling".to_owned())
365 modules_config.pgo_gen = sess.opts.cg.profile_generate.clone();
366 modules_config.pgo_use = sess.opts.cg.profile_use.clone();
367 modules_config.sanitizer = sess.opts.debugging_opts.sanitizer.clone();
368 modules_config.sanitizer_recover = sess.opts.debugging_opts.sanitizer_recover.clone();
369 modules_config.sanitizer_memory_track_origins =
370 sess.opts.debugging_opts.sanitizer_memory_track_origins;
371 modules_config.opt_level = Some(sess.opts.optimize);
372 modules_config.opt_size = Some(sess.opts.optimize);
374 // Save all versions of the bytecode if we're saving our temporaries.
375 if sess.opts.cg.save_temps {
376 modules_config.emit_no_opt_bc = true;
377 modules_config.emit_pre_lto_bc = true;
378 modules_config.emit_bc = true;
379 modules_config.emit_lto_bc = true;
380 metadata_config.emit_bc = true;
381 allocator_config.emit_bc = true;
384 // Emit compressed bitcode files for the crate if we're emitting an rlib.
385 // Whenever an rlib is created, the bitcode is inserted into the archive in
386 // order to allow LTO against it.
387 if need_crate_bitcode_for_rlib(sess) {
388 modules_config.emit_bc_compressed = true;
389 allocator_config.emit_bc_compressed = true;
392 modules_config.emit_pre_lto_bc = need_pre_lto_bitcode_for_incr_comp(sess);
394 modules_config.no_integrated_as =
395 tcx.sess.opts.cg.no_integrated_as || tcx.sess.target.target.options.no_integrated_as;
397 for output_type in sess.opts.output_types.keys() {
399 OutputType::Bitcode => {
400 modules_config.emit_bc = true;
402 OutputType::LlvmAssembly => {
403 modules_config.emit_ir = true;
405 OutputType::Assembly => {
406 modules_config.emit_asm = true;
407 // If we're not using the LLVM assembler, this function
408 // could be invoked specially with output_type_assembly, so
409 // in this case we still want the metadata object file.
410 if !sess.opts.output_types.contains_key(&OutputType::Assembly) {
411 metadata_config.emit_obj = true;
412 allocator_config.emit_obj = true;
415 OutputType::Object => {
416 modules_config.emit_obj = true;
418 OutputType::Metadata => {
419 metadata_config.emit_obj = true;
422 modules_config.emit_obj = true;
423 metadata_config.emit_obj = true;
424 allocator_config.emit_obj = true;
426 OutputType::Mir => {}
427 OutputType::DepInfo => {}
431 modules_config.set_flags(sess, no_builtins);
432 metadata_config.set_flags(sess, no_builtins);
433 allocator_config.set_flags(sess, no_builtins);
435 // Exclude metadata and allocator modules from time_passes output, since
436 // they throw off the "LLVM passes" measurement.
437 metadata_config.time_passes = false;
438 allocator_config.time_passes = false;
440 let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
441 let (codegen_worker_send, codegen_worker_receive) = channel();
443 let coordinator_thread = start_executing_work(
451 sess.jobserver.clone(),
452 Arc::new(modules_config),
453 Arc::new(metadata_config),
454 Arc::new(allocator_config),
455 coordinator_send.clone(),
468 codegen_worker_receive,
470 future: coordinator_thread,
471 output_filenames: tcx.output_filenames(LOCAL_CRATE),
475 fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
477 compiled_modules: &CompiledModules,
478 ) -> FxHashMap<WorkProductId, WorkProduct> {
479 let mut work_products = FxHashMap::default();
481 if sess.opts.incremental.is_none() {
482 return work_products;
485 for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
486 let mut files = vec![];
488 if let Some(ref path) = module.object {
489 files.push((WorkProductFileKind::Object, path.clone()));
491 if let Some(ref path) = module.bytecode {
492 files.push((WorkProductFileKind::Bytecode, path.clone()));
494 if let Some(ref path) = module.bytecode_compressed {
495 files.push((WorkProductFileKind::BytecodeCompressed, path.clone()));
498 if let Some((id, product)) =
499 copy_cgu_workproducts_to_incr_comp_cache_dir(sess, &module.name, &files)
501 work_products.insert(id, product);
508 fn produce_final_output_artifacts(
510 compiled_modules: &CompiledModules,
511 crate_output: &OutputFilenames,
513 let mut user_wants_bitcode = false;
514 let mut user_wants_objects = false;
516 // Produce final compile outputs.
517 let copy_gracefully = |from: &Path, to: &Path| {
518 if let Err(e) = fs::copy(from, to) {
519 sess.err(&format!("could not copy {:?} to {:?}: {}", from, to, e));
523 let copy_if_one_unit = |output_type: OutputType, keep_numbered: bool| {
524 if compiled_modules.modules.len() == 1 {
525 // 1) Only one codegen unit. In this case it's no difficulty
526 // to copy `foo.0.x` to `foo.x`.
527 let module_name = Some(&compiled_modules.modules[0].name[..]);
528 let path = crate_output.temp_path(output_type, module_name);
529 copy_gracefully(&path, &crate_output.path(output_type));
530 if !sess.opts.cg.save_temps && !keep_numbered {
531 // The user just wants `foo.x`, not `foo.#module-name#.x`.
535 let ext = crate_output
536 .temp_path(output_type, None)
543 if crate_output.outputs.contains_key(&output_type) {
544 // 2) Multiple codegen units, with `--emit foo=some_name`. We have
545 // no good solution for this case, so warn the user.
547 "ignoring emit path because multiple .{} files \
551 } else if crate_output.single_output_file.is_some() {
552 // 3) Multiple codegen units, with `-o some_name`. We have
553 // no good solution for this case, so warn the user.
555 "ignoring -o because multiple .{} files \
560 // 4) Multiple codegen units, but no explicit name. We
561 // just leave the `foo.0.x` files in place.
562 // (We don't have to do any work in this case.)
567 // Flag to indicate whether the user explicitly requested bitcode.
568 // Otherwise, we produced it only as a temporary output, and will need
570 for output_type in crate_output.outputs.keys() {
572 OutputType::Bitcode => {
573 user_wants_bitcode = true;
574 // Copy to .bc, but always keep the .0.bc. There is a later
575 // check to figure out if we should delete .0.bc files, or keep
576 // them for making an rlib.
577 copy_if_one_unit(OutputType::Bitcode, true);
579 OutputType::LlvmAssembly => {
580 copy_if_one_unit(OutputType::LlvmAssembly, false);
582 OutputType::Assembly => {
583 copy_if_one_unit(OutputType::Assembly, false);
585 OutputType::Object => {
586 user_wants_objects = true;
587 copy_if_one_unit(OutputType::Object, true);
589 OutputType::Mir | OutputType::Metadata | OutputType::Exe | OutputType::DepInfo => {}
593 // Clean up unwanted temporary files.
595 // We create the following files by default:
596 // - #crate#.#module-name#.bc
597 // - #crate#.#module-name#.o
598 // - #crate#.crate.metadata.bc
599 // - #crate#.crate.metadata.o
600 // - #crate#.o (linked from crate.##.o)
601 // - #crate#.bc (copied from crate.##.bc)
602 // We may create additional files if requested by the user (through
603 // `-C save-temps` or `--emit=` flags).
605 if !sess.opts.cg.save_temps {
606 // Remove the temporary .#module-name#.o objects. If the user didn't
607 // explicitly request bitcode (with --emit=bc), and the bitcode is not
608 // needed for building an rlib, then we must remove .#module-name#.bc as
611 // Specific rules for keeping .#module-name#.bc:
612 // - If the user requested bitcode (`user_wants_bitcode`), and
613 // codegen_units > 1, then keep it.
614 // - If the user requested bitcode but codegen_units == 1, then we
615 // can toss .#module-name#.bc because we copied it to .bc earlier.
616 // - If we're not building an rlib and the user didn't request
617 // bitcode, then delete .#module-name#.bc.
618 // If you change how this works, also update back::link::link_rlib,
619 // where .#module-name#.bc files are (maybe) deleted after making an
621 let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
623 let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units() > 1;
625 let keep_numbered_objects =
626 needs_crate_object || (user_wants_objects && sess.codegen_units() > 1);
628 for module in compiled_modules.modules.iter() {
629 if let Some(ref path) = module.object {
630 if !keep_numbered_objects {
635 if let Some(ref path) = module.bytecode {
636 if !keep_numbered_bitcode {
642 if !user_wants_bitcode {
643 if let Some(ref metadata_module) = compiled_modules.metadata_module {
644 if let Some(ref path) = metadata_module.bytecode {
649 if let Some(ref allocator_module) = compiled_modules.allocator_module {
650 if let Some(ref path) = allocator_module.bytecode {
657 // We leave the following files around by default:
659 // - #crate#.crate.metadata.o
661 // These are used in linking steps and will be cleaned up afterward.
664 pub fn dump_incremental_data(_codegen_results: &CodegenResults) {
665 // FIXME(mw): This does not work at the moment because the situation has
666 // become more complicated due to incremental LTO. Now a CGU
667 // can have more than two caching states.
668 // println!("[incremental] Re-using {} out of {} modules",
669 // codegen_results.modules.iter().filter(|m| m.pre_existing).count(),
670 // codegen_results.modules.len());
673 pub enum WorkItem<B: WriteBackendMethods> {
674 /// Optimize a newly codegened, totally unoptimized module.
675 Optimize(ModuleCodegen<B::Module>),
676 /// Copy the post-LTO artifacts from the incremental cache to the output
678 CopyPostLtoArtifacts(CachedModuleCodegen),
679 /// Performs (Thin)LTO on the given module.
680 LTO(lto::LtoModuleCodegen<B>),
683 impl<B: WriteBackendMethods> WorkItem<B> {
684 pub fn module_kind(&self) -> ModuleKind {
686 WorkItem::Optimize(ref m) => m.kind,
687 WorkItem::CopyPostLtoArtifacts(_) | WorkItem::LTO(_) => ModuleKind::Regular,
691 fn profiling_event_id(&self) -> &'static str {
693 WorkItem::Optimize(_) => "codegen_module_optimize",
694 WorkItem::CopyPostLtoArtifacts(_) => "codegen_copy_artifacts_from_incr_cache",
695 WorkItem::LTO(_) => "codegen_module_perform_lto",
700 enum WorkItemResult<B: WriteBackendMethods> {
701 Compiled(CompiledModule),
702 NeedsFatLTO(FatLTOInput<B>),
703 NeedsThinLTO(String, B::ThinBuffer),
706 pub enum FatLTOInput<B: WriteBackendMethods> {
707 Serialized { name: String, buffer: B::ModuleBuffer },
708 InMemory(ModuleCodegen<B::Module>),
711 fn execute_work_item<B: ExtraBackendMethods>(
712 cgcx: &CodegenContext<B>,
713 work_item: WorkItem<B>,
714 ) -> Result<WorkItemResult<B>, FatalError> {
715 let module_config = cgcx.config(work_item.module_kind());
718 WorkItem::Optimize(module) => execute_optimize_work_item(cgcx, module, module_config),
719 WorkItem::CopyPostLtoArtifacts(module) => {
720 execute_copy_from_cache_work_item(cgcx, module, module_config)
722 WorkItem::LTO(module) => execute_lto_work_item(cgcx, module, module_config),
726 // Actual LTO type we end up chosing based on multiple factors.
727 enum ComputedLtoType {
733 fn execute_optimize_work_item<B: ExtraBackendMethods>(
734 cgcx: &CodegenContext<B>,
735 module: ModuleCodegen<B::Module>,
736 module_config: &ModuleConfig,
737 ) -> Result<WorkItemResult<B>, FatalError> {
738 let diag_handler = cgcx.create_diag_handler();
741 B::optimize(cgcx, &diag_handler, &module, module_config)?;
744 // After we've done the initial round of optimizations we need to
745 // decide whether to synchronously codegen this module or ship it
746 // back to the coordinator thread for further LTO processing (which
747 // has to wait for all the initial modules to be optimized).
749 // If the linker does LTO, we don't have to do it. Note that we
750 // keep doing full LTO, if it is requested, as not to break the
751 // assumption that the output will be a single module.
752 let linker_does_lto = cgcx.opts.cg.linker_plugin_lto.enabled();
754 // When we're automatically doing ThinLTO for multi-codegen-unit
755 // builds we don't actually want to LTO the allocator modules if
756 // it shows up. This is due to various linker shenanigans that
757 // we'll encounter later.
758 let is_allocator = module.kind == ModuleKind::Allocator;
760 // We ignore a request for full crate grath LTO if the cate type
761 // is only an rlib, as there is no full crate graph to process,
762 // that'll happen later.
764 // This use case currently comes up primarily for targets that
765 // require LTO so the request for LTO is always unconditionally
766 // passed down to the backend, but we don't actually want to do
767 // anything about it yet until we've got a final product.
768 let is_rlib = cgcx.crate_types.len() == 1 && cgcx.crate_types[0] == config::CrateType::Rlib;
770 // Metadata modules never participate in LTO regardless of the lto
772 let lto_type = if module.kind == ModuleKind::Metadata {
776 Lto::ThinLocal if !linker_does_lto && !is_allocator => ComputedLtoType::Thin,
777 Lto::Thin if !linker_does_lto && !is_rlib => ComputedLtoType::Thin,
778 Lto::Fat if !is_rlib => ComputedLtoType::Fat,
779 _ => ComputedLtoType::No,
783 // If we're doing some form of incremental LTO then we need to be sure to
784 // save our module to disk first.
785 let bitcode = if cgcx.config(module.kind).emit_pre_lto_bc {
786 let filename = pre_lto_bitcode_filename(&module.name);
787 cgcx.incr_comp_session_dir.as_ref().map(|path| path.join(&filename))
793 ComputedLtoType::No => {
794 let module = unsafe { B::codegen(cgcx, &diag_handler, module, module_config)? };
795 WorkItemResult::Compiled(module)
797 ComputedLtoType::Thin => {
798 let (name, thin_buffer) = B::prepare_thin(module);
799 if let Some(path) = bitcode {
800 fs::write(&path, thin_buffer.data()).unwrap_or_else(|e| {
801 panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
804 WorkItemResult::NeedsThinLTO(name, thin_buffer)
806 ComputedLtoType::Fat => match bitcode {
808 let (name, buffer) = B::serialize_module(module);
809 fs::write(&path, buffer.data()).unwrap_or_else(|e| {
810 panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
812 WorkItemResult::NeedsFatLTO(FatLTOInput::Serialized { name, buffer })
814 None => WorkItemResult::NeedsFatLTO(FatLTOInput::InMemory(module)),
819 fn execute_copy_from_cache_work_item<B: ExtraBackendMethods>(
820 cgcx: &CodegenContext<B>,
821 module: CachedModuleCodegen,
822 module_config: &ModuleConfig,
823 ) -> Result<WorkItemResult<B>, FatalError> {
824 let incr_comp_session_dir = cgcx.incr_comp_session_dir.as_ref().unwrap();
825 let mut object = None;
826 let mut bytecode = None;
827 let mut bytecode_compressed = None;
828 for (kind, saved_file) in &module.source.saved_files {
829 let obj_out = match kind {
830 WorkProductFileKind::Object => {
831 let path = cgcx.output_filenames.temp_path(OutputType::Object, Some(&module.name));
832 object = Some(path.clone());
835 WorkProductFileKind::Bytecode => {
836 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode, Some(&module.name));
837 bytecode = Some(path.clone());
840 WorkProductFileKind::BytecodeCompressed => {
843 .temp_path(OutputType::Bitcode, Some(&module.name))
844 .with_extension(RLIB_BYTECODE_EXTENSION);
845 bytecode_compressed = Some(path.clone());
849 let source_file = in_incr_comp_dir(&incr_comp_session_dir, &saved_file);
851 "copying pre-existing module `{}` from {:?} to {}",
856 if let Err(err) = link_or_copy(&source_file, &obj_out) {
857 let diag_handler = cgcx.create_diag_handler();
858 diag_handler.err(&format!(
859 "unable to copy {} to {}: {}",
860 source_file.display(),
867 assert_eq!(object.is_some(), module_config.emit_obj);
868 assert_eq!(bytecode.is_some(), module_config.emit_bc);
869 assert_eq!(bytecode_compressed.is_some(), module_config.emit_bc_compressed);
871 Ok(WorkItemResult::Compiled(CompiledModule {
873 kind: ModuleKind::Regular,
880 fn execute_lto_work_item<B: ExtraBackendMethods>(
881 cgcx: &CodegenContext<B>,
882 mut module: lto::LtoModuleCodegen<B>,
883 module_config: &ModuleConfig,
884 ) -> Result<WorkItemResult<B>, FatalError> {
885 let diag_handler = cgcx.create_diag_handler();
888 let module = module.optimize(cgcx)?;
889 let module = B::codegen(cgcx, &diag_handler, module, module_config)?;
890 Ok(WorkItemResult::Compiled(module))
894 pub enum Message<B: WriteBackendMethods> {
895 Token(io::Result<Acquired>),
897 result: FatLTOInput<B>,
902 thin_buffer: B::ThinBuffer,
906 result: Result<CompiledModule, ()>,
910 llvm_work_item: WorkItem<B>,
913 AddImportOnlyModule {
914 module_data: SerializedModule<B::ModuleBuffer>,
915 work_product: WorkProduct,
924 code: Option<DiagnosticId>,
928 #[derive(PartialEq, Clone, Copy, Debug)]
929 enum MainThreadWorkerState {
935 fn start_executing_work<B: ExtraBackendMethods>(
938 crate_info: &CrateInfo,
939 shared_emitter: SharedEmitter,
940 codegen_worker_send: Sender<Message<B>>,
941 coordinator_receive: Receiver<Box<dyn Any + Send>>,
944 modules_config: Arc<ModuleConfig>,
945 metadata_config: Arc<ModuleConfig>,
946 allocator_config: Arc<ModuleConfig>,
947 tx_to_llvm_workers: Sender<Box<dyn Any + Send>>,
948 ) -> thread::JoinHandle<Result<CompiledModules, ()>> {
949 let coordinator_send = tx_to_llvm_workers;
952 // Compute the set of symbols we need to retain when doing LTO (if we need to)
953 let exported_symbols = {
954 let mut exported_symbols = FxHashMap::default();
956 let copy_symbols = |cnum| {
958 .exported_symbols(cnum)
960 .map(|&(s, lvl)| (s.symbol_name(tcx).to_string(), lvl))
968 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
969 Some(Arc::new(exported_symbols))
971 Lto::Fat | Lto::Thin => {
972 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
973 for &cnum in tcx.crates().iter() {
974 exported_symbols.insert(cnum, copy_symbols(cnum));
976 Some(Arc::new(exported_symbols))
981 // First up, convert our jobserver into a helper thread so we can use normal
982 // mpsc channels to manage our messages and such.
983 // After we've requested tokens then we'll, when we can,
984 // get tokens on `coordinator_receive` which will
985 // get managed in the main loop below.
986 let coordinator_send2 = coordinator_send.clone();
987 let helper = jobserver
988 .into_helper_thread(move |token| {
989 drop(coordinator_send2.send(Box::new(Message::Token::<B>(token))));
991 .expect("failed to spawn helper thread");
993 let mut each_linked_rlib_for_lto = Vec::new();
994 drop(link::each_linked_rlib(crate_info, &mut |cnum, path| {
995 if link::ignored_for_lto(sess, crate_info, cnum) {
998 each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
1001 let assembler_cmd = if modules_config.no_integrated_as {
1002 // HACK: currently we use linker (gcc) as our assembler
1003 let (linker, flavor) = link::linker_and_flavor(sess);
1005 let (name, mut cmd) = get_linker(sess, &linker, flavor);
1006 cmd.args(&sess.target.target.options.asm_args);
1007 Some(Arc::new(AssemblerCommand { name, cmd }))
1012 let ol = if tcx.sess.opts.debugging_opts.no_codegen
1013 || !tcx.sess.opts.output_types.should_codegen()
1015 // If we know that we won’t be doing codegen, create target machines without optimisation.
1016 config::OptLevel::No
1018 tcx.backend_optimization_level(LOCAL_CRATE)
1020 let cgcx = CodegenContext::<B> {
1021 backend: backend.clone(),
1022 crate_types: sess.crate_types.borrow().clone(),
1023 each_linked_rlib_for_lto,
1025 no_landing_pads: sess.no_landing_pads(),
1026 fewer_names: sess.fewer_names(),
1027 save_temps: sess.opts.cg.save_temps,
1028 opts: Arc::new(sess.opts.clone()),
1029 time_passes: sess.time_extended(),
1030 prof: sess.prof.clone(),
1032 remark: sess.opts.cg.remark.clone(),
1034 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1035 cgu_reuse_tracker: sess.cgu_reuse_tracker.clone(),
1037 diag_emitter: shared_emitter.clone(),
1038 output_filenames: tcx.output_filenames(LOCAL_CRATE),
1039 regular_module_config: modules_config,
1040 metadata_module_config: metadata_config,
1041 allocator_module_config: allocator_config,
1042 tm_factory: TargetMachineFactory(backend.target_machine_factory(tcx.sess, ol, false)),
1044 msvc_imps_needed: msvc_imps_needed(tcx),
1045 target_pointer_width: tcx.sess.target.target.target_pointer_width.clone(),
1046 target_arch: tcx.sess.target.target.arch.clone(),
1047 debuginfo: tcx.sess.opts.debuginfo,
1051 // This is the "main loop" of parallel work happening for parallel codegen.
1052 // It's here that we manage parallelism, schedule work, and work with
1053 // messages coming from clients.
1055 // There are a few environmental pre-conditions that shape how the system
1058 // - Error reporting only can happen on the main thread because that's the
1059 // only place where we have access to the compiler `Session`.
1060 // - LLVM work can be done on any thread.
1061 // - Codegen can only happen on the main thread.
1062 // - Each thread doing substantial work most be in possession of a `Token`
1063 // from the `Jobserver`.
1064 // - The compiler process always holds one `Token`. Any additional `Tokens`
1065 // have to be requested from the `Jobserver`.
1069 // The error reporting restriction is handled separately from the rest: We
1070 // set up a `SharedEmitter` the holds an open channel to the main thread.
1071 // When an error occurs on any thread, the shared emitter will send the
1072 // error message to the receiver main thread (`SharedEmitterMain`). The
1073 // main thread will periodically query this error message queue and emit
1074 // any error messages it has received. It might even abort compilation if
1075 // has received a fatal error. In this case we rely on all other threads
1076 // being torn down automatically with the main thread.
1077 // Since the main thread will often be busy doing codegen work, error
1078 // reporting will be somewhat delayed, since the message queue can only be
1079 // checked in between to work packages.
1081 // Work Processing Infrastructure
1082 // ==============================
1083 // The work processing infrastructure knows three major actors:
1085 // - the coordinator thread,
1086 // - the main thread, and
1087 // - LLVM worker threads
1089 // The coordinator thread is running a message loop. It instructs the main
1090 // thread about what work to do when, and it will spawn off LLVM worker
1091 // threads as open LLVM WorkItems become available.
1093 // The job of the main thread is to codegen CGUs into LLVM work package
1094 // (since the main thread is the only thread that can do this). The main
1095 // thread will block until it receives a message from the coordinator, upon
1096 // which it will codegen one CGU, send it to the coordinator and block
1097 // again. This way the coordinator can control what the main thread is
1100 // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1101 // available, it will spawn off a new LLVM worker thread and let it process
1102 // that a WorkItem. When a LLVM worker thread is done with its WorkItem,
1103 // it will just shut down, which also frees all resources associated with
1104 // the given LLVM module, and sends a message to the coordinator that the
1105 // has been completed.
1109 // The scheduler's goal is to minimize the time it takes to complete all
1110 // work there is, however, we also want to keep memory consumption low
1111 // if possible. These two goals are at odds with each other: If memory
1112 // consumption were not an issue, we could just let the main thread produce
1113 // LLVM WorkItems at full speed, assuring maximal utilization of
1114 // Tokens/LLVM worker threads. However, since codegen usual is faster
1115 // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1116 // WorkItem potentially holds on to a substantial amount of memory.
1118 // So the actual goal is to always produce just enough LLVM WorkItems as
1119 // not to starve our LLVM worker threads. That means, once we have enough
1120 // WorkItems in our queue, we can block the main thread, so it does not
1121 // produce more until we need them.
1123 // Doing LLVM Work on the Main Thread
1124 // ----------------------------------
1125 // Since the main thread owns the compiler processes implicit `Token`, it is
1126 // wasteful to keep it blocked without doing any work. Therefore, what we do
1127 // in this case is: We spawn off an additional LLVM worker thread that helps
1128 // reduce the queue. The work it is doing corresponds to the implicit
1129 // `Token`. The coordinator will mark the main thread as being busy with
1130 // LLVM work. (The actual work happens on another OS thread but we just care
1131 // about `Tokens`, not actual threads).
1133 // When any LLVM worker thread finishes while the main thread is marked as
1134 // "busy with LLVM work", we can do a little switcheroo: We give the Token
1135 // of the just finished thread to the LLVM worker thread that is working on
1136 // behalf of the main thread's implicit Token, thus freeing up the main
1137 // thread again. The coordinator can then again decide what the main thread
1138 // should do. This allows the coordinator to make decisions at more points
1141 // Striking a Balance between Throughput and Memory Consumption
1142 // ------------------------------------------------------------
1143 // Since our two goals, (1) use as many Tokens as possible and (2) keep
1144 // memory consumption as low as possible, are in conflict with each other,
1145 // we have to find a trade off between them. Right now, the goal is to keep
1146 // all workers busy, which means that no worker should find the queue empty
1147 // when it is ready to start.
1148 // How do we do achieve this? Good question :) We actually never know how
1149 // many `Tokens` are potentially available so it's hard to say how much to
1150 // fill up the queue before switching the main thread to LLVM work. Also we
1151 // currently don't have a means to estimate how long a running LLVM worker
1152 // will still be busy with it's current WorkItem. However, we know the
1153 // maximal count of available Tokens that makes sense (=the number of CPU
1154 // cores), so we can take a conservative guess. The heuristic we use here
1155 // is implemented in the `queue_full_enough()` function.
1157 // Some Background on Jobservers
1158 // -----------------------------
1159 // It's worth also touching on the management of parallelism here. We don't
1160 // want to just spawn a thread per work item because while that's optimal
1161 // parallelism it may overload a system with too many threads or violate our
1162 // configuration for the maximum amount of cpu to use for this process. To
1163 // manage this we use the `jobserver` crate.
1165 // Job servers are an artifact of GNU make and are used to manage
1166 // parallelism between processes. A jobserver is a glorified IPC semaphore
1167 // basically. Whenever we want to run some work we acquire the semaphore,
1168 // and whenever we're done with that work we release the semaphore. In this
1169 // manner we can ensure that the maximum number of parallel workers is
1170 // capped at any one point in time.
1172 // LTO and the coordinator thread
1173 // ------------------------------
1175 // The final job the coordinator thread is responsible for is managing LTO
1176 // and how that works. When LTO is requested what we'll to is collect all
1177 // optimized LLVM modules into a local vector on the coordinator. Once all
1178 // modules have been codegened and optimized we hand this to the `lto`
1179 // module for further optimization. The `lto` module will return back a list
1180 // of more modules to work on, which the coordinator will continue to spawn
1183 // Each LLVM module is automatically sent back to the coordinator for LTO if
1184 // necessary. There's already optimizations in place to avoid sending work
1185 // back to the coordinator if LTO isn't requested.
1186 return thread::spawn(move || {
1187 // We pretend to be within the top-level LLVM time-passes task here:
1190 let max_workers = ::num_cpus::get();
1191 let mut worker_id_counter = 0;
1192 let mut free_worker_ids = Vec::new();
1193 let mut get_worker_id = |free_worker_ids: &mut Vec<usize>| {
1194 if let Some(id) = free_worker_ids.pop() {
1197 let id = worker_id_counter;
1198 worker_id_counter += 1;
1203 // This is where we collect codegen units that have gone all the way
1204 // through codegen and LLVM.
1205 let mut compiled_modules = vec![];
1206 let mut compiled_metadata_module = None;
1207 let mut compiled_allocator_module = None;
1208 let mut needs_fat_lto = Vec::new();
1209 let mut needs_thin_lto = Vec::new();
1210 let mut lto_import_only_modules = Vec::new();
1211 let mut started_lto = false;
1212 let mut codegen_aborted = false;
1214 // This flag tracks whether all items have gone through codegens
1215 let mut codegen_done = false;
1217 // This is the queue of LLVM work items that still need processing.
1218 let mut work_items = Vec::<(WorkItem<B>, u64)>::new();
1220 // This are the Jobserver Tokens we currently hold. Does not include
1221 // the implicit Token the compiler process owns no matter what.
1222 let mut tokens = Vec::new();
1224 let mut main_thread_worker_state = MainThreadWorkerState::Idle;
1225 let mut running = 0;
1227 let mut llvm_start_time = None;
1229 // Run the message loop while there's still anything that needs message
1230 // processing. Note that as soon as codegen is aborted we simply want to
1231 // wait for all existing work to finish, so many of the conditions here
1232 // only apply if codegen hasn't been aborted as they represent pending
1236 || (!codegen_aborted
1237 && (work_items.len() > 0
1238 || needs_fat_lto.len() > 0
1239 || needs_thin_lto.len() > 0
1240 || lto_import_only_modules.len() > 0
1241 || main_thread_worker_state != MainThreadWorkerState::Idle))
1243 // While there are still CGUs to be codegened, the coordinator has
1244 // to decide how to utilize the compiler processes implicit Token:
1245 // For codegenning more CGU or for running them through LLVM.
1247 if main_thread_worker_state == MainThreadWorkerState::Idle {
1248 if !queue_full_enough(work_items.len(), running, max_workers) {
1249 // The queue is not full enough, codegen more items:
1250 if let Err(_) = codegen_worker_send.send(Message::CodegenItem) {
1251 panic!("Could not send Message::CodegenItem to main thread")
1253 main_thread_worker_state = MainThreadWorkerState::Codegenning;
1255 // The queue is full enough to not let the worker
1256 // threads starve. Use the implicit Token to do some
1259 work_items.pop().expect("queue empty - queue_full_enough() broken?");
1260 let cgcx = CodegenContext {
1261 worker: get_worker_id(&mut free_worker_ids),
1264 maybe_start_llvm_timer(
1265 cgcx.config(item.module_kind()),
1266 &mut llvm_start_time,
1268 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1269 spawn_work(cgcx, item);
1272 } else if codegen_aborted {
1273 // don't queue up any more work if codegen was aborted, we're
1274 // just waiting for our existing children to finish
1276 // If we've finished everything related to normal codegen
1277 // then it must be the case that we've got some LTO work to do.
1278 // Perform the serial work here of figuring out what we're
1279 // going to LTO and then push a bunch of work items onto our
1281 if work_items.len() == 0
1283 && main_thread_worker_state == MainThreadWorkerState::Idle
1285 assert!(!started_lto);
1288 let needs_fat_lto = mem::take(&mut needs_fat_lto);
1289 let needs_thin_lto = mem::take(&mut needs_thin_lto);
1290 let import_only_modules = mem::take(&mut lto_import_only_modules);
1293 generate_lto_work(&cgcx, needs_fat_lto, needs_thin_lto, import_only_modules)
1295 let insertion_index = work_items
1296 .binary_search_by_key(&cost, |&(_, cost)| cost)
1297 .unwrap_or_else(|e| e);
1298 work_items.insert(insertion_index, (work, cost));
1299 if !cgcx.opts.debugging_opts.no_parallel_llvm {
1300 helper.request_token();
1305 // In this branch, we know that everything has been codegened,
1306 // so it's just a matter of determining whether the implicit
1307 // Token is free to use for LLVM work.
1308 match main_thread_worker_state {
1309 MainThreadWorkerState::Idle => {
1310 if let Some((item, _)) = work_items.pop() {
1311 let cgcx = CodegenContext {
1312 worker: get_worker_id(&mut free_worker_ids),
1315 maybe_start_llvm_timer(
1316 cgcx.config(item.module_kind()),
1317 &mut llvm_start_time,
1319 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1320 spawn_work(cgcx, item);
1322 // There is no unstarted work, so let the main thread
1323 // take over for a running worker. Otherwise the
1324 // implicit token would just go to waste.
1325 // We reduce the `running` counter by one. The
1326 // `tokens.truncate()` below will take care of
1327 // giving the Token back.
1328 debug_assert!(running > 0);
1330 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1333 MainThreadWorkerState::Codegenning => bug!(
1334 "codegen worker should not be codegenning after \
1335 codegen was already completed"
1337 MainThreadWorkerState::LLVMing => {
1338 // Already making good use of that token
1343 // Spin up what work we can, only doing this while we've got available
1344 // parallelism slots and work left to spawn.
1345 while !codegen_aborted && work_items.len() > 0 && running < tokens.len() {
1346 let (item, _) = work_items.pop().unwrap();
1348 maybe_start_llvm_timer(cgcx.config(item.module_kind()), &mut llvm_start_time);
1351 CodegenContext { worker: get_worker_id(&mut free_worker_ids), ..cgcx.clone() };
1353 spawn_work(cgcx, item);
1357 // Relinquish accidentally acquired extra tokens
1358 tokens.truncate(running);
1360 // If a thread exits successfully then we drop a token associated
1361 // with that worker and update our `running` count. We may later
1362 // re-acquire a token to continue running more work. We may also not
1363 // actually drop a token here if the worker was running with an
1364 // "ephemeral token"
1365 let mut free_worker = |worker_id| {
1366 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1367 main_thread_worker_state = MainThreadWorkerState::Idle;
1372 free_worker_ids.push(worker_id);
1375 let msg = coordinator_receive.recv().unwrap();
1376 match *msg.downcast::<Message<B>>().ok().unwrap() {
1377 // Save the token locally and the next turn of the loop will use
1378 // this to spawn a new unit of work, or it may get dropped
1379 // immediately if we have no more work to spawn.
1380 Message::Token(token) => {
1385 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1386 // If the main thread token is used for LLVM work
1387 // at the moment, we turn that thread into a regular
1388 // LLVM worker thread, so the main thread is free
1389 // to react to codegen demand.
1390 main_thread_worker_state = MainThreadWorkerState::Idle;
1395 let msg = &format!("failed to acquire jobserver token: {}", e);
1396 shared_emitter.fatal(msg);
1397 // Exit the coordinator thread
1403 Message::CodegenDone { llvm_work_item, cost } => {
1404 // We keep the queue sorted by estimated processing cost,
1405 // so that more expensive items are processed earlier. This
1406 // is good for throughput as it gives the main thread more
1407 // time to fill up the queue and it avoids scheduling
1408 // expensive items to the end.
1409 // Note, however, that this is not ideal for memory
1410 // consumption, as LLVM module sizes are not evenly
1412 let insertion_index = work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1413 let insertion_index = match insertion_index {
1414 Ok(idx) | Err(idx) => idx,
1416 work_items.insert(insertion_index, (llvm_work_item, cost));
1418 if !cgcx.opts.debugging_opts.no_parallel_llvm {
1419 helper.request_token();
1421 assert!(!codegen_aborted);
1422 assert_eq!(main_thread_worker_state, MainThreadWorkerState::Codegenning);
1423 main_thread_worker_state = MainThreadWorkerState::Idle;
1426 Message::CodegenComplete => {
1427 codegen_done = true;
1428 assert!(!codegen_aborted);
1429 assert_eq!(main_thread_worker_state, MainThreadWorkerState::Codegenning);
1430 main_thread_worker_state = MainThreadWorkerState::Idle;
1433 // If codegen is aborted that means translation was aborted due
1434 // to some normal-ish compiler error. In this situation we want
1435 // to exit as soon as possible, but we want to make sure all
1436 // existing work has finished. Flag codegen as being done, and
1437 // then conditions above will ensure no more work is spawned but
1438 // we'll keep executing this loop until `running` hits 0.
1439 Message::CodegenAborted => {
1440 assert!(!codegen_aborted);
1441 codegen_done = true;
1442 codegen_aborted = true;
1443 assert_eq!(main_thread_worker_state, MainThreadWorkerState::Codegenning);
1445 Message::Done { result: Ok(compiled_module), worker_id } => {
1446 free_worker(worker_id);
1447 match compiled_module.kind {
1448 ModuleKind::Regular => {
1449 compiled_modules.push(compiled_module);
1451 ModuleKind::Metadata => {
1452 assert!(compiled_metadata_module.is_none());
1453 compiled_metadata_module = Some(compiled_module);
1455 ModuleKind::Allocator => {
1456 assert!(compiled_allocator_module.is_none());
1457 compiled_allocator_module = Some(compiled_module);
1461 Message::NeedsFatLTO { result, worker_id } => {
1462 assert!(!started_lto);
1463 free_worker(worker_id);
1464 needs_fat_lto.push(result);
1466 Message::NeedsThinLTO { name, thin_buffer, worker_id } => {
1467 assert!(!started_lto);
1468 free_worker(worker_id);
1469 needs_thin_lto.push((name, thin_buffer));
1471 Message::AddImportOnlyModule { module_data, work_product } => {
1472 assert!(!started_lto);
1473 assert!(!codegen_done);
1474 assert_eq!(main_thread_worker_state, MainThreadWorkerState::Codegenning);
1475 lto_import_only_modules.push((module_data, work_product));
1476 main_thread_worker_state = MainThreadWorkerState::Idle;
1478 // If the thread failed that means it panicked, so we abort immediately.
1479 Message::Done { result: Err(()), worker_id: _ } => {
1480 bug!("worker thread panicked");
1482 Message::CodegenItem => bug!("the coordinator should not receive codegen requests"),
1486 if let Some(llvm_start_time) = llvm_start_time {
1487 let total_llvm_time = Instant::now().duration_since(llvm_start_time);
1488 // This is the top-level timing for all of LLVM, set the time-depth
1491 print_time_passes_entry(cgcx.time_passes, "LLVM passes", total_llvm_time);
1494 // Regardless of what order these modules completed in, report them to
1495 // the backend in the same order every time to ensure that we're handing
1496 // out deterministic results.
1497 compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
1499 Ok(CompiledModules {
1500 modules: compiled_modules,
1501 metadata_module: compiled_metadata_module,
1502 allocator_module: compiled_allocator_module,
1506 // A heuristic that determines if we have enough LLVM WorkItems in the
1507 // queue so that the main thread can do LLVM work instead of codegen
1508 fn queue_full_enough(
1509 items_in_queue: usize,
1510 workers_running: usize,
1514 items_in_queue > 0 && items_in_queue >= max_workers.saturating_sub(workers_running / 2)
1517 fn maybe_start_llvm_timer(config: &ModuleConfig, llvm_start_time: &mut Option<Instant>) {
1518 // We keep track of the -Ztime-passes output manually,
1519 // since the closure-based interface does not fit well here.
1520 if config.time_passes {
1521 if llvm_start_time.is_none() {
1522 *llvm_start_time = Some(Instant::now());
1528 pub const CODEGEN_WORKER_ID: usize = ::std::usize::MAX;
1530 fn spawn_work<B: ExtraBackendMethods>(cgcx: CodegenContext<B>, work: WorkItem<B>) {
1531 let depth = time_depth();
1533 thread::spawn(move || {
1534 set_time_depth(depth);
1536 // Set up a destructor which will fire off a message that we're done as
1538 struct Bomb<B: ExtraBackendMethods> {
1539 coordinator_send: Sender<Box<dyn Any + Send>>,
1540 result: Option<WorkItemResult<B>>,
1543 impl<B: ExtraBackendMethods> Drop for Bomb<B> {
1544 fn drop(&mut self) {
1545 let worker_id = self.worker_id;
1546 let msg = match self.result.take() {
1547 Some(WorkItemResult::Compiled(m)) => {
1548 Message::Done::<B> { result: Ok(m), worker_id }
1550 Some(WorkItemResult::NeedsFatLTO(m)) => {
1551 Message::NeedsFatLTO::<B> { result: m, worker_id }
1553 Some(WorkItemResult::NeedsThinLTO(name, thin_buffer)) => {
1554 Message::NeedsThinLTO::<B> { name, thin_buffer, worker_id }
1556 None => Message::Done::<B> { result: Err(()), worker_id },
1558 drop(self.coordinator_send.send(Box::new(msg)));
1562 let mut bomb = Bomb::<B> {
1563 coordinator_send: cgcx.coordinator_send.clone(),
1565 worker_id: cgcx.worker,
1568 // Execute the work itself, and if it finishes successfully then flag
1569 // ourselves as a success as well.
1571 // Note that we ignore any `FatalError` coming out of `execute_work_item`,
1572 // as a diagnostic was already sent off to the main thread - just
1573 // surface that there was an error in this worker.
1575 let _prof_timer = cgcx.prof.generic_activity(work.profiling_event_id());
1576 execute_work_item(&cgcx, work).ok()
1581 pub fn run_assembler<B: ExtraBackendMethods>(
1582 cgcx: &CodegenContext<B>,
1587 let assembler = cgcx.assembler_cmd.as_ref().expect("cgcx.assembler_cmd is missing?");
1589 let pname = &assembler.name;
1590 let mut cmd = assembler.cmd.clone();
1591 cmd.arg("-c").arg("-o").arg(object).arg(assembly);
1592 debug!("{:?}", cmd);
1594 match cmd.output() {
1596 if !prog.status.success() {
1597 let mut note = prog.stderr.clone();
1598 note.extend_from_slice(&prog.stdout);
1601 .struct_err(&format!(
1602 "linking with `{}` failed: {}",
1606 .note(&format!("{:?}", &cmd))
1607 .note(str::from_utf8(¬e[..]).unwrap())
1609 handler.abort_if_errors();
1613 handler.err(&format!("could not exec the linker `{}`: {}", pname.display(), e));
1614 handler.abort_if_errors();
1619 enum SharedEmitterMessage {
1620 Diagnostic(Diagnostic),
1621 InlineAsmError(u32, String),
1627 pub struct SharedEmitter {
1628 sender: Sender<SharedEmitterMessage>,
1631 pub struct SharedEmitterMain {
1632 receiver: Receiver<SharedEmitterMessage>,
1635 impl SharedEmitter {
1636 pub fn new() -> (SharedEmitter, SharedEmitterMain) {
1637 let (sender, receiver) = channel();
1639 (SharedEmitter { sender }, SharedEmitterMain { receiver })
1642 pub fn inline_asm_error(&self, cookie: u32, msg: String) {
1643 drop(self.sender.send(SharedEmitterMessage::InlineAsmError(cookie, msg)));
1646 pub fn fatal(&self, msg: &str) {
1647 drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1651 impl Emitter for SharedEmitter {
1652 fn emit_diagnostic(&mut self, diag: &rustc_errors::Diagnostic) {
1653 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1654 msg: diag.message(),
1655 code: diag.code.clone(),
1658 for child in &diag.children {
1659 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1660 msg: child.message(),
1665 drop(self.sender.send(SharedEmitterMessage::AbortIfErrors));
1667 fn source_map(&self) -> Option<&Lrc<SourceMap>> {
1672 impl SharedEmitterMain {
1673 pub fn check(&self, sess: &Session, blocking: bool) {
1675 let message = if blocking {
1676 match self.receiver.recv() {
1677 Ok(message) => Ok(message),
1681 match self.receiver.try_recv() {
1682 Ok(message) => Ok(message),
1688 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
1689 let handler = sess.diagnostic();
1690 let mut d = rustc_errors::Diagnostic::new(diag.lvl, &diag.msg);
1691 if let Some(code) = diag.code {
1694 handler.emit_diagnostic(&d);
1695 handler.abort_if_errors_and_should_abort();
1697 Ok(SharedEmitterMessage::InlineAsmError(cookie, msg)) => {
1698 sess.span_err(ExpnId::from_u32(cookie).expn_data().call_site, &msg)
1700 Ok(SharedEmitterMessage::AbortIfErrors) => {
1701 sess.abort_if_errors();
1703 Ok(SharedEmitterMessage::Fatal(msg)) => {
1714 pub struct OngoingCodegen<B: ExtraBackendMethods> {
1716 pub crate_name: Symbol,
1717 pub crate_hash: Svh,
1718 pub metadata: EncodedMetadata,
1719 pub windows_subsystem: Option<String>,
1720 pub linker_info: LinkerInfo,
1721 pub crate_info: CrateInfo,
1722 pub coordinator_send: Sender<Box<dyn Any + Send>>,
1723 pub codegen_worker_receive: Receiver<Message<B>>,
1724 pub shared_emitter_main: SharedEmitterMain,
1725 pub future: thread::JoinHandle<Result<CompiledModules, ()>>,
1726 pub output_filenames: Arc<OutputFilenames>,
1729 impl<B: ExtraBackendMethods> OngoingCodegen<B> {
1730 pub fn join(self, sess: &Session) -> (CodegenResults, FxHashMap<WorkProductId, WorkProduct>) {
1731 self.shared_emitter_main.check(sess, true);
1732 let compiled_modules = match self.future.join() {
1733 Ok(Ok(compiled_modules)) => compiled_modules,
1735 sess.abort_if_errors();
1736 panic!("expected abort due to worker thread errors")
1739 bug!("panic during codegen/LLVM phase");
1743 sess.cgu_reuse_tracker.check_expected_reuse(sess.diagnostic());
1745 sess.abort_if_errors();
1748 copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess, &compiled_modules);
1749 produce_final_output_artifacts(sess, &compiled_modules, &self.output_filenames);
1751 // FIXME: time_llvm_passes support - does this use a global context or
1753 if sess.codegen_units() == 1 && sess.time_llvm_passes() {
1754 self.backend.print_pass_timings()
1759 crate_name: self.crate_name,
1760 crate_hash: self.crate_hash,
1761 metadata: self.metadata,
1762 windows_subsystem: self.windows_subsystem,
1763 linker_info: self.linker_info,
1764 crate_info: self.crate_info,
1766 modules: compiled_modules.modules,
1767 allocator_module: compiled_modules.allocator_module,
1768 metadata_module: compiled_modules.metadata_module,
1774 pub fn submit_pre_codegened_module_to_llvm(
1777 module: ModuleCodegen<B::Module>,
1779 self.wait_for_signal_to_codegen_item();
1780 self.check_for_errors(tcx.sess);
1782 // These are generally cheap and won't throw off scheduling.
1784 submit_codegened_module_to_llvm(&self.backend, &self.coordinator_send, module, cost);
1787 pub fn codegen_finished(&self, tcx: TyCtxt<'_>) {
1788 self.wait_for_signal_to_codegen_item();
1789 self.check_for_errors(tcx.sess);
1790 drop(self.coordinator_send.send(Box::new(Message::CodegenComplete::<B>)));
1793 /// Consumes this context indicating that codegen was entirely aborted, and
1794 /// we need to exit as quickly as possible.
1796 /// This method blocks the current thread until all worker threads have
1797 /// finished, and all worker threads should have exited or be real close to
1798 /// exiting at this point.
1799 pub fn codegen_aborted(self) {
1800 // Signal to the coordinator it should spawn no more work and start
1802 drop(self.coordinator_send.send(Box::new(Message::CodegenAborted::<B>)));
1803 drop(self.future.join());
1806 pub fn check_for_errors(&self, sess: &Session) {
1807 self.shared_emitter_main.check(sess, false);
1810 pub fn wait_for_signal_to_codegen_item(&self) {
1811 match self.codegen_worker_receive.recv() {
1812 Ok(Message::CodegenItem) => {
1815 Ok(_) => panic!("unexpected message"),
1817 // One of the LLVM threads must have panicked, fall through so
1818 // error handling can be reached.
1824 pub fn submit_codegened_module_to_llvm<B: ExtraBackendMethods>(
1826 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
1827 module: ModuleCodegen<B::Module>,
1830 let llvm_work_item = WorkItem::Optimize(module);
1831 drop(tx_to_llvm_workers.send(Box::new(Message::CodegenDone::<B> { llvm_work_item, cost })));
1834 pub fn submit_post_lto_module_to_llvm<B: ExtraBackendMethods>(
1836 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
1837 module: CachedModuleCodegen,
1839 let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
1840 drop(tx_to_llvm_workers.send(Box::new(Message::CodegenDone::<B> { llvm_work_item, cost: 0 })));
1843 pub fn submit_pre_lto_module_to_llvm<B: ExtraBackendMethods>(
1846 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
1847 module: CachedModuleCodegen,
1849 let filename = pre_lto_bitcode_filename(&module.name);
1850 let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
1851 let file = fs::File::open(&bc_path)
1852 .unwrap_or_else(|e| panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e));
1855 memmap::Mmap::map(&file).unwrap_or_else(|e| {
1856 panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
1859 // Schedule the module to be loaded
1860 drop(tx_to_llvm_workers.send(Box::new(Message::AddImportOnlyModule::<B> {
1861 module_data: SerializedModule::FromUncompressedFile(mmap),
1862 work_product: module.source,
1866 pub fn pre_lto_bitcode_filename(module_name: &str) -> String {
1867 format!("{}.{}", module_name, PRE_LTO_BC_EXT)
1870 fn msvc_imps_needed(tcx: TyCtxt<'_>) -> bool {
1871 // This should never be true (because it's not supported). If it is true,
1872 // something is wrong with commandline arg validation.
1874 !(tcx.sess.opts.cg.linker_plugin_lto.enabled()
1875 && tcx.sess.target.target.options.is_like_msvc
1876 && tcx.sess.opts.cg.prefer_dynamic)
1879 tcx.sess.target.target.options.is_like_msvc &&
1880 tcx.sess.crate_types.borrow().iter().any(|ct| *ct == config::CrateType::Rlib) &&
1881 // ThinLTO can't handle this workaround in all cases, so we don't
1882 // emit the `__imp_` symbols. Instead we make them unnecessary by disallowing
1883 // dynamic linking when linker plugin LTO is enabled.
1884 !tcx.sess.opts.cg.linker_plugin_lto.enabled()