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_data_structures::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};
27 use syntax_pos::source_map::SourceMap;
28 use rustc_errors::emitter::{Emitter};
29 use rustc_target::spec::MergeFunctions;
31 use syntax_pos::hygiene::ExpnId;
32 use syntax_pos::symbol::{Symbol, sym};
33 use jobserver::{Client, Acquired};
39 use std::path::{Path, PathBuf};
42 use std::sync::mpsc::{channel, Sender, Receiver};
43 use std::time::Instant;
46 const PRE_LTO_BC_EXT: &str = "pre-lto.bc";
48 /// Module-specific configuration for `optimize_and_codegen`.
49 pub struct ModuleConfig {
50 /// Names of additional optimization passes to run.
51 pub passes: Vec<String>,
52 /// Some(level) to optimize at a certain level, or None to run
53 /// absolutely no optimizations (used for the metadata module).
54 pub opt_level: Option<config::OptLevel>,
56 /// Some(level) to optimize binary size, or None to not affect program size.
57 pub opt_size: Option<config::OptLevel>,
59 pub pgo_gen: SwitchWithOptPath,
60 pub pgo_use: Option<PathBuf>,
62 pub sanitizer: Option<Sanitizer>,
63 pub sanitizer_recover: Vec<Sanitizer>,
64 pub sanitizer_memory_track_origins: usize,
66 // Flags indicating which outputs to produce.
67 pub emit_pre_lto_bc: bool,
68 pub emit_no_opt_bc: bool,
70 pub emit_bc_compressed: bool,
71 pub emit_lto_bc: bool,
75 // Miscellaneous flags. These are mostly copied from command-line
77 pub verify_llvm_ir: bool,
78 pub no_prepopulate_passes: bool,
79 pub no_builtins: bool,
80 pub time_passes: bool,
81 pub vectorize_loop: bool,
82 pub vectorize_slp: bool,
83 pub merge_functions: bool,
84 pub inline_threshold: Option<usize>,
85 // Instead of creating an object file by doing LLVM codegen, just
86 // make the object file bitcode. Provides easy compatibility with
87 // emscripten's ecc compiler, when used as the linker.
88 pub obj_is_bitcode: bool,
89 pub no_integrated_as: bool,
90 pub embed_bitcode: bool,
91 pub embed_bitcode_marker: bool,
95 fn new(passes: Vec<String>) -> ModuleConfig {
101 pgo_gen: SwitchWithOptPath::Disabled,
105 sanitizer_recover: Default::default(),
106 sanitizer_memory_track_origins: 0,
108 emit_no_opt_bc: false,
109 emit_pre_lto_bc: false,
111 emit_bc_compressed: false,
116 obj_is_bitcode: false,
117 embed_bitcode: false,
118 embed_bitcode_marker: false,
119 no_integrated_as: false,
121 verify_llvm_ir: false,
122 no_prepopulate_passes: false,
125 vectorize_loop: false,
126 vectorize_slp: false,
127 merge_functions: false,
128 inline_threshold: None
132 fn set_flags(&mut self, sess: &Session, no_builtins: bool) {
133 self.verify_llvm_ir = sess.verify_llvm_ir();
134 self.no_prepopulate_passes = sess.opts.cg.no_prepopulate_passes;
135 self.no_builtins = no_builtins || sess.target.target.options.no_builtins;
136 self.time_passes = sess.time_extended();
137 self.inline_threshold = sess.opts.cg.inline_threshold;
138 self.obj_is_bitcode = sess.target.target.options.obj_is_bitcode ||
139 sess.opts.cg.linker_plugin_lto.enabled();
140 let embed_bitcode = sess.target.target.options.embed_bitcode ||
141 sess.opts.debugging_opts.embed_bitcode;
143 match sess.opts.optimize {
144 config::OptLevel::No |
145 config::OptLevel::Less => {
146 self.embed_bitcode_marker = embed_bitcode;
148 _ => self.embed_bitcode = embed_bitcode,
152 // Copy what clang does by turning on loop vectorization at O2 and
153 // slp vectorization at O3. Otherwise configure other optimization aspects
154 // of this pass manager builder.
155 self.vectorize_loop = !sess.opts.cg.no_vectorize_loops &&
156 (sess.opts.optimize == config::OptLevel::Default ||
157 sess.opts.optimize == config::OptLevel::Aggressive);
159 self.vectorize_slp = !sess.opts.cg.no_vectorize_slp &&
160 sess.opts.optimize == config::OptLevel::Aggressive;
162 // Some targets (namely, NVPTX) interact badly with the MergeFunctions
163 // pass. This is because MergeFunctions can generate new function calls
164 // which may interfere with the target calling convention; e.g. for the
165 // NVPTX target, PTX kernels should not call other PTX kernels.
166 // MergeFunctions can also be configured to generate aliases instead,
167 // but aliases are not supported by some backends (again, NVPTX).
168 // Therefore, allow targets to opt out of the MergeFunctions pass,
169 // but otherwise keep the pass enabled (at O2 and O3) since it can be
170 // useful for reducing code size.
171 self.merge_functions = match sess.opts.debugging_opts.merge_functions
172 .unwrap_or(sess.target.target.options.merge_functions) {
173 MergeFunctions::Disabled => false,
174 MergeFunctions::Trampolines |
175 MergeFunctions::Aliases => {
176 sess.opts.optimize == config::OptLevel::Default ||
177 sess.opts.optimize == config::OptLevel::Aggressive
182 pub fn bitcode_needed(&self) -> bool {
183 self.emit_bc || self.obj_is_bitcode
184 || self.emit_bc_compressed || self.embed_bitcode
188 /// Assembler name and command used by codegen when no_integrated_as is enabled
189 pub struct AssemblerCommand {
194 // HACK(eddyb) work around `#[derive]` producing wrong bounds for `Clone`.
195 pub struct TargetMachineFactory<B: WriteBackendMethods>(
196 pub Arc<dyn Fn() -> Result<B::TargetMachine, String> + Send + Sync>,
199 impl<B: WriteBackendMethods> Clone for TargetMachineFactory<B> {
200 fn clone(&self) -> Self {
201 TargetMachineFactory(self.0.clone())
205 /// Additional resources used by optimize_and_codegen (not module specific)
207 pub struct CodegenContext<B: WriteBackendMethods> {
208 // Resources needed when running LTO
210 pub time_passes: bool,
211 pub prof: SelfProfilerRef,
213 pub no_landing_pads: bool,
214 pub save_temps: bool,
215 pub fewer_names: bool,
216 pub exported_symbols: Option<Arc<ExportedSymbols>>,
217 pub opts: Arc<config::Options>,
218 pub crate_types: Vec<config::CrateType>,
219 pub each_linked_rlib_for_lto: Vec<(CrateNum, PathBuf)>,
220 pub output_filenames: Arc<OutputFilenames>,
221 pub regular_module_config: Arc<ModuleConfig>,
222 pub metadata_module_config: Arc<ModuleConfig>,
223 pub allocator_module_config: Arc<ModuleConfig>,
224 pub tm_factory: TargetMachineFactory<B>,
225 pub msvc_imps_needed: bool,
226 pub target_pointer_width: String,
227 pub target_arch: String,
228 pub debuginfo: config::DebugInfo,
230 // Number of cgus excluding the allocator/metadata modules
231 pub total_cgus: usize,
232 // Handler to use for diagnostics produced during codegen.
233 pub diag_emitter: SharedEmitter,
234 // LLVM passes added by plugins.
235 pub plugin_passes: Vec<String>,
236 // LLVM optimizations for which we want to print remarks.
238 // Worker thread number
240 // The incremental compilation session directory, or None if we are not
241 // compiling incrementally
242 pub incr_comp_session_dir: Option<PathBuf>,
243 // Used to update CGU re-use information during the thinlto phase.
244 pub cgu_reuse_tracker: CguReuseTracker,
245 // Channel back to the main control thread to send messages to
246 pub coordinator_send: Sender<Box<dyn Any + Send>>,
247 // The assembler command if no_integrated_as option is enabled, None otherwise
248 pub assembler_cmd: Option<Arc<AssemblerCommand>>
251 impl<B: WriteBackendMethods> CodegenContext<B> {
252 pub fn create_diag_handler(&self) -> Handler {
253 Handler::with_emitter(true, None, Box::new(self.diag_emitter.clone()))
256 pub fn config(&self, kind: ModuleKind) -> &ModuleConfig {
258 ModuleKind::Regular => &self.regular_module_config,
259 ModuleKind::Metadata => &self.metadata_module_config,
260 ModuleKind::Allocator => &self.allocator_module_config,
265 fn generate_lto_work<B: ExtraBackendMethods>(
266 cgcx: &CodegenContext<B>,
267 needs_fat_lto: Vec<FatLTOInput<B>>,
268 needs_thin_lto: Vec<(String, B::ThinBuffer)>,
269 import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>
270 ) -> Vec<(WorkItem<B>, u64)> {
271 let _prof_timer = cgcx.prof.generic_activity("codegen_generate_lto_work");
273 let (lto_modules, copy_jobs) = if !needs_fat_lto.is_empty() {
274 assert!(needs_thin_lto.is_empty());
275 let lto_module = B::run_fat_lto(
280 .unwrap_or_else(|e| e.raise());
281 (vec![lto_module], vec![])
283 assert!(needs_fat_lto.is_empty());
284 B::run_thin_lto(cgcx, needs_thin_lto, import_only_modules)
285 .unwrap_or_else(|e| e.raise())
288 let result = lto_modules.into_iter().map(|module| {
289 let cost = module.cost();
290 (WorkItem::LTO(module), cost)
291 }).chain(copy_jobs.into_iter().map(|wp| {
292 (WorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
293 name: wp.cgu_name.clone(),
301 pub struct CompiledModules {
302 pub modules: Vec<CompiledModule>,
303 pub metadata_module: Option<CompiledModule>,
304 pub allocator_module: Option<CompiledModule>,
307 fn need_crate_bitcode_for_rlib(sess: &Session) -> bool {
308 sess.crate_types.borrow().contains(&config::CrateType::Rlib) &&
309 sess.opts.output_types.contains_key(&OutputType::Exe)
312 fn need_pre_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
313 if sess.opts.incremental.is_none() {
321 Lto::ThinLocal => true,
325 pub fn start_async_codegen<B: ExtraBackendMethods>(
328 metadata: EncodedMetadata,
330 ) -> OngoingCodegen<B> {
331 let (coordinator_send, coordinator_receive) = channel();
334 let crate_name = tcx.crate_name(LOCAL_CRATE);
335 let crate_hash = tcx.crate_hash(LOCAL_CRATE);
336 let no_builtins = attr::contains_name(&tcx.hir().krate().attrs, sym::no_builtins);
337 let subsystem = attr::first_attr_value_str_by_name(&tcx.hir().krate().attrs,
338 sym::windows_subsystem);
339 let windows_subsystem = subsystem.map(|subsystem| {
340 if subsystem != sym::windows && subsystem != sym::console {
341 tcx.sess.fatal(&format!("invalid windows subsystem `{}`, only \
342 `windows` and `console` are allowed",
345 subsystem.to_string()
348 let linker_info = LinkerInfo::new(tcx);
349 let crate_info = CrateInfo::new(tcx);
351 // Figure out what we actually need to build.
352 let mut modules_config = ModuleConfig::new(sess.opts.cg.passes.clone());
353 let mut metadata_config = ModuleConfig::new(vec![]);
354 let mut allocator_config = ModuleConfig::new(vec![]);
356 if sess.opts.debugging_opts.profile {
357 modules_config.passes.push("insert-gcov-profiling".to_owned())
360 modules_config.pgo_gen = sess.opts.cg.profile_generate.clone();
361 modules_config.pgo_use = sess.opts.cg.profile_use.clone();
362 modules_config.sanitizer = sess.opts.debugging_opts.sanitizer.clone();
363 modules_config.sanitizer_recover = sess.opts.debugging_opts.sanitizer_recover.clone();
364 modules_config.sanitizer_memory_track_origins =
365 sess.opts.debugging_opts.sanitizer_memory_track_origins;
366 modules_config.opt_level = Some(sess.opts.optimize);
367 modules_config.opt_size = Some(sess.opts.optimize);
369 // Save all versions of the bytecode if we're saving our temporaries.
370 if sess.opts.cg.save_temps {
371 modules_config.emit_no_opt_bc = true;
372 modules_config.emit_pre_lto_bc = true;
373 modules_config.emit_bc = true;
374 modules_config.emit_lto_bc = true;
375 metadata_config.emit_bc = true;
376 allocator_config.emit_bc = true;
379 // Emit compressed bitcode files for the crate if we're emitting an rlib.
380 // Whenever an rlib is created, the bitcode is inserted into the archive in
381 // order to allow LTO against it.
382 if need_crate_bitcode_for_rlib(sess) {
383 modules_config.emit_bc_compressed = true;
384 allocator_config.emit_bc_compressed = true;
387 modules_config.emit_pre_lto_bc =
388 need_pre_lto_bitcode_for_incr_comp(sess);
390 modules_config.no_integrated_as = tcx.sess.opts.cg.no_integrated_as ||
391 tcx.sess.target.target.options.no_integrated_as;
393 for output_type in sess.opts.output_types.keys() {
395 OutputType::Bitcode => { modules_config.emit_bc = true; }
396 OutputType::LlvmAssembly => { modules_config.emit_ir = true; }
397 OutputType::Assembly => {
398 modules_config.emit_asm = true;
399 // If we're not using the LLVM assembler, this function
400 // could be invoked specially with output_type_assembly, so
401 // in this case we still want the metadata object file.
402 if !sess.opts.output_types.contains_key(&OutputType::Assembly) {
403 metadata_config.emit_obj = true;
404 allocator_config.emit_obj = true;
407 OutputType::Object => { modules_config.emit_obj = true; }
408 OutputType::Metadata => { metadata_config.emit_obj = true; }
410 modules_config.emit_obj = true;
411 metadata_config.emit_obj = true;
412 allocator_config.emit_obj = true;
414 OutputType::Mir => {}
415 OutputType::DepInfo => {}
419 modules_config.set_flags(sess, no_builtins);
420 metadata_config.set_flags(sess, no_builtins);
421 allocator_config.set_flags(sess, no_builtins);
423 // Exclude metadata and allocator modules from time_passes output, since
424 // they throw off the "LLVM passes" measurement.
425 metadata_config.time_passes = false;
426 allocator_config.time_passes = false;
428 let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
429 let (codegen_worker_send, codegen_worker_receive) = channel();
431 let coordinator_thread = start_executing_work(backend.clone(),
438 sess.jobserver.clone(),
439 Arc::new(modules_config),
440 Arc::new(metadata_config),
441 Arc::new(allocator_config),
442 coordinator_send.clone());
454 codegen_worker_receive,
456 future: coordinator_thread,
457 output_filenames: tcx.output_filenames(LOCAL_CRATE),
461 fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
463 compiled_modules: &CompiledModules,
464 ) -> FxHashMap<WorkProductId, WorkProduct> {
465 let mut work_products = FxHashMap::default();
467 if sess.opts.incremental.is_none() {
468 return work_products;
471 for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
472 let mut files = vec![];
474 if let Some(ref path) = module.object {
475 files.push((WorkProductFileKind::Object, path.clone()));
477 if let Some(ref path) = module.bytecode {
478 files.push((WorkProductFileKind::Bytecode, path.clone()));
480 if let Some(ref path) = module.bytecode_compressed {
481 files.push((WorkProductFileKind::BytecodeCompressed, path.clone()));
484 if let Some((id, product)) =
485 copy_cgu_workproducts_to_incr_comp_cache_dir(sess, &module.name, &files) {
486 work_products.insert(id, product);
493 fn produce_final_output_artifacts(sess: &Session,
494 compiled_modules: &CompiledModules,
495 crate_output: &OutputFilenames) {
496 let mut user_wants_bitcode = false;
497 let mut user_wants_objects = false;
499 // Produce final compile outputs.
500 let copy_gracefully = |from: &Path, to: &Path| {
501 if let Err(e) = fs::copy(from, to) {
502 sess.err(&format!("could not copy {:?} to {:?}: {}", from, to, e));
506 let copy_if_one_unit = |output_type: OutputType,
507 keep_numbered: bool| {
508 if compiled_modules.modules.len() == 1 {
509 // 1) Only one codegen unit. In this case it's no difficulty
510 // to copy `foo.0.x` to `foo.x`.
511 let module_name = Some(&compiled_modules.modules[0].name[..]);
512 let path = crate_output.temp_path(output_type, module_name);
513 copy_gracefully(&path,
514 &crate_output.path(output_type));
515 if !sess.opts.cg.save_temps && !keep_numbered {
516 // The user just wants `foo.x`, not `foo.#module-name#.x`.
520 let ext = crate_output.temp_path(output_type, None)
527 if crate_output.outputs.contains_key(&output_type) {
528 // 2) Multiple codegen units, with `--emit foo=some_name`. We have
529 // no good solution for this case, so warn the user.
530 sess.warn(&format!("ignoring emit path because multiple .{} files \
531 were produced", ext));
532 } else if crate_output.single_output_file.is_some() {
533 // 3) Multiple codegen units, with `-o some_name`. We have
534 // no good solution for this case, so warn the user.
535 sess.warn(&format!("ignoring -o because multiple .{} files \
536 were produced", ext));
538 // 4) Multiple codegen units, but no explicit name. We
539 // just leave the `foo.0.x` files in place.
540 // (We don't have to do any work in this case.)
545 // Flag to indicate whether the user explicitly requested bitcode.
546 // Otherwise, we produced it only as a temporary output, and will need
548 for output_type in crate_output.outputs.keys() {
550 OutputType::Bitcode => {
551 user_wants_bitcode = true;
552 // Copy to .bc, but always keep the .0.bc. There is a later
553 // check to figure out if we should delete .0.bc files, or keep
554 // them for making an rlib.
555 copy_if_one_unit(OutputType::Bitcode, true);
557 OutputType::LlvmAssembly => {
558 copy_if_one_unit(OutputType::LlvmAssembly, false);
560 OutputType::Assembly => {
561 copy_if_one_unit(OutputType::Assembly, false);
563 OutputType::Object => {
564 user_wants_objects = true;
565 copy_if_one_unit(OutputType::Object, true);
568 OutputType::Metadata |
570 OutputType::DepInfo => {}
574 // Clean up unwanted temporary files.
576 // We create the following files by default:
577 // - #crate#.#module-name#.bc
578 // - #crate#.#module-name#.o
579 // - #crate#.crate.metadata.bc
580 // - #crate#.crate.metadata.o
581 // - #crate#.o (linked from crate.##.o)
582 // - #crate#.bc (copied from crate.##.bc)
583 // We may create additional files if requested by the user (through
584 // `-C save-temps` or `--emit=` flags).
586 if !sess.opts.cg.save_temps {
587 // Remove the temporary .#module-name#.o objects. If the user didn't
588 // explicitly request bitcode (with --emit=bc), and the bitcode is not
589 // needed for building an rlib, then we must remove .#module-name#.bc as
592 // Specific rules for keeping .#module-name#.bc:
593 // - If the user requested bitcode (`user_wants_bitcode`), and
594 // codegen_units > 1, then keep it.
595 // - If the user requested bitcode but codegen_units == 1, then we
596 // can toss .#module-name#.bc because we copied it to .bc earlier.
597 // - If we're not building an rlib and the user didn't request
598 // bitcode, then delete .#module-name#.bc.
599 // If you change how this works, also update back::link::link_rlib,
600 // where .#module-name#.bc files are (maybe) deleted after making an
602 let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
604 let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units() > 1;
606 let keep_numbered_objects = needs_crate_object ||
607 (user_wants_objects && sess.codegen_units() > 1);
609 for module in compiled_modules.modules.iter() {
610 if let Some(ref path) = module.object {
611 if !keep_numbered_objects {
616 if let Some(ref path) = module.bytecode {
617 if !keep_numbered_bitcode {
623 if !user_wants_bitcode {
624 if let Some(ref metadata_module) = compiled_modules.metadata_module {
625 if let Some(ref path) = metadata_module.bytecode {
630 if let Some(ref allocator_module) = compiled_modules.allocator_module {
631 if let Some(ref path) = allocator_module.bytecode {
638 // We leave the following files around by default:
640 // - #crate#.crate.metadata.o
642 // These are used in linking steps and will be cleaned up afterward.
645 pub fn dump_incremental_data(_codegen_results: &CodegenResults) {
646 // FIXME(mw): This does not work at the moment because the situation has
647 // become more complicated due to incremental LTO. Now a CGU
648 // can have more than two caching states.
649 // println!("[incremental] Re-using {} out of {} modules",
650 // codegen_results.modules.iter().filter(|m| m.pre_existing).count(),
651 // codegen_results.modules.len());
654 pub enum WorkItem<B: WriteBackendMethods> {
655 /// Optimize a newly codegened, totally unoptimized module.
656 Optimize(ModuleCodegen<B::Module>),
657 /// Copy the post-LTO artifacts from the incremental cache to the output
659 CopyPostLtoArtifacts(CachedModuleCodegen),
660 /// Performs (Thin)LTO on the given module.
661 LTO(lto::LtoModuleCodegen<B>),
664 impl<B: WriteBackendMethods> WorkItem<B> {
665 pub fn module_kind(&self) -> ModuleKind {
667 WorkItem::Optimize(ref m) => m.kind,
668 WorkItem::CopyPostLtoArtifacts(_) |
669 WorkItem::LTO(_) => ModuleKind::Regular,
673 fn profiling_event_id(&self) -> &'static str {
675 WorkItem::Optimize(_) => "codegen_module_optimize",
676 WorkItem::CopyPostLtoArtifacts(_) => "codegen_copy_artifacts_from_incr_cache",
677 WorkItem::LTO(_) => "codegen_module_perform_lto",
682 enum WorkItemResult<B: WriteBackendMethods> {
683 Compiled(CompiledModule),
684 NeedsFatLTO(FatLTOInput<B>),
685 NeedsThinLTO(String, B::ThinBuffer),
688 pub enum FatLTOInput<B: WriteBackendMethods> {
691 buffer: B::ModuleBuffer,
693 InMemory(ModuleCodegen<B::Module>),
696 fn execute_work_item<B: ExtraBackendMethods>(
697 cgcx: &CodegenContext<B>,
698 work_item: WorkItem<B>,
699 ) -> Result<WorkItemResult<B>, FatalError> {
700 let module_config = cgcx.config(work_item.module_kind());
703 WorkItem::Optimize(module) => {
704 execute_optimize_work_item(cgcx, module, module_config)
706 WorkItem::CopyPostLtoArtifacts(module) => {
707 execute_copy_from_cache_work_item(cgcx, module, module_config)
709 WorkItem::LTO(module) => {
710 execute_lto_work_item(cgcx, module, module_config)
715 // Actual LTO type we end up chosing based on multiple factors.
716 enum ComputedLtoType {
722 fn execute_optimize_work_item<B: ExtraBackendMethods>(
723 cgcx: &CodegenContext<B>,
724 module: ModuleCodegen<B::Module>,
725 module_config: &ModuleConfig,
726 ) -> Result<WorkItemResult<B>, FatalError> {
727 let diag_handler = cgcx.create_diag_handler();
730 B::optimize(cgcx, &diag_handler, &module, module_config)?;
733 // After we've done the initial round of optimizations we need to
734 // decide whether to synchronously codegen this module or ship it
735 // back to the coordinator thread for further LTO processing (which
736 // has to wait for all the initial modules to be optimized).
738 // If the linker does LTO, we don't have to do it. Note that we
739 // keep doing full LTO, if it is requested, as not to break the
740 // assumption that the output will be a single module.
741 let linker_does_lto = cgcx.opts.cg.linker_plugin_lto.enabled();
743 // When we're automatically doing ThinLTO for multi-codegen-unit
744 // builds we don't actually want to LTO the allocator modules if
745 // it shows up. This is due to various linker shenanigans that
746 // we'll encounter later.
747 let is_allocator = module.kind == ModuleKind::Allocator;
749 // We ignore a request for full crate grath LTO if the cate type
750 // is only an rlib, as there is no full crate graph to process,
751 // that'll happen later.
753 // This use case currently comes up primarily for targets that
754 // require LTO so the request for LTO is always unconditionally
755 // passed down to the backend, but we don't actually want to do
756 // anything about it yet until we've got a final product.
757 let is_rlib = cgcx.crate_types.len() == 1
758 && cgcx.crate_types[0] == config::CrateType::Rlib;
760 // Metadata modules never participate in LTO regardless of the lto
762 let lto_type = if module.kind == ModuleKind::Metadata {
766 Lto::ThinLocal if !linker_does_lto && !is_allocator
767 => ComputedLtoType::Thin,
768 Lto::Thin if !linker_does_lto && !is_rlib
769 => ComputedLtoType::Thin,
770 Lto::Fat if !is_rlib => ComputedLtoType::Fat,
771 _ => ComputedLtoType::No,
775 // If we're doing some form of incremental LTO then we need to be sure to
776 // save our module to disk first.
777 let bitcode = if cgcx.config(module.kind).emit_pre_lto_bc {
778 let filename = pre_lto_bitcode_filename(&module.name);
779 cgcx.incr_comp_session_dir.as_ref().map(|path| path.join(&filename))
785 ComputedLtoType::No => {
786 let module = unsafe {
787 B::codegen(cgcx, &diag_handler, module, module_config)?
789 WorkItemResult::Compiled(module)
791 ComputedLtoType::Thin => {
792 let (name, thin_buffer) = B::prepare_thin(module);
793 if let Some(path) = bitcode {
794 fs::write(&path, thin_buffer.data()).unwrap_or_else(|e| {
795 panic!("Error writing pre-lto-bitcode file `{}`: {}",
800 WorkItemResult::NeedsThinLTO(name, thin_buffer)
802 ComputedLtoType::Fat => {
805 let (name, buffer) = B::serialize_module(module);
806 fs::write(&path, buffer.data()).unwrap_or_else(|e| {
807 panic!("Error writing pre-lto-bitcode file `{}`: {}",
811 WorkItemResult::NeedsFatLTO(FatLTOInput::Serialized { name, buffer })
813 None => WorkItemResult::NeedsFatLTO(FatLTOInput::InMemory(module)),
819 fn execute_copy_from_cache_work_item<B: ExtraBackendMethods>(
820 cgcx: &CodegenContext<B>,
821 module: CachedModuleCodegen,
822 module_config: &ModuleConfig,
823 ) -> Result<WorkItemResult<B>, FatalError> {
824 let incr_comp_session_dir = cgcx.incr_comp_session_dir
827 let mut object = None;
828 let mut bytecode = None;
829 let mut bytecode_compressed = None;
830 for (kind, saved_file) in &module.source.saved_files {
831 let obj_out = match kind {
832 WorkProductFileKind::Object => {
833 let path = cgcx.output_filenames.temp_path(OutputType::Object,
835 object = Some(path.clone());
838 WorkProductFileKind::Bytecode => {
839 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode,
841 bytecode = Some(path.clone());
844 WorkProductFileKind::BytecodeCompressed => {
845 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode,
847 .with_extension(RLIB_BYTECODE_EXTENSION);
848 bytecode_compressed = Some(path.clone());
852 let source_file = in_incr_comp_dir(&incr_comp_session_dir,
854 debug!("copying pre-existing module `{}` from {:?} to {}",
858 if let Err(err) = link_or_copy(&source_file, &obj_out) {
859 let diag_handler = cgcx.create_diag_handler();
860 diag_handler.err(&format!("unable to copy {} to {}: {}",
861 source_file.display(),
867 assert_eq!(object.is_some(), module_config.emit_obj);
868 assert_eq!(bytecode.is_some(), module_config.emit_bc);
869 assert_eq!(bytecode_compressed.is_some(), module_config.emit_bc_compressed);
871 Ok(WorkItemResult::Compiled(CompiledModule {
873 kind: ModuleKind::Regular,
880 fn execute_lto_work_item<B: ExtraBackendMethods>(
881 cgcx: &CodegenContext<B>,
882 mut module: lto::LtoModuleCodegen<B>,
883 module_config: &ModuleConfig,
884 ) -> Result<WorkItemResult<B>, FatalError> {
885 let diag_handler = cgcx.create_diag_handler();
888 let module = module.optimize(cgcx)?;
889 let module = B::codegen(cgcx, &diag_handler, module, module_config)?;
890 Ok(WorkItemResult::Compiled(module))
894 pub enum Message<B: WriteBackendMethods> {
895 Token(io::Result<Acquired>),
897 result: FatLTOInput<B>,
902 thin_buffer: B::ThinBuffer,
906 result: Result<CompiledModule, ()>,
910 llvm_work_item: WorkItem<B>,
913 AddImportOnlyModule {
914 module_data: SerializedModule<B::ModuleBuffer>,
915 work_product: WorkProduct,
924 code: Option<DiagnosticId>,
928 #[derive(PartialEq, Clone, Copy, Debug)]
929 enum MainThreadWorkerState {
935 fn start_executing_work<B: ExtraBackendMethods>(
938 crate_info: &CrateInfo,
939 shared_emitter: SharedEmitter,
940 codegen_worker_send: Sender<Message<B>>,
941 coordinator_receive: Receiver<Box<dyn Any + Send>>,
944 modules_config: Arc<ModuleConfig>,
945 metadata_config: Arc<ModuleConfig>,
946 allocator_config: Arc<ModuleConfig>,
947 tx_to_llvm_workers: Sender<Box<dyn Any + Send>>,
948 ) -> thread::JoinHandle<Result<CompiledModules, ()>> {
949 let coordinator_send = tx_to_llvm_workers;
952 // Compute the set of symbols we need to retain when doing LTO (if we need to)
953 let exported_symbols = {
954 let mut exported_symbols = FxHashMap::default();
956 let copy_symbols = |cnum| {
957 let symbols = tcx.exported_symbols(cnum)
959 .map(|&(s, lvl)| (s.symbol_name(tcx).to_string(), lvl))
967 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
968 Some(Arc::new(exported_symbols))
970 Lto::Fat | Lto::Thin => {
971 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
972 for &cnum in tcx.crates().iter() {
973 exported_symbols.insert(cnum, copy_symbols(cnum));
975 Some(Arc::new(exported_symbols))
980 // First up, convert our jobserver into a helper thread so we can use normal
981 // mpsc channels to manage our messages and such.
982 // After we've requested tokens then we'll, when we can,
983 // get tokens on `coordinator_receive` which will
984 // get managed in the main loop below.
985 let coordinator_send2 = coordinator_send.clone();
986 let helper = jobserver.into_helper_thread(move |token| {
987 drop(coordinator_send2.send(Box::new(Message::Token::<B>(token))));
988 }).expect("failed to spawn helper thread");
990 let mut each_linked_rlib_for_lto = Vec::new();
991 drop(link::each_linked_rlib(crate_info, &mut |cnum, path| {
992 if link::ignored_for_lto(sess, crate_info, cnum) {
995 each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
998 let assembler_cmd = if modules_config.no_integrated_as {
999 // HACK: currently we use linker (gcc) as our assembler
1000 let (linker, flavor) = link::linker_and_flavor(sess);
1002 let (name, mut cmd) = get_linker(sess, &linker, flavor);
1003 cmd.args(&sess.target.target.options.asm_args);
1004 Some(Arc::new(AssemblerCommand {
1012 let ol = if tcx.sess.opts.debugging_opts.no_codegen
1013 || !tcx.sess.opts.output_types.should_codegen() {
1014 // If we know that we won’t be doing codegen, create target machines without optimisation.
1015 config::OptLevel::No
1017 tcx.backend_optimization_level(LOCAL_CRATE)
1019 let cgcx = CodegenContext::<B> {
1020 backend: backend.clone(),
1021 crate_types: sess.crate_types.borrow().clone(),
1022 each_linked_rlib_for_lto,
1024 no_landing_pads: sess.no_landing_pads(),
1025 fewer_names: sess.fewer_names(),
1026 save_temps: sess.opts.cg.save_temps,
1027 opts: Arc::new(sess.opts.clone()),
1028 time_passes: sess.time_extended(),
1029 prof: sess.prof.clone(),
1031 plugin_passes: sess.plugin_llvm_passes.borrow().clone(),
1032 remark: sess.opts.cg.remark.clone(),
1034 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1035 cgu_reuse_tracker: sess.cgu_reuse_tracker.clone(),
1037 diag_emitter: shared_emitter.clone(),
1038 output_filenames: tcx.output_filenames(LOCAL_CRATE),
1039 regular_module_config: modules_config,
1040 metadata_module_config: metadata_config,
1041 allocator_module_config: allocator_config,
1042 tm_factory: TargetMachineFactory(backend.target_machine_factory(tcx.sess, ol, false)),
1044 msvc_imps_needed: msvc_imps_needed(tcx),
1045 target_pointer_width: tcx.sess.target.target.target_pointer_width.clone(),
1046 target_arch: tcx.sess.target.target.arch.clone(),
1047 debuginfo: tcx.sess.opts.debuginfo,
1051 // This is the "main loop" of parallel work happening for parallel codegen.
1052 // It's here that we manage parallelism, schedule work, and work with
1053 // messages coming from clients.
1055 // There are a few environmental pre-conditions that shape how the system
1058 // - Error reporting only can happen on the main thread because that's the
1059 // only place where we have access to the compiler `Session`.
1060 // - LLVM work can be done on any thread.
1061 // - Codegen can only happen on the main thread.
1062 // - Each thread doing substantial work most be in possession of a `Token`
1063 // from the `Jobserver`.
1064 // - The compiler process always holds one `Token`. Any additional `Tokens`
1065 // have to be requested from the `Jobserver`.
1069 // The error reporting restriction is handled separately from the rest: We
1070 // set up a `SharedEmitter` the holds an open channel to the main thread.
1071 // When an error occurs on any thread, the shared emitter will send the
1072 // error message to the receiver main thread (`SharedEmitterMain`). The
1073 // main thread will periodically query this error message queue and emit
1074 // any error messages it has received. It might even abort compilation if
1075 // has received a fatal error. In this case we rely on all other threads
1076 // being torn down automatically with the main thread.
1077 // Since the main thread will often be busy doing codegen work, error
1078 // reporting will be somewhat delayed, since the message queue can only be
1079 // checked in between to work packages.
1081 // Work Processing Infrastructure
1082 // ==============================
1083 // The work processing infrastructure knows three major actors:
1085 // - the coordinator thread,
1086 // - the main thread, and
1087 // - LLVM worker threads
1089 // The coordinator thread is running a message loop. It instructs the main
1090 // thread about what work to do when, and it will spawn off LLVM worker
1091 // threads as open LLVM WorkItems become available.
1093 // The job of the main thread is to codegen CGUs into LLVM work package
1094 // (since the main thread is the only thread that can do this). The main
1095 // thread will block until it receives a message from the coordinator, upon
1096 // which it will codegen one CGU, send it to the coordinator and block
1097 // again. This way the coordinator can control what the main thread is
1100 // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1101 // available, it will spawn off a new LLVM worker thread and let it process
1102 // that a WorkItem. When a LLVM worker thread is done with its WorkItem,
1103 // it will just shut down, which also frees all resources associated with
1104 // the given LLVM module, and sends a message to the coordinator that the
1105 // has been completed.
1109 // The scheduler's goal is to minimize the time it takes to complete all
1110 // work there is, however, we also want to keep memory consumption low
1111 // if possible. These two goals are at odds with each other: If memory
1112 // consumption were not an issue, we could just let the main thread produce
1113 // LLVM WorkItems at full speed, assuring maximal utilization of
1114 // Tokens/LLVM worker threads. However, since codegen usual is faster
1115 // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1116 // WorkItem potentially holds on to a substantial amount of memory.
1118 // So the actual goal is to always produce just enough LLVM WorkItems as
1119 // not to starve our LLVM worker threads. That means, once we have enough
1120 // WorkItems in our queue, we can block the main thread, so it does not
1121 // produce more until we need them.
1123 // Doing LLVM Work on the Main Thread
1124 // ----------------------------------
1125 // Since the main thread owns the compiler processes implicit `Token`, it is
1126 // wasteful to keep it blocked without doing any work. Therefore, what we do
1127 // in this case is: We spawn off an additional LLVM worker thread that helps
1128 // reduce the queue. The work it is doing corresponds to the implicit
1129 // `Token`. The coordinator will mark the main thread as being busy with
1130 // LLVM work. (The actual work happens on another OS thread but we just care
1131 // about `Tokens`, not actual threads).
1133 // When any LLVM worker thread finishes while the main thread is marked as
1134 // "busy with LLVM work", we can do a little switcheroo: We give the Token
1135 // of the just finished thread to the LLVM worker thread that is working on
1136 // behalf of the main thread's implicit Token, thus freeing up the main
1137 // thread again. The coordinator can then again decide what the main thread
1138 // should do. This allows the coordinator to make decisions at more points
1141 // Striking a Balance between Throughput and Memory Consumption
1142 // ------------------------------------------------------------
1143 // Since our two goals, (1) use as many Tokens as possible and (2) keep
1144 // memory consumption as low as possible, are in conflict with each other,
1145 // we have to find a trade off between them. Right now, the goal is to keep
1146 // all workers busy, which means that no worker should find the queue empty
1147 // when it is ready to start.
1148 // How do we do achieve this? Good question :) We actually never know how
1149 // many `Tokens` are potentially available so it's hard to say how much to
1150 // fill up the queue before switching the main thread to LLVM work. Also we
1151 // currently don't have a means to estimate how long a running LLVM worker
1152 // will still be busy with it's current WorkItem. However, we know the
1153 // maximal count of available Tokens that makes sense (=the number of CPU
1154 // cores), so we can take a conservative guess. The heuristic we use here
1155 // is implemented in the `queue_full_enough()` function.
1157 // Some Background on Jobservers
1158 // -----------------------------
1159 // It's worth also touching on the management of parallelism here. We don't
1160 // want to just spawn a thread per work item because while that's optimal
1161 // parallelism it may overload a system with too many threads or violate our
1162 // configuration for the maximum amount of cpu to use for this process. To
1163 // manage this we use the `jobserver` crate.
1165 // Job servers are an artifact of GNU make and are used to manage
1166 // parallelism between processes. A jobserver is a glorified IPC semaphore
1167 // basically. Whenever we want to run some work we acquire the semaphore,
1168 // and whenever we're done with that work we release the semaphore. In this
1169 // manner we can ensure that the maximum number of parallel workers is
1170 // capped at any one point in time.
1172 // LTO and the coordinator thread
1173 // ------------------------------
1175 // The final job the coordinator thread is responsible for is managing LTO
1176 // and how that works. When LTO is requested what we'll to is collect all
1177 // optimized LLVM modules into a local vector on the coordinator. Once all
1178 // modules have been codegened and optimized we hand this to the `lto`
1179 // module for further optimization. The `lto` module will return back a list
1180 // of more modules to work on, which the coordinator will continue to spawn
1183 // Each LLVM module is automatically sent back to the coordinator for LTO if
1184 // necessary. There's already optimizations in place to avoid sending work
1185 // back to the coordinator if LTO isn't requested.
1186 return thread::spawn(move || {
1187 // We pretend to be within the top-level LLVM time-passes task here:
1190 let max_workers = ::num_cpus::get();
1191 let mut worker_id_counter = 0;
1192 let mut free_worker_ids = Vec::new();
1193 let mut get_worker_id = |free_worker_ids: &mut Vec<usize>| {
1194 if let Some(id) = free_worker_ids.pop() {
1197 let id = worker_id_counter;
1198 worker_id_counter += 1;
1203 // This is where we collect codegen units that have gone all the way
1204 // through codegen and LLVM.
1205 let mut compiled_modules = vec![];
1206 let mut compiled_metadata_module = None;
1207 let mut compiled_allocator_module = None;
1208 let mut needs_fat_lto = Vec::new();
1209 let mut needs_thin_lto = Vec::new();
1210 let mut lto_import_only_modules = Vec::new();
1211 let mut started_lto = false;
1212 let mut codegen_aborted = false;
1214 // This flag tracks whether all items have gone through codegens
1215 let mut codegen_done = false;
1217 // This is the queue of LLVM work items that still need processing.
1218 let mut work_items = Vec::<(WorkItem<B>, u64)>::new();
1220 // This are the Jobserver Tokens we currently hold. Does not include
1221 // the implicit Token the compiler process owns no matter what.
1222 let mut tokens = Vec::new();
1224 let mut main_thread_worker_state = MainThreadWorkerState::Idle;
1225 let mut running = 0;
1227 let mut llvm_start_time = None;
1229 // Run the message loop while there's still anything that needs message
1230 // processing. Note that as soon as codegen is aborted we simply want to
1231 // wait for all existing work to finish, so many of the conditions here
1232 // only apply if codegen hasn't been aborted as they represent pending
1234 while !codegen_done ||
1236 (!codegen_aborted && (
1237 work_items.len() > 0 ||
1238 needs_fat_lto.len() > 0 ||
1239 needs_thin_lto.len() > 0 ||
1240 lto_import_only_modules.len() > 0 ||
1241 main_thread_worker_state != MainThreadWorkerState::Idle
1245 // While there are still CGUs to be codegened, the coordinator has
1246 // to decide how to utilize the compiler processes implicit Token:
1247 // For codegenning more CGU or for running them through LLVM.
1249 if main_thread_worker_state == MainThreadWorkerState::Idle {
1250 if !queue_full_enough(work_items.len(), running, max_workers) {
1251 // The queue is not full enough, codegen more items:
1252 if let Err(_) = codegen_worker_send.send(Message::CodegenItem) {
1253 panic!("Could not send Message::CodegenItem to main thread")
1255 main_thread_worker_state = MainThreadWorkerState::Codegenning;
1257 // The queue is full enough to not let the worker
1258 // threads starve. Use the implicit Token to do some
1260 let (item, _) = work_items.pop()
1261 .expect("queue empty - queue_full_enough() broken?");
1262 let cgcx = CodegenContext {
1263 worker: get_worker_id(&mut free_worker_ids),
1266 maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1267 &mut llvm_start_time);
1268 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1269 spawn_work(cgcx, item);
1272 } else if codegen_aborted {
1273 // don't queue up any more work if codegen was aborted, we're
1274 // just waiting for our existing children to finish
1276 // If we've finished everything related to normal codegen
1277 // then it must be the case that we've got some LTO work to do.
1278 // Perform the serial work here of figuring out what we're
1279 // going to LTO and then push a bunch of work items onto our
1281 if work_items.len() == 0 &&
1283 main_thread_worker_state == MainThreadWorkerState::Idle {
1284 assert!(!started_lto);
1287 let needs_fat_lto = mem::take(&mut needs_fat_lto);
1288 let needs_thin_lto = mem::take(&mut needs_thin_lto);
1289 let import_only_modules = mem::take(&mut lto_import_only_modules);
1291 for (work, cost) in generate_lto_work(&cgcx, needs_fat_lto,
1292 needs_thin_lto, import_only_modules) {
1293 let insertion_index = work_items
1294 .binary_search_by_key(&cost, |&(_, cost)| cost)
1295 .unwrap_or_else(|e| e);
1296 work_items.insert(insertion_index, (work, cost));
1297 if !cgcx.opts.debugging_opts.no_parallel_llvm {
1298 helper.request_token();
1303 // In this branch, we know that everything has been codegened,
1304 // so it's just a matter of determining whether the implicit
1305 // Token is free to use for LLVM work.
1306 match main_thread_worker_state {
1307 MainThreadWorkerState::Idle => {
1308 if let Some((item, _)) = work_items.pop() {
1309 let cgcx = CodegenContext {
1310 worker: get_worker_id(&mut free_worker_ids),
1313 maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1314 &mut llvm_start_time);
1315 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1316 spawn_work(cgcx, item);
1318 // There is no unstarted work, so let the main thread
1319 // take over for a running worker. Otherwise the
1320 // implicit token would just go to waste.
1321 // We reduce the `running` counter by one. The
1322 // `tokens.truncate()` below will take care of
1323 // giving the Token back.
1324 debug_assert!(running > 0);
1326 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1329 MainThreadWorkerState::Codegenning => {
1330 bug!("codegen worker should not be codegenning after \
1331 codegen was already completed")
1333 MainThreadWorkerState::LLVMing => {
1334 // Already making good use of that token
1339 // Spin up what work we can, only doing this while we've got available
1340 // parallelism slots and work left to spawn.
1341 while !codegen_aborted && work_items.len() > 0 && running < tokens.len() {
1342 let (item, _) = work_items.pop().unwrap();
1344 maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1345 &mut llvm_start_time);
1347 let cgcx = CodegenContext {
1348 worker: get_worker_id(&mut free_worker_ids),
1352 spawn_work(cgcx, item);
1356 // Relinquish accidentally acquired extra tokens
1357 tokens.truncate(running);
1359 // If a thread exits successfully then we drop a token associated
1360 // with that worker and update our `running` count. We may later
1361 // re-acquire a token to continue running more work. We may also not
1362 // actually drop a token here if the worker was running with an
1363 // "ephemeral token"
1364 let mut free_worker = |worker_id| {
1365 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1366 main_thread_worker_state = MainThreadWorkerState::Idle;
1371 free_worker_ids.push(worker_id);
1374 let msg = coordinator_receive.recv().unwrap();
1375 match *msg.downcast::<Message<B>>().ok().unwrap() {
1376 // Save the token locally and the next turn of the loop will use
1377 // this to spawn a new unit of work, or it may get dropped
1378 // immediately if we have no more work to spawn.
1379 Message::Token(token) => {
1384 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1385 // If the main thread token is used for LLVM work
1386 // at the moment, we turn that thread into a regular
1387 // LLVM worker thread, so the main thread is free
1388 // to react to codegen demand.
1389 main_thread_worker_state = MainThreadWorkerState::Idle;
1394 let msg = &format!("failed to acquire jobserver token: {}", e);
1395 shared_emitter.fatal(msg);
1396 // Exit the coordinator thread
1402 Message::CodegenDone { llvm_work_item, cost } => {
1403 // We keep the queue sorted by estimated processing cost,
1404 // so that more expensive items are processed earlier. This
1405 // is good for throughput as it gives the main thread more
1406 // time to fill up the queue and it avoids scheduling
1407 // expensive items to the end.
1408 // Note, however, that this is not ideal for memory
1409 // consumption, as LLVM module sizes are not evenly
1411 let insertion_index =
1412 work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1413 let insertion_index = match insertion_index {
1414 Ok(idx) | Err(idx) => idx
1416 work_items.insert(insertion_index, (llvm_work_item, cost));
1418 if !cgcx.opts.debugging_opts.no_parallel_llvm {
1419 helper.request_token();
1421 assert!(!codegen_aborted);
1422 assert_eq!(main_thread_worker_state,
1423 MainThreadWorkerState::Codegenning);
1424 main_thread_worker_state = MainThreadWorkerState::Idle;
1427 Message::CodegenComplete => {
1428 codegen_done = true;
1429 assert!(!codegen_aborted);
1430 assert_eq!(main_thread_worker_state,
1431 MainThreadWorkerState::Codegenning);
1432 main_thread_worker_state = MainThreadWorkerState::Idle;
1435 // If codegen is aborted that means translation was aborted due
1436 // to some normal-ish compiler error. In this situation we want
1437 // to exit as soon as possible, but we want to make sure all
1438 // existing work has finished. Flag codegen as being done, and
1439 // then conditions above will ensure no more work is spawned but
1440 // we'll keep executing this loop until `running` hits 0.
1441 Message::CodegenAborted => {
1442 assert!(!codegen_aborted);
1443 codegen_done = true;
1444 codegen_aborted = true;
1445 assert_eq!(main_thread_worker_state,
1446 MainThreadWorkerState::Codegenning);
1448 Message::Done { result: Ok(compiled_module), worker_id } => {
1449 free_worker(worker_id);
1450 match compiled_module.kind {
1451 ModuleKind::Regular => {
1452 compiled_modules.push(compiled_module);
1454 ModuleKind::Metadata => {
1455 assert!(compiled_metadata_module.is_none());
1456 compiled_metadata_module = Some(compiled_module);
1458 ModuleKind::Allocator => {
1459 assert!(compiled_allocator_module.is_none());
1460 compiled_allocator_module = Some(compiled_module);
1464 Message::NeedsFatLTO { result, worker_id } => {
1465 assert!(!started_lto);
1466 free_worker(worker_id);
1467 needs_fat_lto.push(result);
1469 Message::NeedsThinLTO { name, thin_buffer, worker_id } => {
1470 assert!(!started_lto);
1471 free_worker(worker_id);
1472 needs_thin_lto.push((name, thin_buffer));
1474 Message::AddImportOnlyModule { module_data, work_product } => {
1475 assert!(!started_lto);
1476 assert!(!codegen_done);
1477 assert_eq!(main_thread_worker_state,
1478 MainThreadWorkerState::Codegenning);
1479 lto_import_only_modules.push((module_data, work_product));
1480 main_thread_worker_state = MainThreadWorkerState::Idle;
1482 // If the thread failed that means it panicked, so we abort immediately.
1483 Message::Done { result: Err(()), worker_id: _ } => {
1484 bug!("worker thread panicked");
1486 Message::CodegenItem => {
1487 bug!("the coordinator should not receive codegen requests")
1492 if let Some(llvm_start_time) = llvm_start_time {
1493 let total_llvm_time = Instant::now().duration_since(llvm_start_time);
1494 // This is the top-level timing for all of LLVM, set the time-depth
1497 print_time_passes_entry(cgcx.time_passes,
1502 // Regardless of what order these modules completed in, report them to
1503 // the backend in the same order every time to ensure that we're handing
1504 // out deterministic results.
1505 compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
1507 Ok(CompiledModules {
1508 modules: compiled_modules,
1509 metadata_module: compiled_metadata_module,
1510 allocator_module: compiled_allocator_module,
1514 // A heuristic that determines if we have enough LLVM WorkItems in the
1515 // queue so that the main thread can do LLVM work instead of codegen
1516 fn queue_full_enough(items_in_queue: usize,
1517 workers_running: usize,
1518 max_workers: usize) -> bool {
1520 items_in_queue > 0 &&
1521 items_in_queue >= max_workers.saturating_sub(workers_running / 2)
1524 fn maybe_start_llvm_timer(config: &ModuleConfig,
1525 llvm_start_time: &mut Option<Instant>) {
1526 // We keep track of the -Ztime-passes output manually,
1527 // since the closure-based interface does not fit well here.
1528 if config.time_passes {
1529 if llvm_start_time.is_none() {
1530 *llvm_start_time = Some(Instant::now());
1536 pub const CODEGEN_WORKER_ID: usize = ::std::usize::MAX;
1538 fn spawn_work<B: ExtraBackendMethods>(
1539 cgcx: CodegenContext<B>,
1542 let depth = time_depth();
1544 thread::spawn(move || {
1545 set_time_depth(depth);
1547 // Set up a destructor which will fire off a message that we're done as
1549 struct Bomb<B: ExtraBackendMethods> {
1550 coordinator_send: Sender<Box<dyn Any + Send>>,
1551 result: Option<WorkItemResult<B>>,
1554 impl<B: ExtraBackendMethods> Drop for Bomb<B> {
1555 fn drop(&mut self) {
1556 let worker_id = self.worker_id;
1557 let msg = match self.result.take() {
1558 Some(WorkItemResult::Compiled(m)) => {
1559 Message::Done::<B> { result: Ok(m), worker_id }
1561 Some(WorkItemResult::NeedsFatLTO(m)) => {
1562 Message::NeedsFatLTO::<B> { result: m, worker_id }
1564 Some(WorkItemResult::NeedsThinLTO(name, thin_buffer)) => {
1565 Message::NeedsThinLTO::<B> { name, thin_buffer, worker_id }
1567 None => Message::Done::<B> { result: Err(()), worker_id }
1569 drop(self.coordinator_send.send(Box::new(msg)));
1573 let mut bomb = Bomb::<B> {
1574 coordinator_send: cgcx.coordinator_send.clone(),
1576 worker_id: cgcx.worker,
1579 // Execute the work itself, and if it finishes successfully then flag
1580 // ourselves as a success as well.
1582 // Note that we ignore any `FatalError` coming out of `execute_work_item`,
1583 // as a diagnostic was already sent off to the main thread - just
1584 // surface that there was an error in this worker.
1586 let _prof_timer = cgcx.prof.generic_activity(work.profiling_event_id());
1587 execute_work_item(&cgcx, work).ok()
1592 pub fn run_assembler<B: ExtraBackendMethods>(
1593 cgcx: &CodegenContext<B>,
1598 let assembler = cgcx.assembler_cmd
1600 .expect("cgcx.assembler_cmd is missing?");
1602 let pname = &assembler.name;
1603 let mut cmd = assembler.cmd.clone();
1604 cmd.arg("-c").arg("-o").arg(object).arg(assembly);
1605 debug!("{:?}", cmd);
1607 match cmd.output() {
1609 if !prog.status.success() {
1610 let mut note = prog.stderr.clone();
1611 note.extend_from_slice(&prog.stdout);
1613 handler.struct_err(&format!("linking with `{}` failed: {}",
1616 .note(&format!("{:?}", &cmd))
1617 .note(str::from_utf8(¬e[..]).unwrap())
1619 handler.abort_if_errors();
1623 handler.err(&format!("could not exec the linker `{}`: {}", pname.display(), e));
1624 handler.abort_if_errors();
1630 enum SharedEmitterMessage {
1631 Diagnostic(Diagnostic),
1632 InlineAsmError(u32, String),
1638 pub struct SharedEmitter {
1639 sender: Sender<SharedEmitterMessage>,
1642 pub struct SharedEmitterMain {
1643 receiver: Receiver<SharedEmitterMessage>,
1646 impl SharedEmitter {
1647 pub fn new() -> (SharedEmitter, SharedEmitterMain) {
1648 let (sender, receiver) = channel();
1650 (SharedEmitter { sender }, SharedEmitterMain { receiver })
1653 pub fn inline_asm_error(&self, cookie: u32, msg: String) {
1654 drop(self.sender.send(SharedEmitterMessage::InlineAsmError(cookie, msg)));
1657 pub fn fatal(&self, msg: &str) {
1658 drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1662 impl Emitter for SharedEmitter {
1663 fn emit_diagnostic(&mut self, diag: &rustc_errors::Diagnostic) {
1664 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1665 msg: diag.message(),
1666 code: diag.code.clone(),
1669 for child in &diag.children {
1670 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1671 msg: child.message(),
1676 drop(self.sender.send(SharedEmitterMessage::AbortIfErrors));
1678 fn source_map(&self) -> Option<&Lrc<SourceMap>> {
1683 impl SharedEmitterMain {
1684 pub fn check(&self, sess: &Session, blocking: bool) {
1686 let message = if blocking {
1687 match self.receiver.recv() {
1688 Ok(message) => Ok(message),
1692 match self.receiver.try_recv() {
1693 Ok(message) => Ok(message),
1699 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
1700 let handler = sess.diagnostic();
1701 let mut d = rustc_errors::Diagnostic::new(diag.lvl, &diag.msg);
1702 if let Some(code) = diag.code {
1705 handler.emit_diagnostic(&d);
1706 handler.abort_if_errors_and_should_abort();
1708 Ok(SharedEmitterMessage::InlineAsmError(cookie, msg)) => {
1709 sess.span_err(ExpnId::from_u32(cookie).expn_data().call_site, &msg)
1711 Ok(SharedEmitterMessage::AbortIfErrors) => {
1712 sess.abort_if_errors();
1714 Ok(SharedEmitterMessage::Fatal(msg)) => {
1726 pub struct OngoingCodegen<B: ExtraBackendMethods> {
1728 pub crate_name: Symbol,
1729 pub crate_hash: Svh,
1730 pub metadata: EncodedMetadata,
1731 pub windows_subsystem: Option<String>,
1732 pub linker_info: LinkerInfo,
1733 pub crate_info: CrateInfo,
1734 pub coordinator_send: Sender<Box<dyn Any + Send>>,
1735 pub codegen_worker_receive: Receiver<Message<B>>,
1736 pub shared_emitter_main: SharedEmitterMain,
1737 pub future: thread::JoinHandle<Result<CompiledModules, ()>>,
1738 pub output_filenames: Arc<OutputFilenames>,
1741 impl<B: ExtraBackendMethods> OngoingCodegen<B> {
1745 ) -> (CodegenResults, FxHashMap<WorkProductId, WorkProduct>) {
1746 self.shared_emitter_main.check(sess, true);
1747 let compiled_modules = match self.future.join() {
1748 Ok(Ok(compiled_modules)) => compiled_modules,
1750 sess.abort_if_errors();
1751 panic!("expected abort due to worker thread errors")
1754 bug!("panic during codegen/LLVM phase");
1758 sess.cgu_reuse_tracker.check_expected_reuse(sess);
1760 sess.abort_if_errors();
1763 copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess,
1765 produce_final_output_artifacts(sess,
1767 &self.output_filenames);
1769 // FIXME: time_llvm_passes support - does this use a global context or
1771 if sess.codegen_units() == 1 && sess.time_llvm_passes() {
1772 self.backend.print_pass_timings()
1776 crate_name: self.crate_name,
1777 crate_hash: self.crate_hash,
1778 metadata: self.metadata,
1779 windows_subsystem: self.windows_subsystem,
1780 linker_info: self.linker_info,
1781 crate_info: self.crate_info,
1783 modules: compiled_modules.modules,
1784 allocator_module: compiled_modules.allocator_module,
1785 metadata_module: compiled_modules.metadata_module,
1789 pub fn submit_pre_codegened_module_to_llvm(
1792 module: ModuleCodegen<B::Module>,
1794 self.wait_for_signal_to_codegen_item();
1795 self.check_for_errors(tcx.sess);
1797 // These are generally cheap and won't throw off scheduling.
1799 submit_codegened_module_to_llvm(&self.backend, &self.coordinator_send, module, cost);
1802 pub fn codegen_finished(&self, tcx: TyCtxt<'_>) {
1803 self.wait_for_signal_to_codegen_item();
1804 self.check_for_errors(tcx.sess);
1805 drop(self.coordinator_send.send(Box::new(Message::CodegenComplete::<B>)));
1808 /// Consumes this context indicating that codegen was entirely aborted, and
1809 /// we need to exit as quickly as possible.
1811 /// This method blocks the current thread until all worker threads have
1812 /// finished, and all worker threads should have exited or be real close to
1813 /// exiting at this point.
1814 pub fn codegen_aborted(self) {
1815 // Signal to the coordinator it should spawn no more work and start
1817 drop(self.coordinator_send.send(Box::new(Message::CodegenAborted::<B>)));
1818 drop(self.future.join());
1821 pub fn check_for_errors(&self, sess: &Session) {
1822 self.shared_emitter_main.check(sess, false);
1825 pub fn wait_for_signal_to_codegen_item(&self) {
1826 match self.codegen_worker_receive.recv() {
1827 Ok(Message::CodegenItem) => {
1830 Ok(_) => panic!("unexpected message"),
1832 // One of the LLVM threads must have panicked, fall through so
1833 // error handling can be reached.
1839 pub fn submit_codegened_module_to_llvm<B: ExtraBackendMethods>(
1841 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
1842 module: ModuleCodegen<B::Module>,
1845 let llvm_work_item = WorkItem::Optimize(module);
1846 drop(tx_to_llvm_workers.send(Box::new(Message::CodegenDone::<B> {
1852 pub fn submit_post_lto_module_to_llvm<B: ExtraBackendMethods>(
1854 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
1855 module: CachedModuleCodegen,
1857 let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
1858 drop(tx_to_llvm_workers.send(Box::new(Message::CodegenDone::<B> {
1864 pub fn submit_pre_lto_module_to_llvm<B: ExtraBackendMethods>(
1867 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
1868 module: CachedModuleCodegen,
1870 let filename = pre_lto_bitcode_filename(&module.name);
1871 let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
1872 let file = fs::File::open(&bc_path).unwrap_or_else(|e| {
1873 panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e)
1877 memmap::Mmap::map(&file).unwrap_or_else(|e| {
1878 panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
1881 // Schedule the module to be loaded
1882 drop(tx_to_llvm_workers.send(Box::new(Message::AddImportOnlyModule::<B> {
1883 module_data: SerializedModule::FromUncompressedFile(mmap),
1884 work_product: module.source,
1888 pub fn pre_lto_bitcode_filename(module_name: &str) -> String {
1889 format!("{}.{}", module_name, PRE_LTO_BC_EXT)
1892 fn msvc_imps_needed(tcx: TyCtxt<'_>) -> bool {
1893 // This should never be true (because it's not supported). If it is true,
1894 // something is wrong with commandline arg validation.
1895 assert!(!(tcx.sess.opts.cg.linker_plugin_lto.enabled() &&
1896 tcx.sess.target.target.options.is_like_msvc &&
1897 tcx.sess.opts.cg.prefer_dynamic));
1899 tcx.sess.target.target.options.is_like_msvc &&
1900 tcx.sess.crate_types.borrow().iter().any(|ct| *ct == config::CrateType::Rlib) &&
1901 // ThinLTO can't handle this workaround in all cases, so we don't
1902 // emit the `__imp_` symbols. Instead we make them unnecessary by disallowing
1903 // dynamic linking when linker plugin LTO is enabled.
1904 !tcx.sess.opts.cg.linker_plugin_lto.enabled()