1 use crate::{ModuleCodegen, ModuleKind, CachedModuleCodegen, CompiledModule, CrateInfo,
2 CodegenResults, RLIB_BYTECODE_EXTENSION};
3 use super::linker::LinkerInfo;
4 use super::lto::{self, SerializedModule};
5 use super::link::{self, remove, get_linker};
6 use super::command::Command;
7 use super::symbol_export::ExportedSymbols;
10 use rustc_incremental::{copy_cgu_workproducts_to_incr_comp_cache_dir,
11 in_incr_comp_dir, in_incr_comp_dir_sess};
12 use rustc::dep_graph::{WorkProduct, WorkProductId, WorkProductFileKind};
13 use rustc::dep_graph::cgu_reuse_tracker::CguReuseTracker;
14 use rustc::middle::cstore::EncodedMetadata;
15 use rustc::session::config::{self, OutputFilenames, OutputType, Passes, Lto,
16 Sanitizer, SwitchWithOptPath};
17 use rustc::session::Session;
18 use rustc::util::nodemap::FxHashMap;
19 use rustc::hir::def_id::{CrateNum, LOCAL_CRATE};
20 use rustc::ty::TyCtxt;
21 use rustc::util::common::{time_depth, set_time_depth, print_time_passes_entry};
22 use rustc::util::profiling::SelfProfilerRef;
23 use rustc_fs_util::link_or_copy;
24 use rustc_data_structures::svh::Svh;
25 use rustc_errors::{Handler, Level, FatalError, DiagnosticId};
26 use rustc_errors::emitter::{Emitter};
27 use rustc_target::spec::MergeFunctions;
29 use syntax::ext::hygiene::ExpnId;
30 use syntax_pos::symbol::{Symbol, sym};
31 use jobserver::{Client, Acquired};
37 use std::path::{Path, PathBuf};
40 use std::sync::mpsc::{channel, Sender, Receiver};
41 use std::time::Instant;
44 const PRE_LTO_BC_EXT: &str = "pre-lto.bc";
46 /// Module-specific configuration for `optimize_and_codegen`.
47 pub struct ModuleConfig {
48 /// Names of additional optimization passes to run.
49 pub passes: Vec<String>,
50 /// Some(level) to optimize at a certain level, or None to run
51 /// absolutely no optimizations (used for the metadata module).
52 pub opt_level: Option<config::OptLevel>,
54 /// Some(level) to optimize binary size, or None to not affect program size.
55 pub opt_size: Option<config::OptLevel>,
57 pub pgo_gen: SwitchWithOptPath,
58 pub pgo_use: Option<PathBuf>,
60 // Flags indicating which outputs to produce.
61 pub emit_pre_lto_bc: bool,
62 pub emit_no_opt_bc: bool,
64 pub emit_bc_compressed: bool,
65 pub emit_lto_bc: bool,
69 // Miscellaneous flags. These are mostly copied from command-line
71 pub verify_llvm_ir: bool,
72 pub no_prepopulate_passes: bool,
73 pub no_builtins: bool,
74 pub time_passes: bool,
75 pub vectorize_loop: bool,
76 pub vectorize_slp: bool,
77 pub merge_functions: bool,
78 pub inline_threshold: Option<usize>,
79 // Instead of creating an object file by doing LLVM codegen, just
80 // make the object file bitcode. Provides easy compatibility with
81 // emscripten's ecc compiler, when used as the linker.
82 pub obj_is_bitcode: bool,
83 pub no_integrated_as: bool,
84 pub embed_bitcode: bool,
85 pub embed_bitcode_marker: bool,
89 fn new(passes: Vec<String>) -> ModuleConfig {
95 pgo_gen: SwitchWithOptPath::Disabled,
98 emit_no_opt_bc: false,
99 emit_pre_lto_bc: false,
101 emit_bc_compressed: false,
106 obj_is_bitcode: false,
107 embed_bitcode: false,
108 embed_bitcode_marker: false,
109 no_integrated_as: false,
111 verify_llvm_ir: false,
112 no_prepopulate_passes: false,
115 vectorize_loop: false,
116 vectorize_slp: false,
117 merge_functions: false,
118 inline_threshold: None
122 fn set_flags(&mut self, sess: &Session, no_builtins: bool) {
123 self.verify_llvm_ir = sess.verify_llvm_ir();
124 self.no_prepopulate_passes = sess.opts.cg.no_prepopulate_passes;
125 self.no_builtins = no_builtins || sess.target.target.options.no_builtins;
126 self.time_passes = sess.time_extended();
127 self.inline_threshold = sess.opts.cg.inline_threshold;
128 self.obj_is_bitcode = sess.target.target.options.obj_is_bitcode ||
129 sess.opts.cg.linker_plugin_lto.enabled();
130 let embed_bitcode = sess.target.target.options.embed_bitcode ||
131 sess.opts.debugging_opts.embed_bitcode;
133 match sess.opts.optimize {
134 config::OptLevel::No |
135 config::OptLevel::Less => {
136 self.embed_bitcode_marker = embed_bitcode;
138 _ => self.embed_bitcode = embed_bitcode,
142 // Copy what clang does by turning on loop vectorization at O2 and
143 // slp vectorization at O3. Otherwise configure other optimization aspects
144 // of this pass manager builder.
145 // Turn off vectorization for emscripten, as it's not very well supported.
146 self.vectorize_loop = !sess.opts.cg.no_vectorize_loops &&
147 (sess.opts.optimize == config::OptLevel::Default ||
148 sess.opts.optimize == config::OptLevel::Aggressive) &&
149 !sess.target.target.options.is_like_emscripten;
151 self.vectorize_slp = !sess.opts.cg.no_vectorize_slp &&
152 sess.opts.optimize == config::OptLevel::Aggressive &&
153 !sess.target.target.options.is_like_emscripten;
155 // Some targets (namely, NVPTX) interact badly with the MergeFunctions
156 // pass. This is because MergeFunctions can generate new function calls
157 // which may interfere with the target calling convention; e.g. for the
158 // NVPTX target, PTX kernels should not call other PTX kernels.
159 // MergeFunctions can also be configured to generate aliases instead,
160 // but aliases are not supported by some backends (again, NVPTX).
161 // Therefore, allow targets to opt out of the MergeFunctions pass,
162 // but otherwise keep the pass enabled (at O2 and O3) since it can be
163 // useful for reducing code size.
164 self.merge_functions = match sess.opts.debugging_opts.merge_functions
165 .unwrap_or(sess.target.target.options.merge_functions) {
166 MergeFunctions::Disabled => false,
167 MergeFunctions::Trampolines |
168 MergeFunctions::Aliases => {
169 sess.opts.optimize == config::OptLevel::Default ||
170 sess.opts.optimize == config::OptLevel::Aggressive
175 pub fn bitcode_needed(&self) -> bool {
176 self.emit_bc || self.obj_is_bitcode
177 || self.emit_bc_compressed || self.embed_bitcode
181 /// Assembler name and command used by codegen when no_integrated_as is enabled
182 pub struct AssemblerCommand {
187 // HACK(eddyb) work around `#[derive]` producing wrong bounds for `Clone`.
188 pub struct TargetMachineFactory<B: WriteBackendMethods>(
189 pub Arc<dyn Fn() -> Result<B::TargetMachine, String> + Send + Sync>,
192 impl<B: WriteBackendMethods> Clone for TargetMachineFactory<B> {
193 fn clone(&self) -> Self {
194 TargetMachineFactory(self.0.clone())
198 /// Additional resources used by optimize_and_codegen (not module specific)
200 pub struct CodegenContext<B: WriteBackendMethods> {
201 // Resources needed when running LTO
203 pub time_passes: bool,
204 pub prof: SelfProfilerRef,
206 pub no_landing_pads: bool,
207 pub save_temps: bool,
208 pub fewer_names: bool,
209 pub exported_symbols: Option<Arc<ExportedSymbols>>,
210 pub opts: Arc<config::Options>,
211 pub crate_types: Vec<config::CrateType>,
212 pub each_linked_rlib_for_lto: Vec<(CrateNum, PathBuf)>,
213 pub output_filenames: Arc<OutputFilenames>,
214 pub regular_module_config: Arc<ModuleConfig>,
215 pub metadata_module_config: Arc<ModuleConfig>,
216 pub allocator_module_config: Arc<ModuleConfig>,
217 pub tm_factory: TargetMachineFactory<B>,
218 pub msvc_imps_needed: bool,
219 pub target_pointer_width: String,
220 pub target_arch: String,
221 pub debuginfo: config::DebugInfo,
223 // Number of cgus excluding the allocator/metadata modules
224 pub total_cgus: usize,
225 // Handler to use for diagnostics produced during codegen.
226 pub diag_emitter: SharedEmitter,
227 // LLVM passes added by plugins.
228 pub plugin_passes: Vec<String>,
229 // LLVM optimizations for which we want to print remarks.
231 // Worker thread number
233 // The incremental compilation session directory, or None if we are not
234 // compiling incrementally
235 pub incr_comp_session_dir: Option<PathBuf>,
236 // Used to update CGU re-use information during the thinlto phase.
237 pub cgu_reuse_tracker: CguReuseTracker,
238 // Channel back to the main control thread to send messages to
239 pub coordinator_send: Sender<Box<dyn Any + Send>>,
240 // The assembler command if no_integrated_as option is enabled, None otherwise
241 pub assembler_cmd: Option<Arc<AssemblerCommand>>
244 impl<B: WriteBackendMethods> CodegenContext<B> {
245 pub fn create_diag_handler(&self) -> Handler {
246 Handler::with_emitter(true, None, Box::new(self.diag_emitter.clone()))
249 pub fn config(&self, kind: ModuleKind) -> &ModuleConfig {
251 ModuleKind::Regular => &self.regular_module_config,
252 ModuleKind::Metadata => &self.metadata_module_config,
253 ModuleKind::Allocator => &self.allocator_module_config,
258 fn generate_lto_work<B: ExtraBackendMethods>(
259 cgcx: &CodegenContext<B>,
260 needs_fat_lto: Vec<FatLTOInput<B>>,
261 needs_thin_lto: Vec<(String, B::ThinBuffer)>,
262 import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>
263 ) -> Vec<(WorkItem<B>, u64)> {
264 let _prof_timer = cgcx.prof.generic_activity("codegen_run_lto");
266 let (lto_modules, copy_jobs) = if !needs_fat_lto.is_empty() {
267 assert!(needs_thin_lto.is_empty());
268 let lto_module = B::run_fat_lto(
273 .unwrap_or_else(|e| e.raise());
274 (vec![lto_module], vec![])
276 assert!(needs_fat_lto.is_empty());
277 B::run_thin_lto(cgcx, needs_thin_lto, import_only_modules)
278 .unwrap_or_else(|e| e.raise())
281 let result = lto_modules.into_iter().map(|module| {
282 let cost = module.cost();
283 (WorkItem::LTO(module), cost)
284 }).chain(copy_jobs.into_iter().map(|wp| {
285 (WorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
286 name: wp.cgu_name.clone(),
294 pub struct CompiledModules {
295 pub modules: Vec<CompiledModule>,
296 pub metadata_module: Option<CompiledModule>,
297 pub allocator_module: Option<CompiledModule>,
300 fn need_crate_bitcode_for_rlib(sess: &Session) -> bool {
301 sess.crate_types.borrow().contains(&config::CrateType::Rlib) &&
302 sess.opts.output_types.contains_key(&OutputType::Exe)
305 fn need_pre_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
306 if sess.opts.incremental.is_none() {
314 Lto::ThinLocal => true,
318 pub fn start_async_codegen<B: ExtraBackendMethods>(
321 metadata: EncodedMetadata,
323 ) -> OngoingCodegen<B> {
324 let (coordinator_send, coordinator_receive) = channel();
327 sess.prof.generic_activity_start("codegen_and_optimize_crate");
329 let crate_name = tcx.crate_name(LOCAL_CRATE);
330 let crate_hash = tcx.crate_hash(LOCAL_CRATE);
331 let no_builtins = attr::contains_name(&tcx.hir().krate().attrs, sym::no_builtins);
332 let subsystem = attr::first_attr_value_str_by_name(&tcx.hir().krate().attrs,
333 sym::windows_subsystem);
334 let windows_subsystem = subsystem.map(|subsystem| {
335 if subsystem != sym::windows && subsystem != sym::console {
336 tcx.sess.fatal(&format!("invalid windows subsystem `{}`, only \
337 `windows` and `console` are allowed",
340 subsystem.to_string()
343 let linker_info = LinkerInfo::new(tcx);
344 let crate_info = CrateInfo::new(tcx);
346 // Figure out what we actually need to build.
347 let mut modules_config = ModuleConfig::new(sess.opts.cg.passes.clone());
348 let mut metadata_config = ModuleConfig::new(vec![]);
349 let mut allocator_config = ModuleConfig::new(vec![]);
351 if let Some(ref sanitizer) = sess.opts.debugging_opts.sanitizer {
353 Sanitizer::Address => {
354 modules_config.passes.push("asan".to_owned());
355 modules_config.passes.push("asan-module".to_owned());
357 Sanitizer::Memory => {
358 modules_config.passes.push("msan".to_owned())
360 Sanitizer::Thread => {
361 modules_config.passes.push("tsan".to_owned())
367 if sess.opts.debugging_opts.profile {
368 modules_config.passes.push("insert-gcov-profiling".to_owned())
371 modules_config.pgo_gen = sess.opts.cg.profile_generate.clone();
372 modules_config.pgo_use = sess.opts.cg.profile_use.clone();
374 modules_config.opt_level = Some(sess.opts.optimize);
375 modules_config.opt_size = Some(sess.opts.optimize);
377 // Save all versions of the bytecode if we're saving our temporaries.
378 if sess.opts.cg.save_temps {
379 modules_config.emit_no_opt_bc = true;
380 modules_config.emit_pre_lto_bc = true;
381 modules_config.emit_bc = true;
382 modules_config.emit_lto_bc = true;
383 metadata_config.emit_bc = true;
384 allocator_config.emit_bc = true;
387 // Emit compressed bitcode files for the crate if we're emitting an rlib.
388 // Whenever an rlib is created, the bitcode is inserted into the archive in
389 // order to allow LTO against it.
390 if need_crate_bitcode_for_rlib(sess) {
391 modules_config.emit_bc_compressed = true;
392 allocator_config.emit_bc_compressed = true;
395 modules_config.emit_pre_lto_bc =
396 need_pre_lto_bitcode_for_incr_comp(sess);
398 modules_config.no_integrated_as = tcx.sess.opts.cg.no_integrated_as ||
399 tcx.sess.target.target.options.no_integrated_as;
401 for output_type in sess.opts.output_types.keys() {
403 OutputType::Bitcode => { modules_config.emit_bc = true; }
404 OutputType::LlvmAssembly => { 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 => { modules_config.emit_obj = true; }
416 OutputType::Metadata => { metadata_config.emit_obj = true; }
418 modules_config.emit_obj = true;
419 metadata_config.emit_obj = true;
420 allocator_config.emit_obj = true;
422 OutputType::Mir => {}
423 OutputType::DepInfo => {}
427 modules_config.set_flags(sess, no_builtins);
428 metadata_config.set_flags(sess, no_builtins);
429 allocator_config.set_flags(sess, no_builtins);
431 // Exclude metadata and allocator modules from time_passes output, since
432 // they throw off the "LLVM passes" measurement.
433 metadata_config.time_passes = false;
434 allocator_config.time_passes = false;
436 let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
437 let (codegen_worker_send, codegen_worker_receive) = channel();
439 let coordinator_thread = start_executing_work(backend.clone(),
446 sess.jobserver.clone(),
447 Arc::new(modules_config),
448 Arc::new(metadata_config),
449 Arc::new(allocator_config),
450 coordinator_send.clone());
462 codegen_worker_receive,
464 future: coordinator_thread,
465 output_filenames: tcx.output_filenames(LOCAL_CRATE),
469 fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
471 compiled_modules: &CompiledModules,
472 ) -> FxHashMap<WorkProductId, WorkProduct> {
473 let mut work_products = FxHashMap::default();
475 if sess.opts.incremental.is_none() {
476 return work_products;
479 for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
480 let mut files = vec![];
482 if let Some(ref path) = module.object {
483 files.push((WorkProductFileKind::Object, path.clone()));
485 if let Some(ref path) = module.bytecode {
486 files.push((WorkProductFileKind::Bytecode, path.clone()));
488 if let Some(ref path) = module.bytecode_compressed {
489 files.push((WorkProductFileKind::BytecodeCompressed, path.clone()));
492 if let Some((id, product)) =
493 copy_cgu_workproducts_to_incr_comp_cache_dir(sess, &module.name, &files) {
494 work_products.insert(id, product);
501 fn produce_final_output_artifacts(sess: &Session,
502 compiled_modules: &CompiledModules,
503 crate_output: &OutputFilenames) {
504 let mut user_wants_bitcode = false;
505 let mut user_wants_objects = false;
507 // Produce final compile outputs.
508 let copy_gracefully = |from: &Path, to: &Path| {
509 if let Err(e) = fs::copy(from, to) {
510 sess.err(&format!("could not copy {:?} to {:?}: {}", from, to, e));
514 let copy_if_one_unit = |output_type: OutputType,
515 keep_numbered: bool| {
516 if compiled_modules.modules.len() == 1 {
517 // 1) Only one codegen unit. In this case it's no difficulty
518 // to copy `foo.0.x` to `foo.x`.
519 let module_name = Some(&compiled_modules.modules[0].name[..]);
520 let path = crate_output.temp_path(output_type, module_name);
521 copy_gracefully(&path,
522 &crate_output.path(output_type));
523 if !sess.opts.cg.save_temps && !keep_numbered {
524 // The user just wants `foo.x`, not `foo.#module-name#.x`.
528 let ext = crate_output.temp_path(output_type, None)
535 if crate_output.outputs.contains_key(&output_type) {
536 // 2) Multiple codegen units, with `--emit foo=some_name`. We have
537 // no good solution for this case, so warn the user.
538 sess.warn(&format!("ignoring emit path because multiple .{} files \
539 were produced", ext));
540 } else if crate_output.single_output_file.is_some() {
541 // 3) Multiple codegen units, with `-o some_name`. We have
542 // no good solution for this case, so warn the user.
543 sess.warn(&format!("ignoring -o because multiple .{} files \
544 were produced", ext));
546 // 4) Multiple codegen units, but no explicit name. We
547 // just leave the `foo.0.x` files in place.
548 // (We don't have to do any work in this case.)
553 // Flag to indicate whether the user explicitly requested bitcode.
554 // Otherwise, we produced it only as a temporary output, and will need
556 for output_type in crate_output.outputs.keys() {
558 OutputType::Bitcode => {
559 user_wants_bitcode = true;
560 // Copy to .bc, but always keep the .0.bc. There is a later
561 // check to figure out if we should delete .0.bc files, or keep
562 // them for making an rlib.
563 copy_if_one_unit(OutputType::Bitcode, true);
565 OutputType::LlvmAssembly => {
566 copy_if_one_unit(OutputType::LlvmAssembly, false);
568 OutputType::Assembly => {
569 copy_if_one_unit(OutputType::Assembly, false);
571 OutputType::Object => {
572 user_wants_objects = true;
573 copy_if_one_unit(OutputType::Object, true);
576 OutputType::Metadata |
578 OutputType::DepInfo => {}
582 // Clean up unwanted temporary files.
584 // We create the following files by default:
585 // - #crate#.#module-name#.bc
586 // - #crate#.#module-name#.o
587 // - #crate#.crate.metadata.bc
588 // - #crate#.crate.metadata.o
589 // - #crate#.o (linked from crate.##.o)
590 // - #crate#.bc (copied from crate.##.bc)
591 // We may create additional files if requested by the user (through
592 // `-C save-temps` or `--emit=` flags).
594 if !sess.opts.cg.save_temps {
595 // Remove the temporary .#module-name#.o objects. If the user didn't
596 // explicitly request bitcode (with --emit=bc), and the bitcode is not
597 // needed for building an rlib, then we must remove .#module-name#.bc as
600 // Specific rules for keeping .#module-name#.bc:
601 // - If the user requested bitcode (`user_wants_bitcode`), and
602 // codegen_units > 1, then keep it.
603 // - If the user requested bitcode but codegen_units == 1, then we
604 // can toss .#module-name#.bc because we copied it to .bc earlier.
605 // - If we're not building an rlib and the user didn't request
606 // bitcode, then delete .#module-name#.bc.
607 // If you change how this works, also update back::link::link_rlib,
608 // where .#module-name#.bc files are (maybe) deleted after making an
610 let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
612 let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units() > 1;
614 let keep_numbered_objects = needs_crate_object ||
615 (user_wants_objects && sess.codegen_units() > 1);
617 for module in compiled_modules.modules.iter() {
618 if let Some(ref path) = module.object {
619 if !keep_numbered_objects {
624 if let Some(ref path) = module.bytecode {
625 if !keep_numbered_bitcode {
631 if !user_wants_bitcode {
632 if let Some(ref metadata_module) = compiled_modules.metadata_module {
633 if let Some(ref path) = metadata_module.bytecode {
638 if let Some(ref allocator_module) = compiled_modules.allocator_module {
639 if let Some(ref path) = allocator_module.bytecode {
646 // We leave the following files around by default:
648 // - #crate#.crate.metadata.o
650 // These are used in linking steps and will be cleaned up afterward.
653 pub fn dump_incremental_data(_codegen_results: &CodegenResults) {
654 // FIXME(mw): This does not work at the moment because the situation has
655 // become more complicated due to incremental LTO. Now a CGU
656 // can have more than two caching states.
657 // println!("[incremental] Re-using {} out of {} modules",
658 // codegen_results.modules.iter().filter(|m| m.pre_existing).count(),
659 // codegen_results.modules.len());
662 pub enum WorkItem<B: WriteBackendMethods> {
663 /// Optimize a newly codegened, totally unoptimized module.
664 Optimize(ModuleCodegen<B::Module>),
665 /// Copy the post-LTO artifacts from the incremental cache to the output
667 CopyPostLtoArtifacts(CachedModuleCodegen),
668 /// Performs (Thin)LTO on the given module.
669 LTO(lto::LtoModuleCodegen<B>),
672 impl<B: WriteBackendMethods> WorkItem<B> {
673 pub fn module_kind(&self) -> ModuleKind {
675 WorkItem::Optimize(ref m) => m.kind,
676 WorkItem::CopyPostLtoArtifacts(_) |
677 WorkItem::LTO(_) => ModuleKind::Regular,
681 pub fn name(&self) -> String {
683 WorkItem::Optimize(ref m) => format!("optimize: {}", m.name),
684 WorkItem::CopyPostLtoArtifacts(ref m) => format!("copy post LTO artifacts: {}", m.name),
685 WorkItem::LTO(ref m) => format!("lto: {}", m.name()),
690 enum WorkItemResult<B: WriteBackendMethods> {
691 Compiled(CompiledModule),
692 NeedsFatLTO(FatLTOInput<B>),
693 NeedsThinLTO(String, B::ThinBuffer),
696 pub enum FatLTOInput<B: WriteBackendMethods> {
699 buffer: B::ModuleBuffer,
701 InMemory(ModuleCodegen<B::Module>),
704 fn execute_work_item<B: ExtraBackendMethods>(
705 cgcx: &CodegenContext<B>,
706 work_item: WorkItem<B>,
707 ) -> Result<WorkItemResult<B>, FatalError> {
708 let module_config = cgcx.config(work_item.module_kind());
711 WorkItem::Optimize(module) => {
712 execute_optimize_work_item(cgcx, module, module_config)
714 WorkItem::CopyPostLtoArtifacts(module) => {
715 execute_copy_from_cache_work_item(cgcx, module, module_config)
717 WorkItem::LTO(module) => {
718 execute_lto_work_item(cgcx, module, module_config)
723 // Actual LTO type we end up chosing based on multiple factors.
724 enum ComputedLtoType {
730 fn execute_optimize_work_item<B: ExtraBackendMethods>(
731 cgcx: &CodegenContext<B>,
732 module: ModuleCodegen<B::Module>,
733 module_config: &ModuleConfig,
734 ) -> Result<WorkItemResult<B>, FatalError> {
735 let diag_handler = cgcx.create_diag_handler();
738 B::optimize(cgcx, &diag_handler, &module, module_config)?;
741 // After we've done the initial round of optimizations we need to
742 // decide whether to synchronously codegen this module or ship it
743 // back to the coordinator thread for further LTO processing (which
744 // has to wait for all the initial modules to be optimized).
746 // If the linker does LTO, we don't have to do it. Note that we
747 // keep doing full LTO, if it is requested, as not to break the
748 // assumption that the output will be a single module.
749 let linker_does_lto = cgcx.opts.cg.linker_plugin_lto.enabled();
751 // When we're automatically doing ThinLTO for multi-codegen-unit
752 // builds we don't actually want to LTO the allocator modules if
753 // it shows up. This is due to various linker shenanigans that
754 // we'll encounter later.
755 let is_allocator = module.kind == ModuleKind::Allocator;
757 // We ignore a request for full crate grath LTO if the cate type
758 // is only an rlib, as there is no full crate graph to process,
759 // that'll happen later.
761 // This use case currently comes up primarily for targets that
762 // require LTO so the request for LTO is always unconditionally
763 // passed down to the backend, but we don't actually want to do
764 // anything about it yet until we've got a final product.
765 let is_rlib = cgcx.crate_types.len() == 1
766 && cgcx.crate_types[0] == config::CrateType::Rlib;
768 // Metadata modules never participate in LTO regardless of the lto
770 let lto_type = if module.kind == ModuleKind::Metadata {
774 Lto::ThinLocal if !linker_does_lto && !is_allocator
775 => ComputedLtoType::Thin,
776 Lto::Thin if !linker_does_lto && !is_rlib
777 => 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 {
795 B::codegen(cgcx, &diag_handler, module, module_config)?
797 WorkItemResult::Compiled(module)
799 ComputedLtoType::Thin => {
800 let (name, thin_buffer) = B::prepare_thin(module);
801 if let Some(path) = bitcode {
802 fs::write(&path, thin_buffer.data()).unwrap_or_else(|e| {
803 panic!("Error writing pre-lto-bitcode file `{}`: {}",
808 WorkItemResult::NeedsThinLTO(name, thin_buffer)
810 ComputedLtoType::Fat => {
813 let (name, buffer) = B::serialize_module(module);
814 fs::write(&path, buffer.data()).unwrap_or_else(|e| {
815 panic!("Error writing pre-lto-bitcode file `{}`: {}",
819 WorkItemResult::NeedsFatLTO(FatLTOInput::Serialized { name, buffer })
821 None => WorkItemResult::NeedsFatLTO(FatLTOInput::InMemory(module)),
827 fn execute_copy_from_cache_work_item<B: ExtraBackendMethods>(
828 cgcx: &CodegenContext<B>,
829 module: CachedModuleCodegen,
830 module_config: &ModuleConfig,
831 ) -> Result<WorkItemResult<B>, FatalError> {
832 let incr_comp_session_dir = cgcx.incr_comp_session_dir
835 let mut object = None;
836 let mut bytecode = None;
837 let mut bytecode_compressed = None;
838 for (kind, saved_file) in &module.source.saved_files {
839 let obj_out = match kind {
840 WorkProductFileKind::Object => {
841 let path = cgcx.output_filenames.temp_path(OutputType::Object,
843 object = Some(path.clone());
846 WorkProductFileKind::Bytecode => {
847 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode,
849 bytecode = Some(path.clone());
852 WorkProductFileKind::BytecodeCompressed => {
853 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode,
855 .with_extension(RLIB_BYTECODE_EXTENSION);
856 bytecode_compressed = Some(path.clone());
860 let source_file = in_incr_comp_dir(&incr_comp_session_dir,
862 debug!("copying pre-existing module `{}` from {:?} to {}",
866 if let Err(err) = link_or_copy(&source_file, &obj_out) {
867 let diag_handler = cgcx.create_diag_handler();
868 diag_handler.err(&format!("unable to copy {} to {}: {}",
869 source_file.display(),
875 assert_eq!(object.is_some(), module_config.emit_obj);
876 assert_eq!(bytecode.is_some(), module_config.emit_bc);
877 assert_eq!(bytecode_compressed.is_some(), module_config.emit_bc_compressed);
879 Ok(WorkItemResult::Compiled(CompiledModule {
881 kind: ModuleKind::Regular,
888 fn execute_lto_work_item<B: ExtraBackendMethods>(
889 cgcx: &CodegenContext<B>,
890 mut module: lto::LtoModuleCodegen<B>,
891 module_config: &ModuleConfig,
892 ) -> Result<WorkItemResult<B>, FatalError> {
893 let diag_handler = cgcx.create_diag_handler();
896 let module = module.optimize(cgcx)?;
897 let module = B::codegen(cgcx, &diag_handler, module, module_config)?;
898 Ok(WorkItemResult::Compiled(module))
902 pub enum Message<B: WriteBackendMethods> {
903 Token(io::Result<Acquired>),
905 result: FatLTOInput<B>,
910 thin_buffer: B::ThinBuffer,
914 result: Result<CompiledModule, ()>,
918 llvm_work_item: WorkItem<B>,
921 AddImportOnlyModule {
922 module_data: SerializedModule<B::ModuleBuffer>,
923 work_product: WorkProduct,
932 code: Option<DiagnosticId>,
936 #[derive(PartialEq, Clone, Copy, Debug)]
937 enum MainThreadWorkerState {
943 fn start_executing_work<B: ExtraBackendMethods>(
946 crate_info: &CrateInfo,
947 shared_emitter: SharedEmitter,
948 codegen_worker_send: Sender<Message<B>>,
949 coordinator_receive: Receiver<Box<dyn Any + Send>>,
952 modules_config: Arc<ModuleConfig>,
953 metadata_config: Arc<ModuleConfig>,
954 allocator_config: Arc<ModuleConfig>,
955 tx_to_llvm_workers: Sender<Box<dyn Any + Send>>,
956 ) -> thread::JoinHandle<Result<CompiledModules, ()>> {
957 let coordinator_send = tx_to_llvm_workers;
960 // Compute the set of symbols we need to retain when doing LTO (if we need to)
961 let exported_symbols = {
962 let mut exported_symbols = FxHashMap::default();
964 let copy_symbols = |cnum| {
965 let symbols = tcx.exported_symbols(cnum)
967 .map(|&(s, lvl)| (s.symbol_name(tcx).to_string(), lvl))
975 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
976 Some(Arc::new(exported_symbols))
978 Lto::Fat | Lto::Thin => {
979 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
980 for &cnum in tcx.crates().iter() {
981 exported_symbols.insert(cnum, copy_symbols(cnum));
983 Some(Arc::new(exported_symbols))
988 // First up, convert our jobserver into a helper thread so we can use normal
989 // mpsc channels to manage our messages and such.
990 // After we've requested tokens then we'll, when we can,
991 // get tokens on `coordinator_receive` which will
992 // get managed in the main loop below.
993 let coordinator_send2 = coordinator_send.clone();
994 let helper = jobserver.into_helper_thread(move |token| {
995 drop(coordinator_send2.send(Box::new(Message::Token::<B>(token))));
996 }).expect("failed to spawn helper thread");
998 let mut each_linked_rlib_for_lto = Vec::new();
999 drop(link::each_linked_rlib(crate_info, &mut |cnum, path| {
1000 if link::ignored_for_lto(sess, crate_info, cnum) {
1003 each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
1006 let assembler_cmd = if modules_config.no_integrated_as {
1007 // HACK: currently we use linker (gcc) as our assembler
1008 let (linker, flavor) = link::linker_and_flavor(sess);
1010 let (name, mut cmd) = get_linker(sess, &linker, flavor);
1011 cmd.args(&sess.target.target.options.asm_args);
1012 Some(Arc::new(AssemblerCommand {
1020 let ol = if tcx.sess.opts.debugging_opts.no_codegen
1021 || !tcx.sess.opts.output_types.should_codegen() {
1022 // If we know that we won’t be doing codegen, create target machines without optimisation.
1023 config::OptLevel::No
1025 tcx.backend_optimization_level(LOCAL_CRATE)
1027 let cgcx = CodegenContext::<B> {
1028 backend: backend.clone(),
1029 crate_types: sess.crate_types.borrow().clone(),
1030 each_linked_rlib_for_lto,
1032 no_landing_pads: sess.no_landing_pads(),
1033 fewer_names: sess.fewer_names(),
1034 save_temps: sess.opts.cg.save_temps,
1035 opts: Arc::new(sess.opts.clone()),
1036 time_passes: sess.time_extended(),
1037 prof: sess.prof.clone(),
1039 plugin_passes: sess.plugin_llvm_passes.borrow().clone(),
1040 remark: sess.opts.cg.remark.clone(),
1042 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1043 cgu_reuse_tracker: sess.cgu_reuse_tracker.clone(),
1045 diag_emitter: shared_emitter.clone(),
1046 output_filenames: tcx.output_filenames(LOCAL_CRATE),
1047 regular_module_config: modules_config,
1048 metadata_module_config: metadata_config,
1049 allocator_module_config: allocator_config,
1050 tm_factory: TargetMachineFactory(backend.target_machine_factory(tcx.sess, ol, false)),
1052 msvc_imps_needed: msvc_imps_needed(tcx),
1053 target_pointer_width: tcx.sess.target.target.target_pointer_width.clone(),
1054 target_arch: tcx.sess.target.target.arch.clone(),
1055 debuginfo: tcx.sess.opts.debuginfo,
1059 // This is the "main loop" of parallel work happening for parallel codegen.
1060 // It's here that we manage parallelism, schedule work, and work with
1061 // messages coming from clients.
1063 // There are a few environmental pre-conditions that shape how the system
1066 // - Error reporting only can happen on the main thread because that's the
1067 // only place where we have access to the compiler `Session`.
1068 // - LLVM work can be done on any thread.
1069 // - Codegen can only happen on the main thread.
1070 // - Each thread doing substantial work most be in possession of a `Token`
1071 // from the `Jobserver`.
1072 // - The compiler process always holds one `Token`. Any additional `Tokens`
1073 // have to be requested from the `Jobserver`.
1077 // The error reporting restriction is handled separately from the rest: We
1078 // set up a `SharedEmitter` the holds an open channel to the main thread.
1079 // When an error occurs on any thread, the shared emitter will send the
1080 // error message to the receiver main thread (`SharedEmitterMain`). The
1081 // main thread will periodically query this error message queue and emit
1082 // any error messages it has received. It might even abort compilation if
1083 // has received a fatal error. In this case we rely on all other threads
1084 // being torn down automatically with the main thread.
1085 // Since the main thread will often be busy doing codegen work, error
1086 // reporting will be somewhat delayed, since the message queue can only be
1087 // checked in between to work packages.
1089 // Work Processing Infrastructure
1090 // ==============================
1091 // The work processing infrastructure knows three major actors:
1093 // - the coordinator thread,
1094 // - the main thread, and
1095 // - LLVM worker threads
1097 // The coordinator thread is running a message loop. It instructs the main
1098 // thread about what work to do when, and it will spawn off LLVM worker
1099 // threads as open LLVM WorkItems become available.
1101 // The job of the main thread is to codegen CGUs into LLVM work package
1102 // (since the main thread is the only thread that can do this). The main
1103 // thread will block until it receives a message from the coordinator, upon
1104 // which it will codegen one CGU, send it to the coordinator and block
1105 // again. This way the coordinator can control what the main thread is
1108 // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1109 // available, it will spawn off a new LLVM worker thread and let it process
1110 // that a WorkItem. When a LLVM worker thread is done with its WorkItem,
1111 // it will just shut down, which also frees all resources associated with
1112 // the given LLVM module, and sends a message to the coordinator that the
1113 // has been completed.
1117 // The scheduler's goal is to minimize the time it takes to complete all
1118 // work there is, however, we also want to keep memory consumption low
1119 // if possible. These two goals are at odds with each other: If memory
1120 // consumption were not an issue, we could just let the main thread produce
1121 // LLVM WorkItems at full speed, assuring maximal utilization of
1122 // Tokens/LLVM worker threads. However, since codegen usual is faster
1123 // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1124 // WorkItem potentially holds on to a substantial amount of memory.
1126 // So the actual goal is to always produce just enough LLVM WorkItems as
1127 // not to starve our LLVM worker threads. That means, once we have enough
1128 // WorkItems in our queue, we can block the main thread, so it does not
1129 // produce more until we need them.
1131 // Doing LLVM Work on the Main Thread
1132 // ----------------------------------
1133 // Since the main thread owns the compiler processes implicit `Token`, it is
1134 // wasteful to keep it blocked without doing any work. Therefore, what we do
1135 // in this case is: We spawn off an additional LLVM worker thread that helps
1136 // reduce the queue. The work it is doing corresponds to the implicit
1137 // `Token`. The coordinator will mark the main thread as being busy with
1138 // LLVM work. (The actual work happens on another OS thread but we just care
1139 // about `Tokens`, not actual threads).
1141 // When any LLVM worker thread finishes while the main thread is marked as
1142 // "busy with LLVM work", we can do a little switcheroo: We give the Token
1143 // of the just finished thread to the LLVM worker thread that is working on
1144 // behalf of the main thread's implicit Token, thus freeing up the main
1145 // thread again. The coordinator can then again decide what the main thread
1146 // should do. This allows the coordinator to make decisions at more points
1149 // Striking a Balance between Throughput and Memory Consumption
1150 // ------------------------------------------------------------
1151 // Since our two goals, (1) use as many Tokens as possible and (2) keep
1152 // memory consumption as low as possible, are in conflict with each other,
1153 // we have to find a trade off between them. Right now, the goal is to keep
1154 // all workers busy, which means that no worker should find the queue empty
1155 // when it is ready to start.
1156 // How do we do achieve this? Good question :) We actually never know how
1157 // many `Tokens` are potentially available so it's hard to say how much to
1158 // fill up the queue before switching the main thread to LLVM work. Also we
1159 // currently don't have a means to estimate how long a running LLVM worker
1160 // will still be busy with it's current WorkItem. However, we know the
1161 // maximal count of available Tokens that makes sense (=the number of CPU
1162 // cores), so we can take a conservative guess. The heuristic we use here
1163 // is implemented in the `queue_full_enough()` function.
1165 // Some Background on Jobservers
1166 // -----------------------------
1167 // It's worth also touching on the management of parallelism here. We don't
1168 // want to just spawn a thread per work item because while that's optimal
1169 // parallelism it may overload a system with too many threads or violate our
1170 // configuration for the maximum amount of cpu to use for this process. To
1171 // manage this we use the `jobserver` crate.
1173 // Job servers are an artifact of GNU make and are used to manage
1174 // parallelism between processes. A jobserver is a glorified IPC semaphore
1175 // basically. Whenever we want to run some work we acquire the semaphore,
1176 // and whenever we're done with that work we release the semaphore. In this
1177 // manner we can ensure that the maximum number of parallel workers is
1178 // capped at any one point in time.
1180 // LTO and the coordinator thread
1181 // ------------------------------
1183 // The final job the coordinator thread is responsible for is managing LTO
1184 // and how that works. When LTO is requested what we'll to is collect all
1185 // optimized LLVM modules into a local vector on the coordinator. Once all
1186 // modules have been codegened and optimized we hand this to the `lto`
1187 // module for further optimization. The `lto` module will return back a list
1188 // of more modules to work on, which the coordinator will continue to spawn
1191 // Each LLVM module is automatically sent back to the coordinator for LTO if
1192 // necessary. There's already optimizations in place to avoid sending work
1193 // back to the coordinator if LTO isn't requested.
1194 return thread::spawn(move || {
1195 // We pretend to be within the top-level LLVM time-passes task here:
1198 let max_workers = ::num_cpus::get();
1199 let mut worker_id_counter = 0;
1200 let mut free_worker_ids = Vec::new();
1201 let mut get_worker_id = |free_worker_ids: &mut Vec<usize>| {
1202 if let Some(id) = free_worker_ids.pop() {
1205 let id = worker_id_counter;
1206 worker_id_counter += 1;
1211 // This is where we collect codegen units that have gone all the way
1212 // through codegen and LLVM.
1213 let mut compiled_modules = vec![];
1214 let mut compiled_metadata_module = None;
1215 let mut compiled_allocator_module = None;
1216 let mut needs_fat_lto = Vec::new();
1217 let mut needs_thin_lto = Vec::new();
1218 let mut lto_import_only_modules = Vec::new();
1219 let mut started_lto = false;
1220 let mut codegen_aborted = false;
1222 // This flag tracks whether all items have gone through codegens
1223 let mut codegen_done = false;
1225 // This is the queue of LLVM work items that still need processing.
1226 let mut work_items = Vec::<(WorkItem<B>, u64)>::new();
1228 // This are the Jobserver Tokens we currently hold. Does not include
1229 // the implicit Token the compiler process owns no matter what.
1230 let mut tokens = Vec::new();
1232 let mut main_thread_worker_state = MainThreadWorkerState::Idle;
1233 let mut running = 0;
1235 let mut llvm_start_time = None;
1237 // Run the message loop while there's still anything that needs message
1238 // processing. Note that as soon as codegen is aborted we simply want to
1239 // wait for all existing work to finish, so many of the conditions here
1240 // only apply if codegen hasn't been aborted as they represent pending
1242 while !codegen_done ||
1244 (!codegen_aborted && (
1245 work_items.len() > 0 ||
1246 needs_fat_lto.len() > 0 ||
1247 needs_thin_lto.len() > 0 ||
1248 lto_import_only_modules.len() > 0 ||
1249 main_thread_worker_state != MainThreadWorkerState::Idle
1253 // While there are still CGUs to be codegened, the coordinator has
1254 // to decide how to utilize the compiler processes implicit Token:
1255 // For codegenning more CGU or for running them through LLVM.
1257 if main_thread_worker_state == MainThreadWorkerState::Idle {
1258 if !queue_full_enough(work_items.len(), running, max_workers) {
1259 // The queue is not full enough, codegen more items:
1260 if let Err(_) = codegen_worker_send.send(Message::CodegenItem) {
1261 panic!("Could not send Message::CodegenItem to main thread")
1263 main_thread_worker_state = MainThreadWorkerState::Codegenning;
1265 // The queue is full enough to not let the worker
1266 // threads starve. Use the implicit Token to do some
1268 let (item, _) = work_items.pop()
1269 .expect("queue empty - queue_full_enough() broken?");
1270 let cgcx = CodegenContext {
1271 worker: get_worker_id(&mut free_worker_ids),
1274 maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1275 &mut llvm_start_time);
1276 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1277 spawn_work(cgcx, item);
1280 } else if codegen_aborted {
1281 // don't queue up any more work if codegen was aborted, we're
1282 // just waiting for our existing children to finish
1284 // If we've finished everything related to normal codegen
1285 // then it must be the case that we've got some LTO work to do.
1286 // Perform the serial work here of figuring out what we're
1287 // going to LTO and then push a bunch of work items onto our
1289 if work_items.len() == 0 &&
1291 main_thread_worker_state == MainThreadWorkerState::Idle {
1292 assert!(!started_lto);
1295 let needs_fat_lto = mem::take(&mut needs_fat_lto);
1296 let needs_thin_lto = mem::take(&mut needs_thin_lto);
1297 let import_only_modules = mem::take(&mut lto_import_only_modules);
1299 for (work, cost) in generate_lto_work(&cgcx, needs_fat_lto,
1300 needs_thin_lto, import_only_modules) {
1301 let insertion_index = work_items
1302 .binary_search_by_key(&cost, |&(_, cost)| cost)
1303 .unwrap_or_else(|e| e);
1304 work_items.insert(insertion_index, (work, cost));
1305 if !cgcx.opts.debugging_opts.no_parallel_llvm {
1306 helper.request_token();
1311 // In this branch, we know that everything has been codegened,
1312 // so it's just a matter of determining whether the implicit
1313 // Token is free to use for LLVM work.
1314 match main_thread_worker_state {
1315 MainThreadWorkerState::Idle => {
1316 if let Some((item, _)) = work_items.pop() {
1317 let cgcx = CodegenContext {
1318 worker: get_worker_id(&mut free_worker_ids),
1321 maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1322 &mut llvm_start_time);
1323 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1324 spawn_work(cgcx, item);
1326 // There is no unstarted work, so let the main thread
1327 // take over for a running worker. Otherwise the
1328 // implicit token would just go to waste.
1329 // We reduce the `running` counter by one. The
1330 // `tokens.truncate()` below will take care of
1331 // giving the Token back.
1332 debug_assert!(running > 0);
1334 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1337 MainThreadWorkerState::Codegenning => {
1338 bug!("codegen worker should not be codegenning after \
1339 codegen was already completed")
1341 MainThreadWorkerState::LLVMing => {
1342 // Already making good use of that token
1347 // Spin up what work we can, only doing this while we've got available
1348 // parallelism slots and work left to spawn.
1349 while !codegen_aborted && work_items.len() > 0 && running < tokens.len() {
1350 let (item, _) = work_items.pop().unwrap();
1352 maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1353 &mut llvm_start_time);
1355 let cgcx = CodegenContext {
1356 worker: get_worker_id(&mut free_worker_ids),
1360 spawn_work(cgcx, item);
1364 // Relinquish accidentally acquired extra tokens
1365 tokens.truncate(running);
1367 // If a thread exits successfully then we drop a token associated
1368 // with that worker and update our `running` count. We may later
1369 // re-acquire a token to continue running more work. We may also not
1370 // actually drop a token here if the worker was running with an
1371 // "ephemeral token"
1372 let mut free_worker = |worker_id| {
1373 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1374 main_thread_worker_state = MainThreadWorkerState::Idle;
1379 free_worker_ids.push(worker_id);
1382 let msg = coordinator_receive.recv().unwrap();
1383 match *msg.downcast::<Message<B>>().ok().unwrap() {
1384 // Save the token locally and the next turn of the loop will use
1385 // this to spawn a new unit of work, or it may get dropped
1386 // immediately if we have no more work to spawn.
1387 Message::Token(token) => {
1392 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1393 // If the main thread token is used for LLVM work
1394 // at the moment, we turn that thread into a regular
1395 // LLVM worker thread, so the main thread is free
1396 // to react to codegen demand.
1397 main_thread_worker_state = MainThreadWorkerState::Idle;
1402 let msg = &format!("failed to acquire jobserver token: {}", e);
1403 shared_emitter.fatal(msg);
1404 // Exit the coordinator thread
1410 Message::CodegenDone { llvm_work_item, cost } => {
1411 // We keep the queue sorted by estimated processing cost,
1412 // so that more expensive items are processed earlier. This
1413 // is good for throughput as it gives the main thread more
1414 // time to fill up the queue and it avoids scheduling
1415 // expensive items to the end.
1416 // Note, however, that this is not ideal for memory
1417 // consumption, as LLVM module sizes are not evenly
1419 let insertion_index =
1420 work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1421 let insertion_index = match insertion_index {
1422 Ok(idx) | Err(idx) => idx
1424 work_items.insert(insertion_index, (llvm_work_item, cost));
1426 if !cgcx.opts.debugging_opts.no_parallel_llvm {
1427 helper.request_token();
1429 assert!(!codegen_aborted);
1430 assert_eq!(main_thread_worker_state,
1431 MainThreadWorkerState::Codegenning);
1432 main_thread_worker_state = MainThreadWorkerState::Idle;
1435 Message::CodegenComplete => {
1436 codegen_done = true;
1437 assert!(!codegen_aborted);
1438 assert_eq!(main_thread_worker_state,
1439 MainThreadWorkerState::Codegenning);
1440 main_thread_worker_state = MainThreadWorkerState::Idle;
1443 // If codegen is aborted that means translation was aborted due
1444 // to some normal-ish compiler error. In this situation we want
1445 // to exit as soon as possible, but we want to make sure all
1446 // existing work has finished. Flag codegen as being done, and
1447 // then conditions above will ensure no more work is spawned but
1448 // we'll keep executing this loop until `running` hits 0.
1449 Message::CodegenAborted => {
1450 assert!(!codegen_aborted);
1451 codegen_done = true;
1452 codegen_aborted = true;
1453 assert_eq!(main_thread_worker_state,
1454 MainThreadWorkerState::Codegenning);
1456 Message::Done { result: Ok(compiled_module), worker_id } => {
1457 free_worker(worker_id);
1458 match compiled_module.kind {
1459 ModuleKind::Regular => {
1460 compiled_modules.push(compiled_module);
1462 ModuleKind::Metadata => {
1463 assert!(compiled_metadata_module.is_none());
1464 compiled_metadata_module = Some(compiled_module);
1466 ModuleKind::Allocator => {
1467 assert!(compiled_allocator_module.is_none());
1468 compiled_allocator_module = Some(compiled_module);
1472 Message::NeedsFatLTO { result, worker_id } => {
1473 assert!(!started_lto);
1474 free_worker(worker_id);
1475 needs_fat_lto.push(result);
1477 Message::NeedsThinLTO { name, thin_buffer, worker_id } => {
1478 assert!(!started_lto);
1479 free_worker(worker_id);
1480 needs_thin_lto.push((name, thin_buffer));
1482 Message::AddImportOnlyModule { module_data, work_product } => {
1483 assert!(!started_lto);
1484 assert!(!codegen_done);
1485 assert_eq!(main_thread_worker_state,
1486 MainThreadWorkerState::Codegenning);
1487 lto_import_only_modules.push((module_data, work_product));
1488 main_thread_worker_state = MainThreadWorkerState::Idle;
1490 // If the thread failed that means it panicked, so we abort immediately.
1491 Message::Done { result: Err(()), worker_id: _ } => {
1492 bug!("worker thread panicked");
1494 Message::CodegenItem => {
1495 bug!("the coordinator should not receive codegen requests")
1500 if let Some(llvm_start_time) = llvm_start_time {
1501 let total_llvm_time = Instant::now().duration_since(llvm_start_time);
1502 // This is the top-level timing for all of LLVM, set the time-depth
1505 print_time_passes_entry(cgcx.time_passes,
1510 // Regardless of what order these modules completed in, report them to
1511 // the backend in the same order every time to ensure that we're handing
1512 // out deterministic results.
1513 compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
1515 Ok(CompiledModules {
1516 modules: compiled_modules,
1517 metadata_module: compiled_metadata_module,
1518 allocator_module: compiled_allocator_module,
1522 // A heuristic that determines if we have enough LLVM WorkItems in the
1523 // queue so that the main thread can do LLVM work instead of codegen
1524 fn queue_full_enough(items_in_queue: usize,
1525 workers_running: usize,
1526 max_workers: usize) -> bool {
1528 items_in_queue > 0 &&
1529 items_in_queue >= max_workers.saturating_sub(workers_running / 2)
1532 fn maybe_start_llvm_timer(config: &ModuleConfig,
1533 llvm_start_time: &mut Option<Instant>) {
1534 // We keep track of the -Ztime-passes output manually,
1535 // since the closure-based interface does not fit well here.
1536 if config.time_passes {
1537 if llvm_start_time.is_none() {
1538 *llvm_start_time = Some(Instant::now());
1544 pub const CODEGEN_WORKER_ID: usize = ::std::usize::MAX;
1546 fn spawn_work<B: ExtraBackendMethods>(
1547 cgcx: CodegenContext<B>,
1550 let depth = time_depth();
1552 thread::spawn(move || {
1553 set_time_depth(depth);
1555 // Set up a destructor which will fire off a message that we're done as
1557 struct Bomb<B: ExtraBackendMethods> {
1558 coordinator_send: Sender<Box<dyn Any + Send>>,
1559 result: Option<WorkItemResult<B>>,
1562 impl<B: ExtraBackendMethods> Drop for Bomb<B> {
1563 fn drop(&mut self) {
1564 let worker_id = self.worker_id;
1565 let msg = match self.result.take() {
1566 Some(WorkItemResult::Compiled(m)) => {
1567 Message::Done::<B> { result: Ok(m), worker_id }
1569 Some(WorkItemResult::NeedsFatLTO(m)) => {
1570 Message::NeedsFatLTO::<B> { result: m, worker_id }
1572 Some(WorkItemResult::NeedsThinLTO(name, thin_buffer)) => {
1573 Message::NeedsThinLTO::<B> { name, thin_buffer, worker_id }
1575 None => Message::Done::<B> { result: Err(()), worker_id }
1577 drop(self.coordinator_send.send(Box::new(msg)));
1581 let mut bomb = Bomb::<B> {
1582 coordinator_send: cgcx.coordinator_send.clone(),
1584 worker_id: cgcx.worker,
1587 // Execute the work itself, and if it finishes successfully then flag
1588 // ourselves as a success as well.
1590 // Note that we ignore any `FatalError` coming out of `execute_work_item`,
1591 // as a diagnostic was already sent off to the main thread - just
1592 // surface that there was an error in this worker.
1594 let _prof_timer = cgcx.prof.generic_activity(&work.name());
1595 execute_work_item(&cgcx, work).ok()
1600 pub fn run_assembler<B: ExtraBackendMethods>(
1601 cgcx: &CodegenContext<B>,
1606 let assembler = cgcx.assembler_cmd
1608 .expect("cgcx.assembler_cmd is missing?");
1610 let pname = &assembler.name;
1611 let mut cmd = assembler.cmd.clone();
1612 cmd.arg("-c").arg("-o").arg(object).arg(assembly);
1613 debug!("{:?}", cmd);
1615 match cmd.output() {
1617 if !prog.status.success() {
1618 let mut note = prog.stderr.clone();
1619 note.extend_from_slice(&prog.stdout);
1621 handler.struct_err(&format!("linking with `{}` failed: {}",
1624 .note(&format!("{:?}", &cmd))
1625 .note(str::from_utf8(¬e[..]).unwrap())
1627 handler.abort_if_errors();
1631 handler.err(&format!("could not exec the linker `{}`: {}", pname.display(), e));
1632 handler.abort_if_errors();
1638 enum SharedEmitterMessage {
1639 Diagnostic(Diagnostic),
1640 InlineAsmError(u32, String),
1646 pub struct SharedEmitter {
1647 sender: Sender<SharedEmitterMessage>,
1650 pub struct SharedEmitterMain {
1651 receiver: Receiver<SharedEmitterMessage>,
1654 impl SharedEmitter {
1655 pub fn new() -> (SharedEmitter, SharedEmitterMain) {
1656 let (sender, receiver) = channel();
1658 (SharedEmitter { sender }, SharedEmitterMain { receiver })
1661 pub fn inline_asm_error(&self, cookie: u32, msg: String) {
1662 drop(self.sender.send(SharedEmitterMessage::InlineAsmError(cookie, msg)));
1665 pub fn fatal(&self, msg: &str) {
1666 drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1670 impl Emitter for SharedEmitter {
1671 fn emit_diagnostic(&mut self, db: &rustc_errors::Diagnostic) {
1672 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1674 code: db.code.clone(),
1677 for child in &db.children {
1678 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1679 msg: child.message(),
1684 drop(self.sender.send(SharedEmitterMessage::AbortIfErrors));
1688 impl SharedEmitterMain {
1689 pub fn check(&self, sess: &Session, blocking: bool) {
1691 let message = if blocking {
1692 match self.receiver.recv() {
1693 Ok(message) => Ok(message),
1697 match self.receiver.try_recv() {
1698 Ok(message) => Ok(message),
1704 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
1705 let handler = sess.diagnostic();
1706 let mut d = rustc_errors::Diagnostic::new(diag.lvl, &diag.msg);
1707 if let Some(code) = diag.code {
1710 handler.emit_diagnostic(&d);
1711 handler.abort_if_errors_and_should_abort();
1713 Ok(SharedEmitterMessage::InlineAsmError(cookie, msg)) => {
1714 sess.span_err(ExpnId::from_u32(cookie).expn_data().call_site, &msg)
1716 Ok(SharedEmitterMessage::AbortIfErrors) => {
1717 sess.abort_if_errors();
1719 Ok(SharedEmitterMessage::Fatal(msg)) => {
1731 pub struct OngoingCodegen<B: ExtraBackendMethods> {
1733 pub crate_name: Symbol,
1734 pub crate_hash: Svh,
1735 pub metadata: EncodedMetadata,
1736 pub windows_subsystem: Option<String>,
1737 pub linker_info: LinkerInfo,
1738 pub crate_info: CrateInfo,
1739 pub coordinator_send: Sender<Box<dyn Any + Send>>,
1740 pub codegen_worker_receive: Receiver<Message<B>>,
1741 pub shared_emitter_main: SharedEmitterMain,
1742 pub future: thread::JoinHandle<Result<CompiledModules, ()>>,
1743 pub output_filenames: Arc<OutputFilenames>,
1746 impl<B: ExtraBackendMethods> OngoingCodegen<B> {
1750 ) -> (CodegenResults, FxHashMap<WorkProductId, WorkProduct>) {
1751 self.shared_emitter_main.check(sess, true);
1752 let compiled_modules = match self.future.join() {
1753 Ok(Ok(compiled_modules)) => compiled_modules,
1755 sess.abort_if_errors();
1756 panic!("expected abort due to worker thread errors")
1759 bug!("panic during codegen/LLVM phase");
1763 sess.cgu_reuse_tracker.check_expected_reuse(sess);
1765 sess.abort_if_errors();
1768 copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess,
1770 produce_final_output_artifacts(sess,
1772 &self.output_filenames);
1774 // FIXME: time_llvm_passes support - does this use a global context or
1776 if sess.codegen_units() == 1 && sess.time_llvm_passes() {
1777 self.backend.print_pass_timings()
1780 sess.prof.generic_activity_end("codegen_and_optimize_crate");
1783 crate_name: self.crate_name,
1784 crate_hash: self.crate_hash,
1785 metadata: self.metadata,
1786 windows_subsystem: self.windows_subsystem,
1787 linker_info: self.linker_info,
1788 crate_info: self.crate_info,
1790 modules: compiled_modules.modules,
1791 allocator_module: compiled_modules.allocator_module,
1792 metadata_module: compiled_modules.metadata_module,
1796 pub fn submit_pre_codegened_module_to_llvm(
1799 module: ModuleCodegen<B::Module>,
1801 self.wait_for_signal_to_codegen_item();
1802 self.check_for_errors(tcx.sess);
1804 // These are generally cheap and won't throw off scheduling.
1806 submit_codegened_module_to_llvm(&self.backend, &self.coordinator_send, module, cost);
1809 pub fn codegen_finished(&self, tcx: TyCtxt<'_>) {
1810 self.wait_for_signal_to_codegen_item();
1811 self.check_for_errors(tcx.sess);
1812 drop(self.coordinator_send.send(Box::new(Message::CodegenComplete::<B>)));
1815 /// Consumes this context indicating that codegen was entirely aborted, and
1816 /// we need to exit as quickly as possible.
1818 /// This method blocks the current thread until all worker threads have
1819 /// finished, and all worker threads should have exited or be real close to
1820 /// exiting at this point.
1821 pub fn codegen_aborted(self) {
1822 // Signal to the coordinator it should spawn no more work and start
1824 drop(self.coordinator_send.send(Box::new(Message::CodegenAborted::<B>)));
1825 drop(self.future.join());
1828 pub fn check_for_errors(&self, sess: &Session) {
1829 self.shared_emitter_main.check(sess, false);
1832 pub fn wait_for_signal_to_codegen_item(&self) {
1833 match self.codegen_worker_receive.recv() {
1834 Ok(Message::CodegenItem) => {
1837 Ok(_) => panic!("unexpected message"),
1839 // One of the LLVM threads must have panicked, fall through so
1840 // error handling can be reached.
1846 pub fn submit_codegened_module_to_llvm<B: ExtraBackendMethods>(
1848 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
1849 module: ModuleCodegen<B::Module>,
1852 let llvm_work_item = WorkItem::Optimize(module);
1853 drop(tx_to_llvm_workers.send(Box::new(Message::CodegenDone::<B> {
1859 pub fn submit_post_lto_module_to_llvm<B: ExtraBackendMethods>(
1861 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
1862 module: CachedModuleCodegen,
1864 let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
1865 drop(tx_to_llvm_workers.send(Box::new(Message::CodegenDone::<B> {
1871 pub fn submit_pre_lto_module_to_llvm<B: ExtraBackendMethods>(
1874 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
1875 module: CachedModuleCodegen,
1877 let filename = pre_lto_bitcode_filename(&module.name);
1878 let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
1879 let file = fs::File::open(&bc_path).unwrap_or_else(|e| {
1880 panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e)
1884 memmap::Mmap::map(&file).unwrap_or_else(|e| {
1885 panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
1888 // Schedule the module to be loaded
1889 drop(tx_to_llvm_workers.send(Box::new(Message::AddImportOnlyModule::<B> {
1890 module_data: SerializedModule::FromUncompressedFile(mmap),
1891 work_product: module.source,
1895 pub fn pre_lto_bitcode_filename(module_name: &str) -> String {
1896 format!("{}.{}", module_name, PRE_LTO_BC_EXT)
1899 fn msvc_imps_needed(tcx: TyCtxt<'_>) -> bool {
1900 // This should never be true (because it's not supported). If it is true,
1901 // something is wrong with commandline arg validation.
1902 assert!(!(tcx.sess.opts.cg.linker_plugin_lto.enabled() &&
1903 tcx.sess.target.target.options.is_like_msvc &&
1904 tcx.sess.opts.cg.prefer_dynamic));
1906 tcx.sess.target.target.options.is_like_msvc &&
1907 tcx.sess.crate_types.borrow().iter().any(|ct| *ct == config::CrateType::Rlib) &&
1908 // ThinLTO can't handle this workaround in all cases, so we don't
1909 // emit the `__imp_` symbols. Instead we make them unnecessary by disallowing
1910 // dynamic linking when linker plugin LTO is enabled.
1911 !tcx.sess.opts.cg.linker_plugin_lto.enabled()