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_data_structures::sync::Lrc;
26 use rustc_errors::{Handler, Level, FatalError, DiagnosticId, SourceMapperDyn};
27 use rustc_errors::emitter::{Emitter};
28 use rustc_target::spec::MergeFunctions;
30 use syntax::ext::hygiene::ExpnId;
31 use syntax_pos::symbol::{Symbol, sym};
32 use jobserver::{Client, Acquired};
38 use std::path::{Path, PathBuf};
41 use std::sync::mpsc::{channel, Sender, Receiver};
42 use std::time::Instant;
45 const PRE_LTO_BC_EXT: &str = "pre-lto.bc";
47 /// Module-specific configuration for `optimize_and_codegen`.
48 pub struct ModuleConfig {
49 /// Names of additional optimization passes to run.
50 pub passes: Vec<String>,
51 /// Some(level) to optimize at a certain level, or None to run
52 /// absolutely no optimizations (used for the metadata module).
53 pub opt_level: Option<config::OptLevel>,
55 /// Some(level) to optimize binary size, or None to not affect program size.
56 pub opt_size: Option<config::OptLevel>,
58 pub pgo_gen: SwitchWithOptPath,
59 pub pgo_use: Option<PathBuf>,
61 // Flags indicating which outputs to produce.
62 pub emit_pre_lto_bc: bool,
63 pub emit_no_opt_bc: bool,
65 pub emit_bc_compressed: bool,
66 pub emit_lto_bc: bool,
70 // Miscellaneous flags. These are mostly copied from command-line
72 pub verify_llvm_ir: bool,
73 pub no_prepopulate_passes: bool,
74 pub no_builtins: bool,
75 pub time_passes: bool,
76 pub vectorize_loop: bool,
77 pub vectorize_slp: bool,
78 pub merge_functions: bool,
79 pub inline_threshold: Option<usize>,
80 // Instead of creating an object file by doing LLVM codegen, just
81 // make the object file bitcode. Provides easy compatibility with
82 // emscripten's ecc compiler, when used as the linker.
83 pub obj_is_bitcode: bool,
84 pub no_integrated_as: bool,
85 pub embed_bitcode: bool,
86 pub embed_bitcode_marker: bool,
90 fn new(passes: Vec<String>) -> ModuleConfig {
96 pgo_gen: SwitchWithOptPath::Disabled,
99 emit_no_opt_bc: false,
100 emit_pre_lto_bc: false,
102 emit_bc_compressed: false,
107 obj_is_bitcode: false,
108 embed_bitcode: false,
109 embed_bitcode_marker: false,
110 no_integrated_as: false,
112 verify_llvm_ir: false,
113 no_prepopulate_passes: false,
116 vectorize_loop: false,
117 vectorize_slp: false,
118 merge_functions: false,
119 inline_threshold: None
123 fn set_flags(&mut self, sess: &Session, no_builtins: bool) {
124 self.verify_llvm_ir = sess.verify_llvm_ir();
125 self.no_prepopulate_passes = sess.opts.cg.no_prepopulate_passes;
126 self.no_builtins = no_builtins || sess.target.target.options.no_builtins;
127 self.time_passes = sess.time_extended();
128 self.inline_threshold = sess.opts.cg.inline_threshold;
129 self.obj_is_bitcode = sess.target.target.options.obj_is_bitcode ||
130 sess.opts.cg.linker_plugin_lto.enabled();
131 let embed_bitcode = sess.target.target.options.embed_bitcode ||
132 sess.opts.debugging_opts.embed_bitcode;
134 match sess.opts.optimize {
135 config::OptLevel::No |
136 config::OptLevel::Less => {
137 self.embed_bitcode_marker = embed_bitcode;
139 _ => self.embed_bitcode = embed_bitcode,
143 // Copy what clang does by turning on loop vectorization at O2 and
144 // slp vectorization at O3. Otherwise configure other optimization aspects
145 // of this pass manager builder.
146 // Turn off vectorization for emscripten, as it's not very well supported.
147 self.vectorize_loop = !sess.opts.cg.no_vectorize_loops &&
148 (sess.opts.optimize == config::OptLevel::Default ||
149 sess.opts.optimize == config::OptLevel::Aggressive) &&
150 !sess.target.target.options.is_like_emscripten;
152 self.vectorize_slp = !sess.opts.cg.no_vectorize_slp &&
153 sess.opts.optimize == config::OptLevel::Aggressive &&
154 !sess.target.target.options.is_like_emscripten;
156 // Some targets (namely, NVPTX) interact badly with the MergeFunctions
157 // pass. This is because MergeFunctions can generate new function calls
158 // which may interfere with the target calling convention; e.g. for the
159 // NVPTX target, PTX kernels should not call other PTX kernels.
160 // MergeFunctions can also be configured to generate aliases instead,
161 // but aliases are not supported by some backends (again, NVPTX).
162 // Therefore, allow targets to opt out of the MergeFunctions pass,
163 // but otherwise keep the pass enabled (at O2 and O3) since it can be
164 // useful for reducing code size.
165 self.merge_functions = match sess.opts.debugging_opts.merge_functions
166 .unwrap_or(sess.target.target.options.merge_functions) {
167 MergeFunctions::Disabled => false,
168 MergeFunctions::Trampolines |
169 MergeFunctions::Aliases => {
170 sess.opts.optimize == config::OptLevel::Default ||
171 sess.opts.optimize == config::OptLevel::Aggressive
176 pub fn bitcode_needed(&self) -> bool {
177 self.emit_bc || self.obj_is_bitcode
178 || self.emit_bc_compressed || self.embed_bitcode
182 /// Assembler name and command used by codegen when no_integrated_as is enabled
183 pub struct AssemblerCommand {
188 // HACK(eddyb) work around `#[derive]` producing wrong bounds for `Clone`.
189 pub struct TargetMachineFactory<B: WriteBackendMethods>(
190 pub Arc<dyn Fn() -> Result<B::TargetMachine, String> + Send + Sync>,
193 impl<B: WriteBackendMethods> Clone for TargetMachineFactory<B> {
194 fn clone(&self) -> Self {
195 TargetMachineFactory(self.0.clone())
199 /// Additional resources used by optimize_and_codegen (not module specific)
201 pub struct CodegenContext<B: WriteBackendMethods> {
202 // Resources needed when running LTO
204 pub time_passes: bool,
205 pub prof: SelfProfilerRef,
207 pub no_landing_pads: bool,
208 pub save_temps: bool,
209 pub fewer_names: bool,
210 pub exported_symbols: Option<Arc<ExportedSymbols>>,
211 pub opts: Arc<config::Options>,
212 pub crate_types: Vec<config::CrateType>,
213 pub each_linked_rlib_for_lto: Vec<(CrateNum, PathBuf)>,
214 pub output_filenames: Arc<OutputFilenames>,
215 pub regular_module_config: Arc<ModuleConfig>,
216 pub metadata_module_config: Arc<ModuleConfig>,
217 pub allocator_module_config: Arc<ModuleConfig>,
218 pub tm_factory: TargetMachineFactory<B>,
219 pub msvc_imps_needed: bool,
220 pub target_pointer_width: String,
221 pub target_arch: String,
222 pub debuginfo: config::DebugInfo,
224 // Number of cgus excluding the allocator/metadata modules
225 pub total_cgus: usize,
226 // Handler to use for diagnostics produced during codegen.
227 pub diag_emitter: SharedEmitter,
228 // LLVM passes added by plugins.
229 pub plugin_passes: Vec<String>,
230 // LLVM optimizations for which we want to print remarks.
232 // Worker thread number
234 // The incremental compilation session directory, or None if we are not
235 // compiling incrementally
236 pub incr_comp_session_dir: Option<PathBuf>,
237 // Used to update CGU re-use information during the thinlto phase.
238 pub cgu_reuse_tracker: CguReuseTracker,
239 // Channel back to the main control thread to send messages to
240 pub coordinator_send: Sender<Box<dyn Any + Send>>,
241 // The assembler command if no_integrated_as option is enabled, None otherwise
242 pub assembler_cmd: Option<Arc<AssemblerCommand>>
245 impl<B: WriteBackendMethods> CodegenContext<B> {
246 pub fn create_diag_handler(&self) -> Handler {
247 Handler::with_emitter(true, None, Box::new(self.diag_emitter.clone()))
250 pub fn config(&self, kind: ModuleKind) -> &ModuleConfig {
252 ModuleKind::Regular => &self.regular_module_config,
253 ModuleKind::Metadata => &self.metadata_module_config,
254 ModuleKind::Allocator => &self.allocator_module_config,
259 fn generate_lto_work<B: ExtraBackendMethods>(
260 cgcx: &CodegenContext<B>,
261 needs_fat_lto: Vec<FatLTOInput<B>>,
262 needs_thin_lto: Vec<(String, B::ThinBuffer)>,
263 import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>
264 ) -> Vec<(WorkItem<B>, u64)> {
265 let _prof_timer = cgcx.prof.generic_activity("codegen_run_lto");
267 let (lto_modules, copy_jobs) = if !needs_fat_lto.is_empty() {
268 assert!(needs_thin_lto.is_empty());
269 let lto_module = B::run_fat_lto(
274 .unwrap_or_else(|e| e.raise());
275 (vec![lto_module], vec![])
277 assert!(needs_fat_lto.is_empty());
278 B::run_thin_lto(cgcx, needs_thin_lto, import_only_modules)
279 .unwrap_or_else(|e| e.raise())
282 let result = lto_modules.into_iter().map(|module| {
283 let cost = module.cost();
284 (WorkItem::LTO(module), cost)
285 }).chain(copy_jobs.into_iter().map(|wp| {
286 (WorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
287 name: wp.cgu_name.clone(),
295 pub struct CompiledModules {
296 pub modules: Vec<CompiledModule>,
297 pub metadata_module: Option<CompiledModule>,
298 pub allocator_module: Option<CompiledModule>,
301 fn need_crate_bitcode_for_rlib(sess: &Session) -> bool {
302 sess.crate_types.borrow().contains(&config::CrateType::Rlib) &&
303 sess.opts.output_types.contains_key(&OutputType::Exe)
306 fn need_pre_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
307 if sess.opts.incremental.is_none() {
315 Lto::ThinLocal => true,
319 pub fn start_async_codegen<B: ExtraBackendMethods>(
322 metadata: EncodedMetadata,
324 ) -> OngoingCodegen<B> {
325 let (coordinator_send, coordinator_receive) = channel();
328 let crate_name = tcx.crate_name(LOCAL_CRATE);
329 let crate_hash = tcx.crate_hash(LOCAL_CRATE);
330 let no_builtins = attr::contains_name(&tcx.hir().krate().attrs, sym::no_builtins);
331 let subsystem = attr::first_attr_value_str_by_name(&tcx.hir().krate().attrs,
332 sym::windows_subsystem);
333 let windows_subsystem = subsystem.map(|subsystem| {
334 if subsystem != sym::windows && subsystem != sym::console {
335 tcx.sess.fatal(&format!("invalid windows subsystem `{}`, only \
336 `windows` and `console` are allowed",
339 subsystem.to_string()
342 let linker_info = LinkerInfo::new(tcx);
343 let crate_info = CrateInfo::new(tcx);
345 // Figure out what we actually need to build.
346 let mut modules_config = ModuleConfig::new(sess.opts.cg.passes.clone());
347 let mut metadata_config = ModuleConfig::new(vec![]);
348 let mut allocator_config = ModuleConfig::new(vec![]);
350 if let Some(ref sanitizer) = sess.opts.debugging_opts.sanitizer {
352 Sanitizer::Address => {
353 modules_config.passes.push("asan".to_owned());
354 modules_config.passes.push("asan-module".to_owned());
356 Sanitizer::Memory => {
357 modules_config.passes.push("msan".to_owned())
359 Sanitizer::Thread => {
360 modules_config.passes.push("tsan".to_owned())
366 if sess.opts.debugging_opts.profile {
367 modules_config.passes.push("insert-gcov-profiling".to_owned())
370 modules_config.pgo_gen = sess.opts.cg.profile_generate.clone();
371 modules_config.pgo_use = sess.opts.cg.profile_use.clone();
373 modules_config.opt_level = Some(sess.opts.optimize);
374 modules_config.opt_size = Some(sess.opts.optimize);
376 // Save all versions of the bytecode if we're saving our temporaries.
377 if sess.opts.cg.save_temps {
378 modules_config.emit_no_opt_bc = true;
379 modules_config.emit_pre_lto_bc = true;
380 modules_config.emit_bc = true;
381 modules_config.emit_lto_bc = true;
382 metadata_config.emit_bc = true;
383 allocator_config.emit_bc = true;
386 // Emit compressed bitcode files for the crate if we're emitting an rlib.
387 // Whenever an rlib is created, the bitcode is inserted into the archive in
388 // order to allow LTO against it.
389 if need_crate_bitcode_for_rlib(sess) {
390 modules_config.emit_bc_compressed = true;
391 allocator_config.emit_bc_compressed = true;
394 modules_config.emit_pre_lto_bc =
395 need_pre_lto_bitcode_for_incr_comp(sess);
397 modules_config.no_integrated_as = tcx.sess.opts.cg.no_integrated_as ||
398 tcx.sess.target.target.options.no_integrated_as;
400 for output_type in sess.opts.output_types.keys() {
402 OutputType::Bitcode => { modules_config.emit_bc = true; }
403 OutputType::LlvmAssembly => { modules_config.emit_ir = true; }
404 OutputType::Assembly => {
405 modules_config.emit_asm = true;
406 // If we're not using the LLVM assembler, this function
407 // could be invoked specially with output_type_assembly, so
408 // in this case we still want the metadata object file.
409 if !sess.opts.output_types.contains_key(&OutputType::Assembly) {
410 metadata_config.emit_obj = true;
411 allocator_config.emit_obj = true;
414 OutputType::Object => { modules_config.emit_obj = true; }
415 OutputType::Metadata => { metadata_config.emit_obj = true; }
417 modules_config.emit_obj = true;
418 metadata_config.emit_obj = true;
419 allocator_config.emit_obj = true;
421 OutputType::Mir => {}
422 OutputType::DepInfo => {}
426 modules_config.set_flags(sess, no_builtins);
427 metadata_config.set_flags(sess, no_builtins);
428 allocator_config.set_flags(sess, no_builtins);
430 // Exclude metadata and allocator modules from time_passes output, since
431 // they throw off the "LLVM passes" measurement.
432 metadata_config.time_passes = false;
433 allocator_config.time_passes = false;
435 let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
436 let (codegen_worker_send, codegen_worker_receive) = channel();
438 let coordinator_thread = start_executing_work(backend.clone(),
445 sess.jobserver.clone(),
446 Arc::new(modules_config),
447 Arc::new(metadata_config),
448 Arc::new(allocator_config),
449 coordinator_send.clone());
461 codegen_worker_receive,
463 future: coordinator_thread,
464 output_filenames: tcx.output_filenames(LOCAL_CRATE),
468 fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
470 compiled_modules: &CompiledModules,
471 ) -> FxHashMap<WorkProductId, WorkProduct> {
472 let mut work_products = FxHashMap::default();
474 if sess.opts.incremental.is_none() {
475 return work_products;
478 for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
479 let mut files = vec![];
481 if let Some(ref path) = module.object {
482 files.push((WorkProductFileKind::Object, path.clone()));
484 if let Some(ref path) = module.bytecode {
485 files.push((WorkProductFileKind::Bytecode, path.clone()));
487 if let Some(ref path) = module.bytecode_compressed {
488 files.push((WorkProductFileKind::BytecodeCompressed, path.clone()));
491 if let Some((id, product)) =
492 copy_cgu_workproducts_to_incr_comp_cache_dir(sess, &module.name, &files) {
493 work_products.insert(id, product);
500 fn produce_final_output_artifacts(sess: &Session,
501 compiled_modules: &CompiledModules,
502 crate_output: &OutputFilenames) {
503 let mut user_wants_bitcode = false;
504 let mut user_wants_objects = false;
506 // Produce final compile outputs.
507 let copy_gracefully = |from: &Path, to: &Path| {
508 if let Err(e) = fs::copy(from, to) {
509 sess.err(&format!("could not copy {:?} to {:?}: {}", from, to, e));
513 let copy_if_one_unit = |output_type: OutputType,
514 keep_numbered: bool| {
515 if compiled_modules.modules.len() == 1 {
516 // 1) Only one codegen unit. In this case it's no difficulty
517 // to copy `foo.0.x` to `foo.x`.
518 let module_name = Some(&compiled_modules.modules[0].name[..]);
519 let path = crate_output.temp_path(output_type, module_name);
520 copy_gracefully(&path,
521 &crate_output.path(output_type));
522 if !sess.opts.cg.save_temps && !keep_numbered {
523 // The user just wants `foo.x`, not `foo.#module-name#.x`.
527 let ext = crate_output.temp_path(output_type, None)
534 if crate_output.outputs.contains_key(&output_type) {
535 // 2) Multiple codegen units, with `--emit foo=some_name`. We have
536 // no good solution for this case, so warn the user.
537 sess.warn(&format!("ignoring emit path because multiple .{} files \
538 were produced", ext));
539 } else if crate_output.single_output_file.is_some() {
540 // 3) Multiple codegen units, with `-o some_name`. We have
541 // no good solution for this case, so warn the user.
542 sess.warn(&format!("ignoring -o because multiple .{} files \
543 were produced", ext));
545 // 4) Multiple codegen units, but no explicit name. We
546 // just leave the `foo.0.x` files in place.
547 // (We don't have to do any work in this case.)
552 // Flag to indicate whether the user explicitly requested bitcode.
553 // Otherwise, we produced it only as a temporary output, and will need
555 for output_type in crate_output.outputs.keys() {
557 OutputType::Bitcode => {
558 user_wants_bitcode = true;
559 // Copy to .bc, but always keep the .0.bc. There is a later
560 // check to figure out if we should delete .0.bc files, or keep
561 // them for making an rlib.
562 copy_if_one_unit(OutputType::Bitcode, true);
564 OutputType::LlvmAssembly => {
565 copy_if_one_unit(OutputType::LlvmAssembly, false);
567 OutputType::Assembly => {
568 copy_if_one_unit(OutputType::Assembly, false);
570 OutputType::Object => {
571 user_wants_objects = true;
572 copy_if_one_unit(OutputType::Object, true);
575 OutputType::Metadata |
577 OutputType::DepInfo => {}
581 // Clean up unwanted temporary files.
583 // We create the following files by default:
584 // - #crate#.#module-name#.bc
585 // - #crate#.#module-name#.o
586 // - #crate#.crate.metadata.bc
587 // - #crate#.crate.metadata.o
588 // - #crate#.o (linked from crate.##.o)
589 // - #crate#.bc (copied from crate.##.bc)
590 // We may create additional files if requested by the user (through
591 // `-C save-temps` or `--emit=` flags).
593 if !sess.opts.cg.save_temps {
594 // Remove the temporary .#module-name#.o objects. If the user didn't
595 // explicitly request bitcode (with --emit=bc), and the bitcode is not
596 // needed for building an rlib, then we must remove .#module-name#.bc as
599 // Specific rules for keeping .#module-name#.bc:
600 // - If the user requested bitcode (`user_wants_bitcode`), and
601 // codegen_units > 1, then keep it.
602 // - If the user requested bitcode but codegen_units == 1, then we
603 // can toss .#module-name#.bc because we copied it to .bc earlier.
604 // - If we're not building an rlib and the user didn't request
605 // bitcode, then delete .#module-name#.bc.
606 // If you change how this works, also update back::link::link_rlib,
607 // where .#module-name#.bc files are (maybe) deleted after making an
609 let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
611 let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units() > 1;
613 let keep_numbered_objects = needs_crate_object ||
614 (user_wants_objects && sess.codegen_units() > 1);
616 for module in compiled_modules.modules.iter() {
617 if let Some(ref path) = module.object {
618 if !keep_numbered_objects {
623 if let Some(ref path) = module.bytecode {
624 if !keep_numbered_bitcode {
630 if !user_wants_bitcode {
631 if let Some(ref metadata_module) = compiled_modules.metadata_module {
632 if let Some(ref path) = metadata_module.bytecode {
637 if let Some(ref allocator_module) = compiled_modules.allocator_module {
638 if let Some(ref path) = allocator_module.bytecode {
645 // We leave the following files around by default:
647 // - #crate#.crate.metadata.o
649 // These are used in linking steps and will be cleaned up afterward.
652 pub fn dump_incremental_data(_codegen_results: &CodegenResults) {
653 // FIXME(mw): This does not work at the moment because the situation has
654 // become more complicated due to incremental LTO. Now a CGU
655 // can have more than two caching states.
656 // println!("[incremental] Re-using {} out of {} modules",
657 // codegen_results.modules.iter().filter(|m| m.pre_existing).count(),
658 // codegen_results.modules.len());
661 pub enum WorkItem<B: WriteBackendMethods> {
662 /// Optimize a newly codegened, totally unoptimized module.
663 Optimize(ModuleCodegen<B::Module>),
664 /// Copy the post-LTO artifacts from the incremental cache to the output
666 CopyPostLtoArtifacts(CachedModuleCodegen),
667 /// Performs (Thin)LTO on the given module.
668 LTO(lto::LtoModuleCodegen<B>),
671 impl<B: WriteBackendMethods> WorkItem<B> {
672 pub fn module_kind(&self) -> ModuleKind {
674 WorkItem::Optimize(ref m) => m.kind,
675 WorkItem::CopyPostLtoArtifacts(_) |
676 WorkItem::LTO(_) => ModuleKind::Regular,
680 pub fn name(&self) -> String {
682 WorkItem::Optimize(ref m) => format!("optimize: {}", m.name),
683 WorkItem::CopyPostLtoArtifacts(ref m) => format!("copy post LTO artifacts: {}", m.name),
684 WorkItem::LTO(ref m) => format!("lto: {}", m.name()),
689 enum WorkItemResult<B: WriteBackendMethods> {
690 Compiled(CompiledModule),
691 NeedsFatLTO(FatLTOInput<B>),
692 NeedsThinLTO(String, B::ThinBuffer),
695 pub enum FatLTOInput<B: WriteBackendMethods> {
698 buffer: B::ModuleBuffer,
700 InMemory(ModuleCodegen<B::Module>),
703 fn execute_work_item<B: ExtraBackendMethods>(
704 cgcx: &CodegenContext<B>,
705 work_item: WorkItem<B>,
706 ) -> Result<WorkItemResult<B>, FatalError> {
707 let module_config = cgcx.config(work_item.module_kind());
710 WorkItem::Optimize(module) => {
711 execute_optimize_work_item(cgcx, module, module_config)
713 WorkItem::CopyPostLtoArtifacts(module) => {
714 execute_copy_from_cache_work_item(cgcx, module, module_config)
716 WorkItem::LTO(module) => {
717 execute_lto_work_item(cgcx, module, module_config)
722 // Actual LTO type we end up chosing based on multiple factors.
723 enum ComputedLtoType {
729 fn execute_optimize_work_item<B: ExtraBackendMethods>(
730 cgcx: &CodegenContext<B>,
731 module: ModuleCodegen<B::Module>,
732 module_config: &ModuleConfig,
733 ) -> Result<WorkItemResult<B>, FatalError> {
734 let diag_handler = cgcx.create_diag_handler();
737 B::optimize(cgcx, &diag_handler, &module, module_config)?;
740 // After we've done the initial round of optimizations we need to
741 // decide whether to synchronously codegen this module or ship it
742 // back to the coordinator thread for further LTO processing (which
743 // has to wait for all the initial modules to be optimized).
745 // If the linker does LTO, we don't have to do it. Note that we
746 // keep doing full LTO, if it is requested, as not to break the
747 // assumption that the output will be a single module.
748 let linker_does_lto = cgcx.opts.cg.linker_plugin_lto.enabled();
750 // When we're automatically doing ThinLTO for multi-codegen-unit
751 // builds we don't actually want to LTO the allocator modules if
752 // it shows up. This is due to various linker shenanigans that
753 // we'll encounter later.
754 let is_allocator = module.kind == ModuleKind::Allocator;
756 // We ignore a request for full crate grath LTO if the cate type
757 // is only an rlib, as there is no full crate graph to process,
758 // that'll happen later.
760 // This use case currently comes up primarily for targets that
761 // require LTO so the request for LTO is always unconditionally
762 // passed down to the backend, but we don't actually want to do
763 // anything about it yet until we've got a final product.
764 let is_rlib = cgcx.crate_types.len() == 1
765 && cgcx.crate_types[0] == config::CrateType::Rlib;
767 // Metadata modules never participate in LTO regardless of the lto
769 let lto_type = if module.kind == ModuleKind::Metadata {
773 Lto::ThinLocal if !linker_does_lto && !is_allocator
774 => ComputedLtoType::Thin,
775 Lto::Thin if !linker_does_lto && !is_rlib
776 => ComputedLtoType::Thin,
777 Lto::Fat if !is_rlib => ComputedLtoType::Fat,
778 _ => ComputedLtoType::No,
782 // If we're doing some form of incremental LTO then we need to be sure to
783 // save our module to disk first.
784 let bitcode = if cgcx.config(module.kind).emit_pre_lto_bc {
785 let filename = pre_lto_bitcode_filename(&module.name);
786 cgcx.incr_comp_session_dir.as_ref().map(|path| path.join(&filename))
792 ComputedLtoType::No => {
793 let module = unsafe {
794 B::codegen(cgcx, &diag_handler, module, module_config)?
796 WorkItemResult::Compiled(module)
798 ComputedLtoType::Thin => {
799 let (name, thin_buffer) = B::prepare_thin(module);
800 if let Some(path) = bitcode {
801 fs::write(&path, thin_buffer.data()).unwrap_or_else(|e| {
802 panic!("Error writing pre-lto-bitcode file `{}`: {}",
807 WorkItemResult::NeedsThinLTO(name, thin_buffer)
809 ComputedLtoType::Fat => {
812 let (name, buffer) = B::serialize_module(module);
813 fs::write(&path, buffer.data()).unwrap_or_else(|e| {
814 panic!("Error writing pre-lto-bitcode file `{}`: {}",
818 WorkItemResult::NeedsFatLTO(FatLTOInput::Serialized { name, buffer })
820 None => WorkItemResult::NeedsFatLTO(FatLTOInput::InMemory(module)),
826 fn execute_copy_from_cache_work_item<B: ExtraBackendMethods>(
827 cgcx: &CodegenContext<B>,
828 module: CachedModuleCodegen,
829 module_config: &ModuleConfig,
830 ) -> Result<WorkItemResult<B>, FatalError> {
831 let incr_comp_session_dir = cgcx.incr_comp_session_dir
834 let mut object = None;
835 let mut bytecode = None;
836 let mut bytecode_compressed = None;
837 for (kind, saved_file) in &module.source.saved_files {
838 let obj_out = match kind {
839 WorkProductFileKind::Object => {
840 let path = cgcx.output_filenames.temp_path(OutputType::Object,
842 object = Some(path.clone());
845 WorkProductFileKind::Bytecode => {
846 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode,
848 bytecode = Some(path.clone());
851 WorkProductFileKind::BytecodeCompressed => {
852 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode,
854 .with_extension(RLIB_BYTECODE_EXTENSION);
855 bytecode_compressed = Some(path.clone());
859 let source_file = in_incr_comp_dir(&incr_comp_session_dir,
861 debug!("copying pre-existing module `{}` from {:?} to {}",
865 if let Err(err) = link_or_copy(&source_file, &obj_out) {
866 let diag_handler = cgcx.create_diag_handler();
867 diag_handler.err(&format!("unable to copy {} to {}: {}",
868 source_file.display(),
874 assert_eq!(object.is_some(), module_config.emit_obj);
875 assert_eq!(bytecode.is_some(), module_config.emit_bc);
876 assert_eq!(bytecode_compressed.is_some(), module_config.emit_bc_compressed);
878 Ok(WorkItemResult::Compiled(CompiledModule {
880 kind: ModuleKind::Regular,
887 fn execute_lto_work_item<B: ExtraBackendMethods>(
888 cgcx: &CodegenContext<B>,
889 mut module: lto::LtoModuleCodegen<B>,
890 module_config: &ModuleConfig,
891 ) -> Result<WorkItemResult<B>, FatalError> {
892 let diag_handler = cgcx.create_diag_handler();
895 let module = module.optimize(cgcx)?;
896 let module = B::codegen(cgcx, &diag_handler, module, module_config)?;
897 Ok(WorkItemResult::Compiled(module))
901 pub enum Message<B: WriteBackendMethods> {
902 Token(io::Result<Acquired>),
904 result: FatLTOInput<B>,
909 thin_buffer: B::ThinBuffer,
913 result: Result<CompiledModule, ()>,
917 llvm_work_item: WorkItem<B>,
920 AddImportOnlyModule {
921 module_data: SerializedModule<B::ModuleBuffer>,
922 work_product: WorkProduct,
931 code: Option<DiagnosticId>,
935 #[derive(PartialEq, Clone, Copy, Debug)]
936 enum MainThreadWorkerState {
942 fn start_executing_work<B: ExtraBackendMethods>(
945 crate_info: &CrateInfo,
946 shared_emitter: SharedEmitter,
947 codegen_worker_send: Sender<Message<B>>,
948 coordinator_receive: Receiver<Box<dyn Any + Send>>,
951 modules_config: Arc<ModuleConfig>,
952 metadata_config: Arc<ModuleConfig>,
953 allocator_config: Arc<ModuleConfig>,
954 tx_to_llvm_workers: Sender<Box<dyn Any + Send>>,
955 ) -> thread::JoinHandle<Result<CompiledModules, ()>> {
956 let coordinator_send = tx_to_llvm_workers;
959 // Compute the set of symbols we need to retain when doing LTO (if we need to)
960 let exported_symbols = {
961 let mut exported_symbols = FxHashMap::default();
963 let copy_symbols = |cnum| {
964 let symbols = tcx.exported_symbols(cnum)
966 .map(|&(s, lvl)| (s.symbol_name(tcx).to_string(), lvl))
974 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
975 Some(Arc::new(exported_symbols))
977 Lto::Fat | Lto::Thin => {
978 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
979 for &cnum in tcx.crates().iter() {
980 exported_symbols.insert(cnum, copy_symbols(cnum));
982 Some(Arc::new(exported_symbols))
987 // First up, convert our jobserver into a helper thread so we can use normal
988 // mpsc channels to manage our messages and such.
989 // After we've requested tokens then we'll, when we can,
990 // get tokens on `coordinator_receive` which will
991 // get managed in the main loop below.
992 let coordinator_send2 = coordinator_send.clone();
993 let helper = jobserver.into_helper_thread(move |token| {
994 drop(coordinator_send2.send(Box::new(Message::Token::<B>(token))));
995 }).expect("failed to spawn helper thread");
997 let mut each_linked_rlib_for_lto = Vec::new();
998 drop(link::each_linked_rlib(crate_info, &mut |cnum, path| {
999 if link::ignored_for_lto(sess, crate_info, cnum) {
1002 each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
1005 let assembler_cmd = if modules_config.no_integrated_as {
1006 // HACK: currently we use linker (gcc) as our assembler
1007 let (linker, flavor) = link::linker_and_flavor(sess);
1009 let (name, mut cmd) = get_linker(sess, &linker, flavor);
1010 cmd.args(&sess.target.target.options.asm_args);
1011 Some(Arc::new(AssemblerCommand {
1019 let ol = if tcx.sess.opts.debugging_opts.no_codegen
1020 || !tcx.sess.opts.output_types.should_codegen() {
1021 // If we know that we won’t be doing codegen, create target machines without optimisation.
1022 config::OptLevel::No
1024 tcx.backend_optimization_level(LOCAL_CRATE)
1026 let cgcx = CodegenContext::<B> {
1027 backend: backend.clone(),
1028 crate_types: sess.crate_types.borrow().clone(),
1029 each_linked_rlib_for_lto,
1031 no_landing_pads: sess.no_landing_pads(),
1032 fewer_names: sess.fewer_names(),
1033 save_temps: sess.opts.cg.save_temps,
1034 opts: Arc::new(sess.opts.clone()),
1035 time_passes: sess.time_extended(),
1036 prof: sess.prof.clone(),
1038 plugin_passes: sess.plugin_llvm_passes.borrow().clone(),
1039 remark: sess.opts.cg.remark.clone(),
1041 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1042 cgu_reuse_tracker: sess.cgu_reuse_tracker.clone(),
1044 diag_emitter: shared_emitter.clone(),
1045 output_filenames: tcx.output_filenames(LOCAL_CRATE),
1046 regular_module_config: modules_config,
1047 metadata_module_config: metadata_config,
1048 allocator_module_config: allocator_config,
1049 tm_factory: TargetMachineFactory(backend.target_machine_factory(tcx.sess, ol, false)),
1051 msvc_imps_needed: msvc_imps_needed(tcx),
1052 target_pointer_width: tcx.sess.target.target.target_pointer_width.clone(),
1053 target_arch: tcx.sess.target.target.arch.clone(),
1054 debuginfo: tcx.sess.opts.debuginfo,
1058 // This is the "main loop" of parallel work happening for parallel codegen.
1059 // It's here that we manage parallelism, schedule work, and work with
1060 // messages coming from clients.
1062 // There are a few environmental pre-conditions that shape how the system
1065 // - Error reporting only can happen on the main thread because that's the
1066 // only place where we have access to the compiler `Session`.
1067 // - LLVM work can be done on any thread.
1068 // - Codegen can only happen on the main thread.
1069 // - Each thread doing substantial work most be in possession of a `Token`
1070 // from the `Jobserver`.
1071 // - The compiler process always holds one `Token`. Any additional `Tokens`
1072 // have to be requested from the `Jobserver`.
1076 // The error reporting restriction is handled separately from the rest: We
1077 // set up a `SharedEmitter` the holds an open channel to the main thread.
1078 // When an error occurs on any thread, the shared emitter will send the
1079 // error message to the receiver main thread (`SharedEmitterMain`). The
1080 // main thread will periodically query this error message queue and emit
1081 // any error messages it has received. It might even abort compilation if
1082 // has received a fatal error. In this case we rely on all other threads
1083 // being torn down automatically with the main thread.
1084 // Since the main thread will often be busy doing codegen work, error
1085 // reporting will be somewhat delayed, since the message queue can only be
1086 // checked in between to work packages.
1088 // Work Processing Infrastructure
1089 // ==============================
1090 // The work processing infrastructure knows three major actors:
1092 // - the coordinator thread,
1093 // - the main thread, and
1094 // - LLVM worker threads
1096 // The coordinator thread is running a message loop. It instructs the main
1097 // thread about what work to do when, and it will spawn off LLVM worker
1098 // threads as open LLVM WorkItems become available.
1100 // The job of the main thread is to codegen CGUs into LLVM work package
1101 // (since the main thread is the only thread that can do this). The main
1102 // thread will block until it receives a message from the coordinator, upon
1103 // which it will codegen one CGU, send it to the coordinator and block
1104 // again. This way the coordinator can control what the main thread is
1107 // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1108 // available, it will spawn off a new LLVM worker thread and let it process
1109 // that a WorkItem. When a LLVM worker thread is done with its WorkItem,
1110 // it will just shut down, which also frees all resources associated with
1111 // the given LLVM module, and sends a message to the coordinator that the
1112 // has been completed.
1116 // The scheduler's goal is to minimize the time it takes to complete all
1117 // work there is, however, we also want to keep memory consumption low
1118 // if possible. These two goals are at odds with each other: If memory
1119 // consumption were not an issue, we could just let the main thread produce
1120 // LLVM WorkItems at full speed, assuring maximal utilization of
1121 // Tokens/LLVM worker threads. However, since codegen usual is faster
1122 // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1123 // WorkItem potentially holds on to a substantial amount of memory.
1125 // So the actual goal is to always produce just enough LLVM WorkItems as
1126 // not to starve our LLVM worker threads. That means, once we have enough
1127 // WorkItems in our queue, we can block the main thread, so it does not
1128 // produce more until we need them.
1130 // Doing LLVM Work on the Main Thread
1131 // ----------------------------------
1132 // Since the main thread owns the compiler processes implicit `Token`, it is
1133 // wasteful to keep it blocked without doing any work. Therefore, what we do
1134 // in this case is: We spawn off an additional LLVM worker thread that helps
1135 // reduce the queue. The work it is doing corresponds to the implicit
1136 // `Token`. The coordinator will mark the main thread as being busy with
1137 // LLVM work. (The actual work happens on another OS thread but we just care
1138 // about `Tokens`, not actual threads).
1140 // When any LLVM worker thread finishes while the main thread is marked as
1141 // "busy with LLVM work", we can do a little switcheroo: We give the Token
1142 // of the just finished thread to the LLVM worker thread that is working on
1143 // behalf of the main thread's implicit Token, thus freeing up the main
1144 // thread again. The coordinator can then again decide what the main thread
1145 // should do. This allows the coordinator to make decisions at more points
1148 // Striking a Balance between Throughput and Memory Consumption
1149 // ------------------------------------------------------------
1150 // Since our two goals, (1) use as many Tokens as possible and (2) keep
1151 // memory consumption as low as possible, are in conflict with each other,
1152 // we have to find a trade off between them. Right now, the goal is to keep
1153 // all workers busy, which means that no worker should find the queue empty
1154 // when it is ready to start.
1155 // How do we do achieve this? Good question :) We actually never know how
1156 // many `Tokens` are potentially available so it's hard to say how much to
1157 // fill up the queue before switching the main thread to LLVM work. Also we
1158 // currently don't have a means to estimate how long a running LLVM worker
1159 // will still be busy with it's current WorkItem. However, we know the
1160 // maximal count of available Tokens that makes sense (=the number of CPU
1161 // cores), so we can take a conservative guess. The heuristic we use here
1162 // is implemented in the `queue_full_enough()` function.
1164 // Some Background on Jobservers
1165 // -----------------------------
1166 // It's worth also touching on the management of parallelism here. We don't
1167 // want to just spawn a thread per work item because while that's optimal
1168 // parallelism it may overload a system with too many threads or violate our
1169 // configuration for the maximum amount of cpu to use for this process. To
1170 // manage this we use the `jobserver` crate.
1172 // Job servers are an artifact of GNU make and are used to manage
1173 // parallelism between processes. A jobserver is a glorified IPC semaphore
1174 // basically. Whenever we want to run some work we acquire the semaphore,
1175 // and whenever we're done with that work we release the semaphore. In this
1176 // manner we can ensure that the maximum number of parallel workers is
1177 // capped at any one point in time.
1179 // LTO and the coordinator thread
1180 // ------------------------------
1182 // The final job the coordinator thread is responsible for is managing LTO
1183 // and how that works. When LTO is requested what we'll to is collect all
1184 // optimized LLVM modules into a local vector on the coordinator. Once all
1185 // modules have been codegened and optimized we hand this to the `lto`
1186 // module for further optimization. The `lto` module will return back a list
1187 // of more modules to work on, which the coordinator will continue to spawn
1190 // Each LLVM module is automatically sent back to the coordinator for LTO if
1191 // necessary. There's already optimizations in place to avoid sending work
1192 // back to the coordinator if LTO isn't requested.
1193 return thread::spawn(move || {
1194 // We pretend to be within the top-level LLVM time-passes task here:
1197 let max_workers = ::num_cpus::get();
1198 let mut worker_id_counter = 0;
1199 let mut free_worker_ids = Vec::new();
1200 let mut get_worker_id = |free_worker_ids: &mut Vec<usize>| {
1201 if let Some(id) = free_worker_ids.pop() {
1204 let id = worker_id_counter;
1205 worker_id_counter += 1;
1210 // This is where we collect codegen units that have gone all the way
1211 // through codegen and LLVM.
1212 let mut compiled_modules = vec![];
1213 let mut compiled_metadata_module = None;
1214 let mut compiled_allocator_module = None;
1215 let mut needs_fat_lto = Vec::new();
1216 let mut needs_thin_lto = Vec::new();
1217 let mut lto_import_only_modules = Vec::new();
1218 let mut started_lto = false;
1219 let mut codegen_aborted = false;
1221 // This flag tracks whether all items have gone through codegens
1222 let mut codegen_done = false;
1224 // This is the queue of LLVM work items that still need processing.
1225 let mut work_items = Vec::<(WorkItem<B>, u64)>::new();
1227 // This are the Jobserver Tokens we currently hold. Does not include
1228 // the implicit Token the compiler process owns no matter what.
1229 let mut tokens = Vec::new();
1231 let mut main_thread_worker_state = MainThreadWorkerState::Idle;
1232 let mut running = 0;
1234 let mut llvm_start_time = None;
1236 // Run the message loop while there's still anything that needs message
1237 // processing. Note that as soon as codegen is aborted we simply want to
1238 // wait for all existing work to finish, so many of the conditions here
1239 // only apply if codegen hasn't been aborted as they represent pending
1241 while !codegen_done ||
1243 (!codegen_aborted && (
1244 work_items.len() > 0 ||
1245 needs_fat_lto.len() > 0 ||
1246 needs_thin_lto.len() > 0 ||
1247 lto_import_only_modules.len() > 0 ||
1248 main_thread_worker_state != MainThreadWorkerState::Idle
1252 // While there are still CGUs to be codegened, the coordinator has
1253 // to decide how to utilize the compiler processes implicit Token:
1254 // For codegenning more CGU or for running them through LLVM.
1256 if main_thread_worker_state == MainThreadWorkerState::Idle {
1257 if !queue_full_enough(work_items.len(), running, max_workers) {
1258 // The queue is not full enough, codegen more items:
1259 if let Err(_) = codegen_worker_send.send(Message::CodegenItem) {
1260 panic!("Could not send Message::CodegenItem to main thread")
1262 main_thread_worker_state = MainThreadWorkerState::Codegenning;
1264 // The queue is full enough to not let the worker
1265 // threads starve. Use the implicit Token to do some
1267 let (item, _) = work_items.pop()
1268 .expect("queue empty - queue_full_enough() broken?");
1269 let cgcx = CodegenContext {
1270 worker: get_worker_id(&mut free_worker_ids),
1273 maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1274 &mut llvm_start_time);
1275 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1276 spawn_work(cgcx, item);
1279 } else if codegen_aborted {
1280 // don't queue up any more work if codegen was aborted, we're
1281 // just waiting for our existing children to finish
1283 // If we've finished everything related to normal codegen
1284 // then it must be the case that we've got some LTO work to do.
1285 // Perform the serial work here of figuring out what we're
1286 // going to LTO and then push a bunch of work items onto our
1288 if work_items.len() == 0 &&
1290 main_thread_worker_state == MainThreadWorkerState::Idle {
1291 assert!(!started_lto);
1294 let needs_fat_lto = mem::take(&mut needs_fat_lto);
1295 let needs_thin_lto = mem::take(&mut needs_thin_lto);
1296 let import_only_modules = mem::take(&mut lto_import_only_modules);
1298 for (work, cost) in generate_lto_work(&cgcx, needs_fat_lto,
1299 needs_thin_lto, import_only_modules) {
1300 let insertion_index = work_items
1301 .binary_search_by_key(&cost, |&(_, cost)| cost)
1302 .unwrap_or_else(|e| e);
1303 work_items.insert(insertion_index, (work, cost));
1304 if !cgcx.opts.debugging_opts.no_parallel_llvm {
1305 helper.request_token();
1310 // In this branch, we know that everything has been codegened,
1311 // so it's just a matter of determining whether the implicit
1312 // Token is free to use for LLVM work.
1313 match main_thread_worker_state {
1314 MainThreadWorkerState::Idle => {
1315 if let Some((item, _)) = work_items.pop() {
1316 let cgcx = CodegenContext {
1317 worker: get_worker_id(&mut free_worker_ids),
1320 maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1321 &mut llvm_start_time);
1322 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1323 spawn_work(cgcx, item);
1325 // There is no unstarted work, so let the main thread
1326 // take over for a running worker. Otherwise the
1327 // implicit token would just go to waste.
1328 // We reduce the `running` counter by one. The
1329 // `tokens.truncate()` below will take care of
1330 // giving the Token back.
1331 debug_assert!(running > 0);
1333 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1336 MainThreadWorkerState::Codegenning => {
1337 bug!("codegen worker should not be codegenning after \
1338 codegen was already completed")
1340 MainThreadWorkerState::LLVMing => {
1341 // Already making good use of that token
1346 // Spin up what work we can, only doing this while we've got available
1347 // parallelism slots and work left to spawn.
1348 while !codegen_aborted && work_items.len() > 0 && running < tokens.len() {
1349 let (item, _) = work_items.pop().unwrap();
1351 maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1352 &mut llvm_start_time);
1354 let cgcx = CodegenContext {
1355 worker: get_worker_id(&mut free_worker_ids),
1359 spawn_work(cgcx, item);
1363 // Relinquish accidentally acquired extra tokens
1364 tokens.truncate(running);
1366 // If a thread exits successfully then we drop a token associated
1367 // with that worker and update our `running` count. We may later
1368 // re-acquire a token to continue running more work. We may also not
1369 // actually drop a token here if the worker was running with an
1370 // "ephemeral token"
1371 let mut free_worker = |worker_id| {
1372 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1373 main_thread_worker_state = MainThreadWorkerState::Idle;
1378 free_worker_ids.push(worker_id);
1381 let msg = coordinator_receive.recv().unwrap();
1382 match *msg.downcast::<Message<B>>().ok().unwrap() {
1383 // Save the token locally and the next turn of the loop will use
1384 // this to spawn a new unit of work, or it may get dropped
1385 // immediately if we have no more work to spawn.
1386 Message::Token(token) => {
1391 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1392 // If the main thread token is used for LLVM work
1393 // at the moment, we turn that thread into a regular
1394 // LLVM worker thread, so the main thread is free
1395 // to react to codegen demand.
1396 main_thread_worker_state = MainThreadWorkerState::Idle;
1401 let msg = &format!("failed to acquire jobserver token: {}", e);
1402 shared_emitter.fatal(msg);
1403 // Exit the coordinator thread
1409 Message::CodegenDone { llvm_work_item, cost } => {
1410 // We keep the queue sorted by estimated processing cost,
1411 // so that more expensive items are processed earlier. This
1412 // is good for throughput as it gives the main thread more
1413 // time to fill up the queue and it avoids scheduling
1414 // expensive items to the end.
1415 // Note, however, that this is not ideal for memory
1416 // consumption, as LLVM module sizes are not evenly
1418 let insertion_index =
1419 work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1420 let insertion_index = match insertion_index {
1421 Ok(idx) | Err(idx) => idx
1423 work_items.insert(insertion_index, (llvm_work_item, cost));
1425 if !cgcx.opts.debugging_opts.no_parallel_llvm {
1426 helper.request_token();
1428 assert!(!codegen_aborted);
1429 assert_eq!(main_thread_worker_state,
1430 MainThreadWorkerState::Codegenning);
1431 main_thread_worker_state = MainThreadWorkerState::Idle;
1434 Message::CodegenComplete => {
1435 codegen_done = true;
1436 assert!(!codegen_aborted);
1437 assert_eq!(main_thread_worker_state,
1438 MainThreadWorkerState::Codegenning);
1439 main_thread_worker_state = MainThreadWorkerState::Idle;
1442 // If codegen is aborted that means translation was aborted due
1443 // to some normal-ish compiler error. In this situation we want
1444 // to exit as soon as possible, but we want to make sure all
1445 // existing work has finished. Flag codegen as being done, and
1446 // then conditions above will ensure no more work is spawned but
1447 // we'll keep executing this loop until `running` hits 0.
1448 Message::CodegenAborted => {
1449 assert!(!codegen_aborted);
1450 codegen_done = true;
1451 codegen_aborted = true;
1452 assert_eq!(main_thread_worker_state,
1453 MainThreadWorkerState::Codegenning);
1455 Message::Done { result: Ok(compiled_module), worker_id } => {
1456 free_worker(worker_id);
1457 match compiled_module.kind {
1458 ModuleKind::Regular => {
1459 compiled_modules.push(compiled_module);
1461 ModuleKind::Metadata => {
1462 assert!(compiled_metadata_module.is_none());
1463 compiled_metadata_module = Some(compiled_module);
1465 ModuleKind::Allocator => {
1466 assert!(compiled_allocator_module.is_none());
1467 compiled_allocator_module = Some(compiled_module);
1471 Message::NeedsFatLTO { result, worker_id } => {
1472 assert!(!started_lto);
1473 free_worker(worker_id);
1474 needs_fat_lto.push(result);
1476 Message::NeedsThinLTO { name, thin_buffer, worker_id } => {
1477 assert!(!started_lto);
1478 free_worker(worker_id);
1479 needs_thin_lto.push((name, thin_buffer));
1481 Message::AddImportOnlyModule { module_data, work_product } => {
1482 assert!(!started_lto);
1483 assert!(!codegen_done);
1484 assert_eq!(main_thread_worker_state,
1485 MainThreadWorkerState::Codegenning);
1486 lto_import_only_modules.push((module_data, work_product));
1487 main_thread_worker_state = MainThreadWorkerState::Idle;
1489 // If the thread failed that means it panicked, so we abort immediately.
1490 Message::Done { result: Err(()), worker_id: _ } => {
1491 bug!("worker thread panicked");
1493 Message::CodegenItem => {
1494 bug!("the coordinator should not receive codegen requests")
1499 if let Some(llvm_start_time) = llvm_start_time {
1500 let total_llvm_time = Instant::now().duration_since(llvm_start_time);
1501 // This is the top-level timing for all of LLVM, set the time-depth
1504 print_time_passes_entry(cgcx.time_passes,
1509 // Regardless of what order these modules completed in, report them to
1510 // the backend in the same order every time to ensure that we're handing
1511 // out deterministic results.
1512 compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
1514 Ok(CompiledModules {
1515 modules: compiled_modules,
1516 metadata_module: compiled_metadata_module,
1517 allocator_module: compiled_allocator_module,
1521 // A heuristic that determines if we have enough LLVM WorkItems in the
1522 // queue so that the main thread can do LLVM work instead of codegen
1523 fn queue_full_enough(items_in_queue: usize,
1524 workers_running: usize,
1525 max_workers: usize) -> bool {
1527 items_in_queue > 0 &&
1528 items_in_queue >= max_workers.saturating_sub(workers_running / 2)
1531 fn maybe_start_llvm_timer(config: &ModuleConfig,
1532 llvm_start_time: &mut Option<Instant>) {
1533 // We keep track of the -Ztime-passes output manually,
1534 // since the closure-based interface does not fit well here.
1535 if config.time_passes {
1536 if llvm_start_time.is_none() {
1537 *llvm_start_time = Some(Instant::now());
1543 pub const CODEGEN_WORKER_ID: usize = ::std::usize::MAX;
1545 fn spawn_work<B: ExtraBackendMethods>(
1546 cgcx: CodegenContext<B>,
1549 let depth = time_depth();
1551 thread::spawn(move || {
1552 set_time_depth(depth);
1554 // Set up a destructor which will fire off a message that we're done as
1556 struct Bomb<B: ExtraBackendMethods> {
1557 coordinator_send: Sender<Box<dyn Any + Send>>,
1558 result: Option<WorkItemResult<B>>,
1561 impl<B: ExtraBackendMethods> Drop for Bomb<B> {
1562 fn drop(&mut self) {
1563 let worker_id = self.worker_id;
1564 let msg = match self.result.take() {
1565 Some(WorkItemResult::Compiled(m)) => {
1566 Message::Done::<B> { result: Ok(m), worker_id }
1568 Some(WorkItemResult::NeedsFatLTO(m)) => {
1569 Message::NeedsFatLTO::<B> { result: m, worker_id }
1571 Some(WorkItemResult::NeedsThinLTO(name, thin_buffer)) => {
1572 Message::NeedsThinLTO::<B> { name, thin_buffer, worker_id }
1574 None => Message::Done::<B> { result: Err(()), worker_id }
1576 drop(self.coordinator_send.send(Box::new(msg)));
1580 let mut bomb = Bomb::<B> {
1581 coordinator_send: cgcx.coordinator_send.clone(),
1583 worker_id: cgcx.worker,
1586 // Execute the work itself, and if it finishes successfully then flag
1587 // ourselves as a success as well.
1589 // Note that we ignore any `FatalError` coming out of `execute_work_item`,
1590 // as a diagnostic was already sent off to the main thread - just
1591 // surface that there was an error in this worker.
1593 let _prof_timer = cgcx.prof.generic_activity(&work.name());
1594 execute_work_item(&cgcx, work).ok()
1599 pub fn run_assembler<B: ExtraBackendMethods>(
1600 cgcx: &CodegenContext<B>,
1605 let assembler = cgcx.assembler_cmd
1607 .expect("cgcx.assembler_cmd is missing?");
1609 let pname = &assembler.name;
1610 let mut cmd = assembler.cmd.clone();
1611 cmd.arg("-c").arg("-o").arg(object).arg(assembly);
1612 debug!("{:?}", cmd);
1614 match cmd.output() {
1616 if !prog.status.success() {
1617 let mut note = prog.stderr.clone();
1618 note.extend_from_slice(&prog.stdout);
1620 handler.struct_err(&format!("linking with `{}` failed: {}",
1623 .note(&format!("{:?}", &cmd))
1624 .note(str::from_utf8(¬e[..]).unwrap())
1626 handler.abort_if_errors();
1630 handler.err(&format!("could not exec the linker `{}`: {}", pname.display(), e));
1631 handler.abort_if_errors();
1637 enum SharedEmitterMessage {
1638 Diagnostic(Diagnostic),
1639 InlineAsmError(u32, String),
1645 pub struct SharedEmitter {
1646 sender: Sender<SharedEmitterMessage>,
1649 pub struct SharedEmitterMain {
1650 receiver: Receiver<SharedEmitterMessage>,
1653 impl SharedEmitter {
1654 pub fn new() -> (SharedEmitter, SharedEmitterMain) {
1655 let (sender, receiver) = channel();
1657 (SharedEmitter { sender }, SharedEmitterMain { receiver })
1660 pub fn inline_asm_error(&self, cookie: u32, msg: String) {
1661 drop(self.sender.send(SharedEmitterMessage::InlineAsmError(cookie, msg)));
1664 pub fn fatal(&self, msg: &str) {
1665 drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1669 impl Emitter for SharedEmitter {
1670 fn emit_diagnostic(&mut self, db: &rustc_errors::Diagnostic) {
1671 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1673 code: db.code.clone(),
1676 for child in &db.children {
1677 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1678 msg: child.message(),
1683 drop(self.sender.send(SharedEmitterMessage::AbortIfErrors));
1685 fn source_map(&self) -> Option<&Lrc<SourceMapperDyn>> {
1690 impl SharedEmitterMain {
1691 pub fn check(&self, sess: &Session, blocking: bool) {
1693 let message = if blocking {
1694 match self.receiver.recv() {
1695 Ok(message) => Ok(message),
1699 match self.receiver.try_recv() {
1700 Ok(message) => Ok(message),
1706 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
1707 let handler = sess.diagnostic();
1708 let mut d = rustc_errors::Diagnostic::new(diag.lvl, &diag.msg);
1709 if let Some(code) = diag.code {
1712 handler.emit_diagnostic(&d);
1713 handler.abort_if_errors_and_should_abort();
1715 Ok(SharedEmitterMessage::InlineAsmError(cookie, msg)) => {
1716 sess.span_err(ExpnId::from_u32(cookie).expn_data().call_site, &msg)
1718 Ok(SharedEmitterMessage::AbortIfErrors) => {
1719 sess.abort_if_errors();
1721 Ok(SharedEmitterMessage::Fatal(msg)) => {
1733 pub struct OngoingCodegen<B: ExtraBackendMethods> {
1735 pub crate_name: Symbol,
1736 pub crate_hash: Svh,
1737 pub metadata: EncodedMetadata,
1738 pub windows_subsystem: Option<String>,
1739 pub linker_info: LinkerInfo,
1740 pub crate_info: CrateInfo,
1741 pub coordinator_send: Sender<Box<dyn Any + Send>>,
1742 pub codegen_worker_receive: Receiver<Message<B>>,
1743 pub shared_emitter_main: SharedEmitterMain,
1744 pub future: thread::JoinHandle<Result<CompiledModules, ()>>,
1745 pub output_filenames: Arc<OutputFilenames>,
1748 impl<B: ExtraBackendMethods> OngoingCodegen<B> {
1752 ) -> (CodegenResults, FxHashMap<WorkProductId, WorkProduct>) {
1753 self.shared_emitter_main.check(sess, true);
1754 let compiled_modules = match self.future.join() {
1755 Ok(Ok(compiled_modules)) => compiled_modules,
1757 sess.abort_if_errors();
1758 panic!("expected abort due to worker thread errors")
1761 bug!("panic during codegen/LLVM phase");
1765 sess.cgu_reuse_tracker.check_expected_reuse(sess);
1767 sess.abort_if_errors();
1770 copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess,
1772 produce_final_output_artifacts(sess,
1774 &self.output_filenames);
1776 // FIXME: time_llvm_passes support - does this use a global context or
1778 if sess.codegen_units() == 1 && sess.time_llvm_passes() {
1779 self.backend.print_pass_timings()
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()