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, Sanitizer, Lto};
16 use rustc::session::Session;
17 use rustc::util::nodemap::FxHashMap;
18 use rustc::util::time_graph::{self, TimeGraph, Timeline};
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_fs_util::link_or_copy;
23 use rustc_data_structures::svh::Svh;
24 use rustc_errors::{Handler, Level, DiagnosticBuilder, FatalError, DiagnosticId};
25 use rustc_errors::emitter::{Emitter};
26 use rustc_target::spec::MergeFunctions;
28 use syntax::ext::hygiene::Mark;
29 use syntax_pos::MultiSpan;
30 use syntax_pos::symbol::Symbol;
31 use jobserver::{Client, Acquired};
37 use std::path::{Path, PathBuf};
40 use std::sync::mpsc::{channel, Sender, Receiver};
41 use std::time::Instant;
44 const PRE_LTO_BC_EXT: &str = "pre-lto.bc";
46 /// Module-specific configuration for `optimize_and_codegen`.
47 pub struct ModuleConfig {
48 /// Names of additional optimization passes to run.
49 pub passes: Vec<String>,
50 /// Some(level) to optimize at a certain level, or None to run
51 /// absolutely no optimizations (used for the metadata module).
52 pub opt_level: Option<config::OptLevel>,
54 /// Some(level) to optimize binary size, or None to not affect program size.
55 pub opt_size: Option<config::OptLevel>,
57 pub pgo_gen: Option<String>,
60 // Flags indicating which outputs to produce.
61 pub emit_pre_lto_bc: bool,
62 pub emit_no_opt_bc: bool,
64 pub emit_bc_compressed: bool,
65 pub emit_lto_bc: bool,
69 // Miscellaneous flags. These are mostly copied from command-line
71 pub verify_llvm_ir: bool,
72 pub no_prepopulate_passes: bool,
73 pub no_builtins: bool,
74 pub time_passes: bool,
75 pub vectorize_loop: bool,
76 pub vectorize_slp: bool,
77 pub merge_functions: bool,
78 pub inline_threshold: Option<usize>,
79 // Instead of creating an object file by doing LLVM codegen, just
80 // make the object file bitcode. Provides easy compatibility with
81 // emscripten's ecc compiler, when used as the linker.
82 pub obj_is_bitcode: bool,
83 pub no_integrated_as: bool,
84 pub embed_bitcode: bool,
85 pub embed_bitcode_marker: bool,
89 fn new(passes: Vec<String>) -> ModuleConfig {
96 pgo_use: String::new(),
98 emit_no_opt_bc: false,
99 emit_pre_lto_bc: false,
101 emit_bc_compressed: false,
106 obj_is_bitcode: false,
107 embed_bitcode: false,
108 embed_bitcode_marker: false,
109 no_integrated_as: false,
111 verify_llvm_ir: false,
112 no_prepopulate_passes: false,
115 vectorize_loop: false,
116 vectorize_slp: false,
117 merge_functions: false,
118 inline_threshold: None
122 fn set_flags(&mut self, sess: &Session, no_builtins: bool) {
123 self.verify_llvm_ir = sess.verify_llvm_ir();
124 self.no_prepopulate_passes = sess.opts.cg.no_prepopulate_passes;
125 self.no_builtins = no_builtins || sess.target.target.options.no_builtins;
126 self.time_passes = sess.time_passes();
127 self.inline_threshold = sess.opts.cg.inline_threshold;
128 self.obj_is_bitcode = sess.target.target.options.obj_is_bitcode ||
129 sess.opts.cg.linker_plugin_lto.enabled();
130 let embed_bitcode = sess.target.target.options.embed_bitcode ||
131 sess.opts.debugging_opts.embed_bitcode;
133 match sess.opts.optimize {
134 config::OptLevel::No |
135 config::OptLevel::Less => {
136 self.embed_bitcode_marker = embed_bitcode;
138 _ => self.embed_bitcode = embed_bitcode,
142 // Copy what clang does by turning on loop vectorization at O2 and
143 // slp vectorization at O3. Otherwise configure other optimization aspects
144 // of this pass manager builder.
145 // Turn off vectorization for emscripten, as it's not very well supported.
146 self.vectorize_loop = !sess.opts.cg.no_vectorize_loops &&
147 (sess.opts.optimize == config::OptLevel::Default ||
148 sess.opts.optimize == config::OptLevel::Aggressive) &&
149 !sess.target.target.options.is_like_emscripten;
151 self.vectorize_slp = !sess.opts.cg.no_vectorize_slp &&
152 sess.opts.optimize == config::OptLevel::Aggressive &&
153 !sess.target.target.options.is_like_emscripten;
155 // Some targets (namely, NVPTX) interact badly with the MergeFunctions
156 // pass. This is because MergeFunctions can generate new function calls
157 // which may interfere with the target calling convention; e.g. for the
158 // NVPTX target, PTX kernels should not call other PTX kernels.
159 // MergeFunctions can also be configured to generate aliases instead,
160 // but aliases are not supported by some backends (again, NVPTX).
161 // Therefore, allow targets to opt out of the MergeFunctions pass,
162 // but otherwise keep the pass enabled (at O2 and O3) since it can be
163 // useful for reducing code size.
164 self.merge_functions = match sess.opts.debugging_opts.merge_functions
165 .unwrap_or(sess.target.target.options.merge_functions) {
166 MergeFunctions::Disabled => false,
167 MergeFunctions::Trampolines |
168 MergeFunctions::Aliases => {
169 sess.opts.optimize == config::OptLevel::Default ||
170 sess.opts.optimize == config::OptLevel::Aggressive
175 pub fn bitcode_needed(&self) -> bool {
176 self.emit_bc || self.obj_is_bitcode
177 || self.emit_bc_compressed || self.embed_bitcode
181 /// Assembler name and command used by codegen when no_integrated_as is enabled
182 pub struct AssemblerCommand {
187 // HACK(eddyb) work around `#[derive]` producing wrong bounds for `Clone`.
188 pub struct TargetMachineFactory<B: WriteBackendMethods>(
189 pub Arc<dyn Fn() -> Result<B::TargetMachine, String> + Send + Sync>,
192 impl<B: WriteBackendMethods> Clone for TargetMachineFactory<B> {
193 fn clone(&self) -> Self {
194 TargetMachineFactory(self.0.clone())
198 /// Additional resources used by optimize_and_codegen (not module specific)
200 pub struct CodegenContext<B: WriteBackendMethods> {
201 // Resources needed when running LTO
203 pub time_passes: bool,
205 pub no_landing_pads: bool,
206 pub save_temps: bool,
207 pub fewer_names: bool,
208 pub exported_symbols: Option<Arc<ExportedSymbols>>,
209 pub opts: Arc<config::Options>,
210 pub crate_types: Vec<config::CrateType>,
211 pub each_linked_rlib_for_lto: Vec<(CrateNum, PathBuf)>,
212 pub output_filenames: Arc<OutputFilenames>,
213 pub regular_module_config: Arc<ModuleConfig>,
214 pub metadata_module_config: Arc<ModuleConfig>,
215 pub allocator_module_config: Arc<ModuleConfig>,
216 pub tm_factory: TargetMachineFactory<B>,
217 pub msvc_imps_needed: bool,
218 pub target_pointer_width: String,
219 pub debuginfo: config::DebugInfo,
221 // Number of cgus excluding the allocator/metadata modules
222 pub total_cgus: usize,
223 // Handler to use for diagnostics produced during codegen.
224 pub diag_emitter: SharedEmitter,
225 // LLVM passes added by plugins.
226 pub plugin_passes: Vec<String>,
227 // LLVM optimizations for which we want to print remarks.
229 // Worker thread number
231 // The incremental compilation session directory, or None if we are not
232 // compiling incrementally
233 pub incr_comp_session_dir: Option<PathBuf>,
234 // Used to update CGU re-use information during the thinlto phase.
235 pub cgu_reuse_tracker: CguReuseTracker,
236 // Channel back to the main control thread to send messages to
237 pub coordinator_send: Sender<Box<dyn Any + Send>>,
238 // A reference to the TimeGraph so we can register timings. None means that
239 // measuring is disabled.
240 pub time_graph: Option<TimeGraph>,
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, false, 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 mut timeline = cgcx.time_graph.as_ref().map(|tg| {
266 tg.start(CODEGEN_WORKER_TIMELINE,
267 CODEGEN_WORK_PACKAGE_KIND,
269 }).unwrap_or(Timeline::noop());
271 let (lto_modules, copy_jobs) = if !needs_fat_lto.is_empty() {
272 assert!(needs_thin_lto.is_empty());
273 let lto_module = B::run_fat_lto(
279 .unwrap_or_else(|e| e.raise());
280 (vec![lto_module], vec![])
282 assert!(needs_fat_lto.is_empty());
283 B::run_thin_lto(cgcx, needs_thin_lto, import_only_modules, &mut timeline)
284 .unwrap_or_else(|e| e.raise())
287 lto_modules.into_iter().map(|module| {
288 let cost = module.cost();
289 (WorkItem::LTO(module), cost)
290 }).chain(copy_jobs.into_iter().map(|wp| {
291 (WorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
292 name: wp.cgu_name.clone(),
298 pub struct CompiledModules {
299 pub modules: Vec<CompiledModule>,
300 pub metadata_module: CompiledModule,
301 pub allocator_module: Option<CompiledModule>,
304 fn need_crate_bitcode_for_rlib(sess: &Session) -> bool {
305 sess.crate_types.borrow().contains(&config::CrateType::Rlib) &&
306 sess.opts.output_types.contains_key(&OutputType::Exe)
309 fn need_pre_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
310 if sess.opts.incremental.is_none() {
318 Lto::ThinLocal => true,
322 pub fn start_async_codegen<B: ExtraBackendMethods>(
325 time_graph: Option<TimeGraph>,
326 metadata: EncodedMetadata,
327 coordinator_receive: Receiver<Box<dyn Any + Send>>,
329 ) -> OngoingCodegen<B> {
331 let crate_name = tcx.crate_name(LOCAL_CRATE);
332 let crate_hash = tcx.crate_hash(LOCAL_CRATE);
333 let no_builtins = attr::contains_name(&tcx.hir().krate().attrs, "no_builtins");
334 let subsystem = attr::first_attr_value_str_by_name(&tcx.hir().krate().attrs,
335 "windows_subsystem");
336 let windows_subsystem = subsystem.map(|subsystem| {
337 if subsystem != "windows" && subsystem != "console" {
338 tcx.sess.fatal(&format!("invalid windows subsystem `{}`, only \
339 `windows` and `console` are allowed",
342 subsystem.to_string()
345 let linker_info = LinkerInfo::new(tcx);
346 let crate_info = CrateInfo::new(tcx);
348 // Figure out what we actually need to build.
349 let mut modules_config = ModuleConfig::new(sess.opts.cg.passes.clone());
350 let mut metadata_config = ModuleConfig::new(vec![]);
351 let mut allocator_config = ModuleConfig::new(vec![]);
353 if let Some(ref sanitizer) = sess.opts.debugging_opts.sanitizer {
355 Sanitizer::Address => {
356 modules_config.passes.push("asan".to_owned());
357 modules_config.passes.push("asan-module".to_owned());
359 Sanitizer::Memory => {
360 modules_config.passes.push("msan".to_owned())
362 Sanitizer::Thread => {
363 modules_config.passes.push("tsan".to_owned())
369 if sess.opts.debugging_opts.profile {
370 modules_config.passes.push("insert-gcov-profiling".to_owned())
373 modules_config.pgo_gen = sess.opts.debugging_opts.pgo_gen.clone();
374 modules_config.pgo_use = sess.opts.debugging_opts.pgo_use.clone();
376 modules_config.opt_level = Some(sess.opts.optimize);
377 modules_config.opt_size = Some(sess.opts.optimize);
379 // Save all versions of the bytecode if we're saving our temporaries.
380 if sess.opts.cg.save_temps {
381 modules_config.emit_no_opt_bc = true;
382 modules_config.emit_pre_lto_bc = true;
383 modules_config.emit_bc = true;
384 modules_config.emit_lto_bc = true;
385 metadata_config.emit_bc = true;
386 allocator_config.emit_bc = true;
389 // Emit compressed bitcode files for the crate if we're emitting an rlib.
390 // Whenever an rlib is created, the bitcode is inserted into the archive in
391 // order to allow LTO against it.
392 if need_crate_bitcode_for_rlib(sess) {
393 modules_config.emit_bc_compressed = true;
394 allocator_config.emit_bc_compressed = true;
397 modules_config.emit_pre_lto_bc =
398 need_pre_lto_bitcode_for_incr_comp(sess);
400 modules_config.no_integrated_as = tcx.sess.opts.cg.no_integrated_as ||
401 tcx.sess.target.target.options.no_integrated_as;
403 for output_type in sess.opts.output_types.keys() {
405 OutputType::Bitcode => { modules_config.emit_bc = true; }
406 OutputType::LlvmAssembly => { modules_config.emit_ir = true; }
407 OutputType::Assembly => {
408 modules_config.emit_asm = true;
409 // If we're not using the LLVM assembler, this function
410 // could be invoked specially with output_type_assembly, so
411 // in this case we still want the metadata object file.
412 if !sess.opts.output_types.contains_key(&OutputType::Assembly) {
413 metadata_config.emit_obj = true;
414 allocator_config.emit_obj = true;
417 OutputType::Object => { modules_config.emit_obj = true; }
418 OutputType::Metadata => { metadata_config.emit_obj = true; }
420 modules_config.emit_obj = true;
421 metadata_config.emit_obj = true;
422 allocator_config.emit_obj = true;
424 OutputType::Mir => {}
425 OutputType::DepInfo => {}
429 modules_config.set_flags(sess, no_builtins);
430 metadata_config.set_flags(sess, no_builtins);
431 allocator_config.set_flags(sess, no_builtins);
433 // Exclude metadata and allocator modules from time_passes output, since
434 // they throw off the "LLVM passes" measurement.
435 metadata_config.time_passes = false;
436 allocator_config.time_passes = false;
438 let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
439 let (codegen_worker_send, codegen_worker_receive) = channel();
441 let coordinator_thread = start_executing_work(backend.clone(),
448 sess.jobserver.clone(),
450 Arc::new(modules_config),
451 Arc::new(metadata_config),
452 Arc::new(allocator_config));
464 coordinator_send: tcx.tx_to_llvm_workers.lock().clone(),
465 codegen_worker_receive,
467 future: coordinator_thread,
468 output_filenames: tcx.output_filenames(LOCAL_CRATE),
472 fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
474 compiled_modules: &CompiledModules,
475 ) -> FxHashMap<WorkProductId, WorkProduct> {
476 let mut work_products = FxHashMap::default();
478 if sess.opts.incremental.is_none() {
479 return work_products;
482 for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
483 let mut files = vec![];
485 if let Some(ref path) = module.object {
486 files.push((WorkProductFileKind::Object, path.clone()));
488 if let Some(ref path) = module.bytecode {
489 files.push((WorkProductFileKind::Bytecode, path.clone()));
491 if let Some(ref path) = module.bytecode_compressed {
492 files.push((WorkProductFileKind::BytecodeCompressed, path.clone()));
495 if let Some((id, product)) =
496 copy_cgu_workproducts_to_incr_comp_cache_dir(sess, &module.name, &files) {
497 work_products.insert(id, product);
504 fn produce_final_output_artifacts(sess: &Session,
505 compiled_modules: &CompiledModules,
506 crate_output: &OutputFilenames) {
507 let mut user_wants_bitcode = false;
508 let mut user_wants_objects = false;
510 // Produce final compile outputs.
511 let copy_gracefully = |from: &Path, to: &Path| {
512 if let Err(e) = fs::copy(from, to) {
513 sess.err(&format!("could not copy {:?} to {:?}: {}", from, to, e));
517 let copy_if_one_unit = |output_type: OutputType,
518 keep_numbered: bool| {
519 if compiled_modules.modules.len() == 1 {
520 // 1) Only one codegen unit. In this case it's no difficulty
521 // to copy `foo.0.x` to `foo.x`.
522 let module_name = Some(&compiled_modules.modules[0].name[..]);
523 let path = crate_output.temp_path(output_type, module_name);
524 copy_gracefully(&path,
525 &crate_output.path(output_type));
526 if !sess.opts.cg.save_temps && !keep_numbered {
527 // The user just wants `foo.x`, not `foo.#module-name#.x`.
531 let ext = crate_output.temp_path(output_type, None)
538 if crate_output.outputs.contains_key(&output_type) {
539 // 2) Multiple codegen units, with `--emit foo=some_name`. We have
540 // no good solution for this case, so warn the user.
541 sess.warn(&format!("ignoring emit path because multiple .{} files \
542 were produced", ext));
543 } else if crate_output.single_output_file.is_some() {
544 // 3) Multiple codegen units, with `-o some_name`. We have
545 // no good solution for this case, so warn the user.
546 sess.warn(&format!("ignoring -o because multiple .{} files \
547 were produced", ext));
549 // 4) Multiple codegen units, but no explicit name. We
550 // just leave the `foo.0.x` files in place.
551 // (We don't have to do any work in this case.)
556 // Flag to indicate whether the user explicitly requested bitcode.
557 // Otherwise, we produced it only as a temporary output, and will need
559 for output_type in crate_output.outputs.keys() {
561 OutputType::Bitcode => {
562 user_wants_bitcode = true;
563 // Copy to .bc, but always keep the .0.bc. There is a later
564 // check to figure out if we should delete .0.bc files, or keep
565 // them for making an rlib.
566 copy_if_one_unit(OutputType::Bitcode, true);
568 OutputType::LlvmAssembly => {
569 copy_if_one_unit(OutputType::LlvmAssembly, false);
571 OutputType::Assembly => {
572 copy_if_one_unit(OutputType::Assembly, false);
574 OutputType::Object => {
575 user_wants_objects = true;
576 copy_if_one_unit(OutputType::Object, true);
579 OutputType::Metadata |
581 OutputType::DepInfo => {}
585 // Clean up unwanted temporary files.
587 // We create the following files by default:
588 // - #crate#.#module-name#.bc
589 // - #crate#.#module-name#.o
590 // - #crate#.crate.metadata.bc
591 // - #crate#.crate.metadata.o
592 // - #crate#.o (linked from crate.##.o)
593 // - #crate#.bc (copied from crate.##.bc)
594 // We may create additional files if requested by the user (through
595 // `-C save-temps` or `--emit=` flags).
597 if !sess.opts.cg.save_temps {
598 // Remove the temporary .#module-name#.o objects. If the user didn't
599 // explicitly request bitcode (with --emit=bc), and the bitcode is not
600 // needed for building an rlib, then we must remove .#module-name#.bc as
603 // Specific rules for keeping .#module-name#.bc:
604 // - If the user requested bitcode (`user_wants_bitcode`), and
605 // codegen_units > 1, then keep it.
606 // - If the user requested bitcode but codegen_units == 1, then we
607 // can toss .#module-name#.bc because we copied it to .bc earlier.
608 // - If we're not building an rlib and the user didn't request
609 // bitcode, then delete .#module-name#.bc.
610 // If you change how this works, also update back::link::link_rlib,
611 // where .#module-name#.bc files are (maybe) deleted after making an
613 let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
615 let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units() > 1;
617 let keep_numbered_objects = needs_crate_object ||
618 (user_wants_objects && sess.codegen_units() > 1);
620 for module in compiled_modules.modules.iter() {
621 if let Some(ref path) = module.object {
622 if !keep_numbered_objects {
627 if let Some(ref path) = module.bytecode {
628 if !keep_numbered_bitcode {
634 if !user_wants_bitcode {
635 if let Some(ref path) = compiled_modules.metadata_module.bytecode {
639 if let Some(ref allocator_module) = compiled_modules.allocator_module {
640 if let Some(ref path) = allocator_module.bytecode {
647 // We leave the following files around by default:
649 // - #crate#.crate.metadata.o
651 // These are used in linking steps and will be cleaned up afterward.
654 pub fn dump_incremental_data(_codegen_results: &CodegenResults) {
655 // FIXME(mw): This does not work at the moment because the situation has
656 // become more complicated due to incremental LTO. Now a CGU
657 // can have more than two caching states.
658 // println!("[incremental] Re-using {} out of {} modules",
659 // codegen_results.modules.iter().filter(|m| m.pre_existing).count(),
660 // codegen_results.modules.len());
663 pub enum WorkItem<B: WriteBackendMethods> {
664 /// Optimize a newly codegened, totally unoptimized module.
665 Optimize(ModuleCodegen<B::Module>),
666 /// Copy the post-LTO artifacts from the incremental cache to the output
668 CopyPostLtoArtifacts(CachedModuleCodegen),
669 /// Performs (Thin)LTO on the given module.
670 LTO(lto::LtoModuleCodegen<B>),
673 impl<B: WriteBackendMethods> WorkItem<B> {
674 pub fn module_kind(&self) -> ModuleKind {
676 WorkItem::Optimize(ref m) => m.kind,
677 WorkItem::CopyPostLtoArtifacts(_) |
678 WorkItem::LTO(_) => ModuleKind::Regular,
682 pub fn name(&self) -> String {
684 WorkItem::Optimize(ref m) => format!("optimize: {}", m.name),
685 WorkItem::CopyPostLtoArtifacts(ref m) => format!("copy post LTO artifacts: {}", m.name),
686 WorkItem::LTO(ref m) => format!("lto: {}", m.name()),
691 enum WorkItemResult<B: WriteBackendMethods> {
692 Compiled(CompiledModule),
693 NeedsFatLTO(FatLTOInput<B>),
694 NeedsThinLTO(String, B::ThinBuffer),
697 pub enum FatLTOInput<B: WriteBackendMethods> {
700 buffer: B::ModuleBuffer,
702 InMemory(ModuleCodegen<B::Module>),
705 fn execute_work_item<B: ExtraBackendMethods>(
706 cgcx: &CodegenContext<B>,
707 work_item: WorkItem<B>,
708 timeline: &mut Timeline
709 ) -> Result<WorkItemResult<B>, FatalError> {
710 let module_config = cgcx.config(work_item.module_kind());
713 WorkItem::Optimize(module) => {
714 execute_optimize_work_item(cgcx, module, module_config, timeline)
716 WorkItem::CopyPostLtoArtifacts(module) => {
717 execute_copy_from_cache_work_item(cgcx, module, module_config, timeline)
719 WorkItem::LTO(module) => {
720 execute_lto_work_item(cgcx, module, module_config, timeline)
725 // Actual LTO type we end up chosing based on multiple factors.
726 enum ComputedLtoType {
732 fn execute_optimize_work_item<B: ExtraBackendMethods>(
733 cgcx: &CodegenContext<B>,
734 module: ModuleCodegen<B::Module>,
735 module_config: &ModuleConfig,
736 timeline: &mut Timeline
737 ) -> Result<WorkItemResult<B>, FatalError> {
738 let diag_handler = cgcx.create_diag_handler();
741 B::optimize(cgcx, &diag_handler, &module, module_config, timeline)?;
744 // After we've done the initial round of optimizations we need to
745 // decide whether to synchronously codegen this module or ship it
746 // back to the coordinator thread for further LTO processing (which
747 // has to wait for all the initial modules to be optimized).
749 // If the linker does LTO, we don't have to do it. Note that we
750 // keep doing full LTO, if it is requested, as not to break the
751 // assumption that the output will be a single module.
752 let linker_does_lto = cgcx.opts.cg.linker_plugin_lto.enabled();
754 // When we're automatically doing ThinLTO for multi-codegen-unit
755 // builds we don't actually want to LTO the allocator modules if
756 // it shows up. This is due to various linker shenanigans that
757 // we'll encounter later.
758 let is_allocator = module.kind == ModuleKind::Allocator;
760 // We ignore a request for full crate grath LTO if the cate type
761 // is only an rlib, as there is no full crate graph to process,
762 // that'll happen later.
764 // This use case currently comes up primarily for targets that
765 // require LTO so the request for LTO is always unconditionally
766 // passed down to the backend, but we don't actually want to do
767 // anything about it yet until we've got a final product.
768 let is_rlib = cgcx.crate_types.len() == 1
769 && cgcx.crate_types[0] == config::CrateType::Rlib;
771 // Metadata modules never participate in LTO regardless of the lto
773 let lto_type = if module.kind == ModuleKind::Metadata {
777 Lto::ThinLocal if !linker_does_lto && !is_allocator
778 => ComputedLtoType::Thin,
779 Lto::Thin if !linker_does_lto && !is_rlib
780 => ComputedLtoType::Thin,
781 Lto::Fat if !is_rlib => ComputedLtoType::Fat,
782 _ => ComputedLtoType::No,
786 // If we're doing some form of incremental LTO then we need to be sure to
787 // save our module to disk first.
788 let bitcode = if cgcx.config(module.kind).emit_pre_lto_bc {
789 let filename = pre_lto_bitcode_filename(&module.name);
790 cgcx.incr_comp_session_dir.as_ref().map(|path| path.join(&filename))
796 ComputedLtoType::No => {
797 let module = unsafe {
798 B::codegen(cgcx, &diag_handler, module, module_config, timeline)?
800 WorkItemResult::Compiled(module)
802 ComputedLtoType::Thin => {
803 let (name, thin_buffer) = B::prepare_thin(module);
804 if let Some(path) = bitcode {
805 fs::write(&path, thin_buffer.data()).unwrap_or_else(|e| {
806 panic!("Error writing pre-lto-bitcode file `{}`: {}",
811 WorkItemResult::NeedsThinLTO(name, thin_buffer)
813 ComputedLtoType::Fat => {
816 let (name, buffer) = B::serialize_module(module);
817 fs::write(&path, buffer.data()).unwrap_or_else(|e| {
818 panic!("Error writing pre-lto-bitcode file `{}`: {}",
822 WorkItemResult::NeedsFatLTO(FatLTOInput::Serialized { name, buffer })
824 None => WorkItemResult::NeedsFatLTO(FatLTOInput::InMemory(module)),
830 fn execute_copy_from_cache_work_item<B: ExtraBackendMethods>(
831 cgcx: &CodegenContext<B>,
832 module: CachedModuleCodegen,
833 module_config: &ModuleConfig,
835 ) -> Result<WorkItemResult<B>, FatalError> {
836 let incr_comp_session_dir = cgcx.incr_comp_session_dir
839 let mut object = None;
840 let mut bytecode = None;
841 let mut bytecode_compressed = None;
842 for (kind, saved_file) in &module.source.saved_files {
843 let obj_out = match kind {
844 WorkProductFileKind::Object => {
845 let path = cgcx.output_filenames.temp_path(OutputType::Object,
847 object = Some(path.clone());
850 WorkProductFileKind::Bytecode => {
851 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode,
853 bytecode = Some(path.clone());
856 WorkProductFileKind::BytecodeCompressed => {
857 let path = cgcx.output_filenames.temp_path(OutputType::Bitcode,
859 .with_extension(RLIB_BYTECODE_EXTENSION);
860 bytecode_compressed = Some(path.clone());
864 let source_file = in_incr_comp_dir(&incr_comp_session_dir,
866 debug!("copying pre-existing module `{}` from {:?} to {}",
870 if let Err(err) = link_or_copy(&source_file, &obj_out) {
871 let diag_handler = cgcx.create_diag_handler();
872 diag_handler.err(&format!("unable to copy {} to {}: {}",
873 source_file.display(),
879 assert_eq!(object.is_some(), module_config.emit_obj);
880 assert_eq!(bytecode.is_some(), module_config.emit_bc);
881 assert_eq!(bytecode_compressed.is_some(), module_config.emit_bc_compressed);
883 Ok(WorkItemResult::Compiled(CompiledModule {
885 kind: ModuleKind::Regular,
892 fn execute_lto_work_item<B: ExtraBackendMethods>(
893 cgcx: &CodegenContext<B>,
894 mut module: lto::LtoModuleCodegen<B>,
895 module_config: &ModuleConfig,
896 timeline: &mut Timeline
897 ) -> Result<WorkItemResult<B>, FatalError> {
898 let diag_handler = cgcx.create_diag_handler();
901 let module = module.optimize(cgcx, timeline)?;
902 let module = B::codegen(cgcx, &diag_handler, module, module_config, timeline)?;
903 Ok(WorkItemResult::Compiled(module))
907 pub enum Message<B: WriteBackendMethods> {
908 Token(io::Result<Acquired>),
910 result: FatLTOInput<B>,
915 thin_buffer: B::ThinBuffer,
919 result: Result<CompiledModule, ()>,
923 llvm_work_item: WorkItem<B>,
926 AddImportOnlyModule {
927 module_data: SerializedModule<B::ModuleBuffer>,
928 work_product: WorkProduct,
937 code: Option<DiagnosticId>,
941 #[derive(PartialEq, Clone, Copy, Debug)]
942 enum MainThreadWorkerState {
948 fn start_executing_work<B: ExtraBackendMethods>(
951 crate_info: &CrateInfo,
952 shared_emitter: SharedEmitter,
953 codegen_worker_send: Sender<Message<B>>,
954 coordinator_receive: Receiver<Box<dyn Any + Send>>,
957 time_graph: Option<TimeGraph>,
958 modules_config: Arc<ModuleConfig>,
959 metadata_config: Arc<ModuleConfig>,
960 allocator_config: Arc<ModuleConfig>
961 ) -> thread::JoinHandle<Result<CompiledModules, ()>> {
962 let coordinator_send = tcx.tx_to_llvm_workers.lock().clone();
965 // Compute the set of symbols we need to retain when doing LTO (if we need to)
966 let exported_symbols = {
967 let mut exported_symbols = FxHashMap::default();
969 let copy_symbols = |cnum| {
970 let symbols = tcx.exported_symbols(cnum)
972 .map(|&(s, lvl)| (s.symbol_name(tcx).to_string(), lvl))
980 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
981 Some(Arc::new(exported_symbols))
983 Lto::Fat | Lto::Thin => {
984 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
985 for &cnum in tcx.crates().iter() {
986 exported_symbols.insert(cnum, copy_symbols(cnum));
988 Some(Arc::new(exported_symbols))
993 // First up, convert our jobserver into a helper thread so we can use normal
994 // mpsc channels to manage our messages and such.
995 // After we've requested tokens then we'll, when we can,
996 // get tokens on `coordinator_receive` which will
997 // get managed in the main loop below.
998 let coordinator_send2 = coordinator_send.clone();
999 let helper = jobserver.into_helper_thread(move |token| {
1000 drop(coordinator_send2.send(Box::new(Message::Token::<B>(token))));
1001 }).expect("failed to spawn helper thread");
1003 let mut each_linked_rlib_for_lto = Vec::new();
1004 drop(link::each_linked_rlib(sess, crate_info, &mut |cnum, path| {
1005 if link::ignored_for_lto(sess, crate_info, cnum) {
1008 each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
1011 let assembler_cmd = if modules_config.no_integrated_as {
1012 // HACK: currently we use linker (gcc) as our assembler
1013 let (linker, flavor) = link::linker_and_flavor(sess);
1015 let (name, mut cmd) = get_linker(sess, &linker, flavor);
1016 cmd.args(&sess.target.target.options.asm_args);
1017 Some(Arc::new(AssemblerCommand {
1025 let ol = 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_passes(),
1037 plugin_passes: sess.plugin_llvm_passes.borrow().clone(),
1038 remark: sess.opts.cg.remark.clone(),
1040 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1041 cgu_reuse_tracker: sess.cgu_reuse_tracker.clone(),
1043 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 debuginfo: tcx.sess.opts.debuginfo,
1057 // This is the "main loop" of parallel work happening for parallel codegen.
1058 // It's here that we manage parallelism, schedule work, and work with
1059 // messages coming from clients.
1061 // There are a few environmental pre-conditions that shape how the system
1064 // - Error reporting only can happen on the main thread because that's the
1065 // only place where we have access to the compiler `Session`.
1066 // - LLVM work can be done on any thread.
1067 // - Codegen can only happen on the main thread.
1068 // - Each thread doing substantial work most be in possession of a `Token`
1069 // from the `Jobserver`.
1070 // - The compiler process always holds one `Token`. Any additional `Tokens`
1071 // have to be requested from the `Jobserver`.
1075 // The error reporting restriction is handled separately from the rest: We
1076 // set up a `SharedEmitter` the holds an open channel to the main thread.
1077 // When an error occurs on any thread, the shared emitter will send the
1078 // error message to the receiver main thread (`SharedEmitterMain`). The
1079 // main thread will periodically query this error message queue and emit
1080 // any error messages it has received. It might even abort compilation if
1081 // has received a fatal error. In this case we rely on all other threads
1082 // being torn down automatically with the main thread.
1083 // Since the main thread will often be busy doing codegen work, error
1084 // reporting will be somewhat delayed, since the message queue can only be
1085 // checked in between to work packages.
1087 // Work Processing Infrastructure
1088 // ==============================
1089 // The work processing infrastructure knows three major actors:
1091 // - the coordinator thread,
1092 // - the main thread, and
1093 // - LLVM worker threads
1095 // The coordinator thread is running a message loop. It instructs the main
1096 // thread about what work to do when, and it will spawn off LLVM worker
1097 // threads as open LLVM WorkItems become available.
1099 // The job of the main thread is to codegen CGUs into LLVM work package
1100 // (since the main thread is the only thread that can do this). The main
1101 // thread will block until it receives a message from the coordinator, upon
1102 // which it will codegen one CGU, send it to the coordinator and block
1103 // again. This way the coordinator can control what the main thread is
1106 // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1107 // available, it will spawn off a new LLVM worker thread and let it process
1108 // that a WorkItem. When a LLVM worker thread is done with its WorkItem,
1109 // it will just shut down, which also frees all resources associated with
1110 // the given LLVM module, and sends a message to the coordinator that the
1111 // has been completed.
1115 // The scheduler's goal is to minimize the time it takes to complete all
1116 // work there is, however, we also want to keep memory consumption low
1117 // if possible. These two goals are at odds with each other: If memory
1118 // consumption were not an issue, we could just let the main thread produce
1119 // LLVM WorkItems at full speed, assuring maximal utilization of
1120 // Tokens/LLVM worker threads. However, since codegen usual is faster
1121 // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1122 // WorkItem potentially holds on to a substantial amount of memory.
1124 // So the actual goal is to always produce just enough LLVM WorkItems as
1125 // not to starve our LLVM worker threads. That means, once we have enough
1126 // WorkItems in our queue, we can block the main thread, so it does not
1127 // produce more until we need them.
1129 // Doing LLVM Work on the Main Thread
1130 // ----------------------------------
1131 // Since the main thread owns the compiler processes implicit `Token`, it is
1132 // wasteful to keep it blocked without doing any work. Therefore, what we do
1133 // in this case is: We spawn off an additional LLVM worker thread that helps
1134 // reduce the queue. The work it is doing corresponds to the implicit
1135 // `Token`. The coordinator will mark the main thread as being busy with
1136 // LLVM work. (The actual work happens on another OS thread but we just care
1137 // about `Tokens`, not actual threads).
1139 // When any LLVM worker thread finishes while the main thread is marked as
1140 // "busy with LLVM work", we can do a little switcheroo: We give the Token
1141 // of the just finished thread to the LLVM worker thread that is working on
1142 // behalf of the main thread's implicit Token, thus freeing up the main
1143 // thread again. The coordinator can then again decide what the main thread
1144 // should do. This allows the coordinator to make decisions at more points
1147 // Striking a Balance between Throughput and Memory Consumption
1148 // ------------------------------------------------------------
1149 // Since our two goals, (1) use as many Tokens as possible and (2) keep
1150 // memory consumption as low as possible, are in conflict with each other,
1151 // we have to find a trade off between them. Right now, the goal is to keep
1152 // all workers busy, which means that no worker should find the queue empty
1153 // when it is ready to start.
1154 // How do we do achieve this? Good question :) We actually never know how
1155 // many `Tokens` are potentially available so it's hard to say how much to
1156 // fill up the queue before switching the main thread to LLVM work. Also we
1157 // currently don't have a means to estimate how long a running LLVM worker
1158 // will still be busy with it's current WorkItem. However, we know the
1159 // maximal count of available Tokens that makes sense (=the number of CPU
1160 // cores), so we can take a conservative guess. The heuristic we use here
1161 // is implemented in the `queue_full_enough()` function.
1163 // Some Background on Jobservers
1164 // -----------------------------
1165 // It's worth also touching on the management of parallelism here. We don't
1166 // want to just spawn a thread per work item because while that's optimal
1167 // parallelism it may overload a system with too many threads or violate our
1168 // configuration for the maximum amount of cpu to use for this process. To
1169 // manage this we use the `jobserver` crate.
1171 // Job servers are an artifact of GNU make and are used to manage
1172 // parallelism between processes. A jobserver is a glorified IPC semaphore
1173 // basically. Whenever we want to run some work we acquire the semaphore,
1174 // and whenever we're done with that work we release the semaphore. In this
1175 // manner we can ensure that the maximum number of parallel workers is
1176 // capped at any one point in time.
1178 // LTO and the coordinator thread
1179 // ------------------------------
1181 // The final job the coordinator thread is responsible for is managing LTO
1182 // and how that works. When LTO is requested what we'll to is collect all
1183 // optimized LLVM modules into a local vector on the coordinator. Once all
1184 // modules have been codegened and optimized we hand this to the `lto`
1185 // module for further optimization. The `lto` module will return back a list
1186 // of more modules to work on, which the coordinator will continue to spawn
1189 // Each LLVM module is automatically sent back to the coordinator for LTO if
1190 // necessary. There's already optimizations in place to avoid sending work
1191 // back to the coordinator if LTO isn't requested.
1192 return thread::spawn(move || {
1193 // We pretend to be within the top-level LLVM time-passes task here:
1196 let max_workers = ::num_cpus::get();
1197 let mut worker_id_counter = 0;
1198 let mut free_worker_ids = Vec::new();
1199 let mut get_worker_id = |free_worker_ids: &mut Vec<usize>| {
1200 if let Some(id) = free_worker_ids.pop() {
1203 let id = worker_id_counter;
1204 worker_id_counter += 1;
1209 // This is where we collect codegen units that have gone all the way
1210 // through codegen and LLVM.
1211 let mut compiled_modules = vec![];
1212 let mut compiled_metadata_module = None;
1213 let mut compiled_allocator_module = None;
1214 let mut needs_fat_lto = Vec::new();
1215 let mut needs_thin_lto = Vec::new();
1216 let mut lto_import_only_modules = Vec::new();
1217 let mut started_lto = false;
1218 let mut codegen_aborted = false;
1220 // This flag tracks whether all items have gone through codegens
1221 let mut codegen_done = false;
1223 // This is the queue of LLVM work items that still need processing.
1224 let mut work_items = Vec::<(WorkItem<B>, u64)>::new();
1226 // This are the Jobserver Tokens we currently hold. Does not include
1227 // the implicit Token the compiler process owns no matter what.
1228 let mut tokens = Vec::new();
1230 let mut main_thread_worker_state = MainThreadWorkerState::Idle;
1231 let mut running = 0;
1233 let mut llvm_start_time = None;
1235 // Run the message loop while there's still anything that needs message
1236 // processing. Note that as soon as codegen is aborted we simply want to
1237 // wait for all existing work to finish, so many of the conditions here
1238 // only apply if codegen hasn't been aborted as they represent pending
1240 while !codegen_done ||
1242 (!codegen_aborted && (
1243 work_items.len() > 0 ||
1244 needs_fat_lto.len() > 0 ||
1245 needs_thin_lto.len() > 0 ||
1246 lto_import_only_modules.len() > 0 ||
1247 main_thread_worker_state != MainThreadWorkerState::Idle
1251 // While there are still CGUs to be codegened, the coordinator has
1252 // to decide how to utilize the compiler processes implicit Token:
1253 // For codegenning more CGU or for running them through LLVM.
1255 if main_thread_worker_state == MainThreadWorkerState::Idle {
1256 if !queue_full_enough(work_items.len(), running, max_workers) {
1257 // The queue is not full enough, codegen more items:
1258 if let Err(_) = codegen_worker_send.send(Message::CodegenItem) {
1259 panic!("Could not send Message::CodegenItem to main thread")
1261 main_thread_worker_state = MainThreadWorkerState::Codegenning;
1263 // The queue is full enough to not let the worker
1264 // threads starve. Use the implicit Token to do some
1266 let (item, _) = work_items.pop()
1267 .expect("queue empty - queue_full_enough() broken?");
1268 let cgcx = CodegenContext {
1269 worker: get_worker_id(&mut free_worker_ids),
1272 maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1273 &mut llvm_start_time);
1274 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1275 spawn_work(cgcx, item);
1278 } else if codegen_aborted {
1279 // don't queue up any more work if codegen was aborted, we're
1280 // just waiting for our existing children to finish
1282 // If we've finished everything related to normal codegen
1283 // then it must be the case that we've got some LTO work to do.
1284 // Perform the serial work here of figuring out what we're
1285 // going to LTO and then push a bunch of work items onto our
1287 if work_items.len() == 0 &&
1289 main_thread_worker_state == MainThreadWorkerState::Idle {
1290 assert!(!started_lto);
1294 mem::replace(&mut needs_fat_lto, Vec::new());
1295 let needs_thin_lto =
1296 mem::replace(&mut needs_thin_lto, Vec::new());
1297 let import_only_modules =
1298 mem::replace(&mut lto_import_only_modules, Vec::new());
1300 for (work, cost) in generate_lto_work(&cgcx, needs_fat_lto,
1301 needs_thin_lto, import_only_modules) {
1302 let insertion_index = work_items
1303 .binary_search_by_key(&cost, |&(_, cost)| cost)
1304 .unwrap_or_else(|e| e);
1305 work_items.insert(insertion_index, (work, cost));
1306 if !cgcx.opts.debugging_opts.no_parallel_llvm {
1307 helper.request_token();
1312 // In this branch, we know that everything has been codegened,
1313 // so it's just a matter of determining whether the implicit
1314 // Token is free to use for LLVM work.
1315 match main_thread_worker_state {
1316 MainThreadWorkerState::Idle => {
1317 if let Some((item, _)) = work_items.pop() {
1318 let cgcx = CodegenContext {
1319 worker: get_worker_id(&mut free_worker_ids),
1322 maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1323 &mut llvm_start_time);
1324 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1325 spawn_work(cgcx, item);
1327 // There is no unstarted work, so let the main thread
1328 // take over for a running worker. Otherwise the
1329 // implicit token would just go to waste.
1330 // We reduce the `running` counter by one. The
1331 // `tokens.truncate()` below will take care of
1332 // giving the Token back.
1333 debug_assert!(running > 0);
1335 main_thread_worker_state = MainThreadWorkerState::LLVMing;
1338 MainThreadWorkerState::Codegenning => {
1339 bug!("codegen worker should not be codegenning after \
1340 codegen was already completed")
1342 MainThreadWorkerState::LLVMing => {
1343 // Already making good use of that token
1348 // Spin up what work we can, only doing this while we've got available
1349 // parallelism slots and work left to spawn.
1350 while !codegen_aborted && work_items.len() > 0 && running < tokens.len() {
1351 let (item, _) = work_items.pop().unwrap();
1353 maybe_start_llvm_timer(cgcx.config(item.module_kind()),
1354 &mut llvm_start_time);
1356 let cgcx = CodegenContext {
1357 worker: get_worker_id(&mut free_worker_ids),
1361 spawn_work(cgcx, item);
1365 // Relinquish accidentally acquired extra tokens
1366 tokens.truncate(running);
1368 // If a thread exits successfully then we drop a token associated
1369 // with that worker and update our `running` count. We may later
1370 // re-acquire a token to continue running more work. We may also not
1371 // actually drop a token here if the worker was running with an
1372 // "ephemeral token"
1373 let mut free_worker = |worker_id| {
1374 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1375 main_thread_worker_state = MainThreadWorkerState::Idle;
1380 free_worker_ids.push(worker_id);
1383 let msg = coordinator_receive.recv().unwrap();
1384 match *msg.downcast::<Message<B>>().ok().unwrap() {
1385 // Save the token locally and the next turn of the loop will use
1386 // this to spawn a new unit of work, or it may get dropped
1387 // immediately if we have no more work to spawn.
1388 Message::Token(token) => {
1393 if main_thread_worker_state == MainThreadWorkerState::LLVMing {
1394 // If the main thread token is used for LLVM work
1395 // at the moment, we turn that thread into a regular
1396 // LLVM worker thread, so the main thread is free
1397 // to react to codegen demand.
1398 main_thread_worker_state = MainThreadWorkerState::Idle;
1403 let msg = &format!("failed to acquire jobserver token: {}", e);
1404 shared_emitter.fatal(msg);
1405 // Exit the coordinator thread
1411 Message::CodegenDone { llvm_work_item, cost } => {
1412 // We keep the queue sorted by estimated processing cost,
1413 // so that more expensive items are processed earlier. This
1414 // is good for throughput as it gives the main thread more
1415 // time to fill up the queue and it avoids scheduling
1416 // expensive items to the end.
1417 // Note, however, that this is not ideal for memory
1418 // consumption, as LLVM module sizes are not evenly
1420 let insertion_index =
1421 work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1422 let insertion_index = match insertion_index {
1423 Ok(idx) | Err(idx) => idx
1425 work_items.insert(insertion_index, (llvm_work_item, cost));
1427 if !cgcx.opts.debugging_opts.no_parallel_llvm {
1428 helper.request_token();
1430 assert!(!codegen_aborted);
1431 assert_eq!(main_thread_worker_state,
1432 MainThreadWorkerState::Codegenning);
1433 main_thread_worker_state = MainThreadWorkerState::Idle;
1436 Message::CodegenComplete => {
1437 codegen_done = true;
1438 assert!(!codegen_aborted);
1439 assert_eq!(main_thread_worker_state,
1440 MainThreadWorkerState::Codegenning);
1441 main_thread_worker_state = MainThreadWorkerState::Idle;
1444 // If codegen is aborted that means translation was aborted due
1445 // to some normal-ish compiler error. In this situation we want
1446 // to exit as soon as possible, but we want to make sure all
1447 // existing work has finished. Flag codegen as being done, and
1448 // then conditions above will ensure no more work is spawned but
1449 // we'll keep executing this loop until `running` hits 0.
1450 Message::CodegenAborted => {
1451 assert!(!codegen_aborted);
1452 codegen_done = true;
1453 codegen_aborted = true;
1454 assert_eq!(main_thread_worker_state,
1455 MainThreadWorkerState::Codegenning);
1457 Message::Done { result: Ok(compiled_module), worker_id } => {
1458 free_worker(worker_id);
1459 match compiled_module.kind {
1460 ModuleKind::Regular => {
1461 compiled_modules.push(compiled_module);
1463 ModuleKind::Metadata => {
1464 assert!(compiled_metadata_module.is_none());
1465 compiled_metadata_module = Some(compiled_module);
1467 ModuleKind::Allocator => {
1468 assert!(compiled_allocator_module.is_none());
1469 compiled_allocator_module = Some(compiled_module);
1473 Message::NeedsFatLTO { result, worker_id } => {
1474 assert!(!started_lto);
1475 free_worker(worker_id);
1476 needs_fat_lto.push(result);
1478 Message::NeedsThinLTO { name, thin_buffer, worker_id } => {
1479 assert!(!started_lto);
1480 free_worker(worker_id);
1481 needs_thin_lto.push((name, thin_buffer));
1483 Message::AddImportOnlyModule { module_data, work_product } => {
1484 assert!(!started_lto);
1485 assert!(!codegen_done);
1486 assert_eq!(main_thread_worker_state,
1487 MainThreadWorkerState::Codegenning);
1488 lto_import_only_modules.push((module_data, work_product));
1489 main_thread_worker_state = MainThreadWorkerState::Idle;
1491 // If the thread failed that means it panicked, so we abort immediately.
1492 Message::Done { result: Err(()), worker_id: _ } => {
1493 bug!("worker thread panicked");
1495 Message::CodegenItem => {
1496 bug!("the coordinator should not receive codegen requests")
1501 if let Some(llvm_start_time) = llvm_start_time {
1502 let total_llvm_time = Instant::now().duration_since(llvm_start_time);
1503 // This is the top-level timing for all of LLVM, set the time-depth
1506 print_time_passes_entry(cgcx.time_passes,
1511 // Regardless of what order these modules completed in, report them to
1512 // the backend in the same order every time to ensure that we're handing
1513 // out deterministic results.
1514 compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
1516 let compiled_metadata_module = compiled_metadata_module
1517 .expect("Metadata module not compiled?");
1519 Ok(CompiledModules {
1520 modules: compiled_modules,
1521 metadata_module: compiled_metadata_module,
1522 allocator_module: compiled_allocator_module,
1526 // A heuristic that determines if we have enough LLVM WorkItems in the
1527 // queue so that the main thread can do LLVM work instead of codegen
1528 fn queue_full_enough(items_in_queue: usize,
1529 workers_running: usize,
1530 max_workers: usize) -> bool {
1532 items_in_queue > 0 &&
1533 items_in_queue >= max_workers.saturating_sub(workers_running / 2)
1536 fn maybe_start_llvm_timer(config: &ModuleConfig,
1537 llvm_start_time: &mut Option<Instant>) {
1538 // We keep track of the -Ztime-passes output manually,
1539 // since the closure-based interface does not fit well here.
1540 if config.time_passes {
1541 if llvm_start_time.is_none() {
1542 *llvm_start_time = Some(Instant::now());
1548 pub const CODEGEN_WORKER_ID: usize = ::std::usize::MAX;
1549 pub const CODEGEN_WORKER_TIMELINE: time_graph::TimelineId =
1550 time_graph::TimelineId(CODEGEN_WORKER_ID);
1551 pub const CODEGEN_WORK_PACKAGE_KIND: time_graph::WorkPackageKind =
1552 time_graph::WorkPackageKind(&["#DE9597", "#FED1D3", "#FDC5C7", "#B46668", "#88494B"]);
1553 const LLVM_WORK_PACKAGE_KIND: time_graph::WorkPackageKind =
1554 time_graph::WorkPackageKind(&["#7DB67A", "#C6EEC4", "#ACDAAA", "#579354", "#3E6F3C"]);
1556 fn spawn_work<B: ExtraBackendMethods>(
1557 cgcx: CodegenContext<B>,
1560 let depth = time_depth();
1562 thread::spawn(move || {
1563 set_time_depth(depth);
1565 // Set up a destructor which will fire off a message that we're done as
1567 struct Bomb<B: ExtraBackendMethods> {
1568 coordinator_send: Sender<Box<dyn Any + Send>>,
1569 result: Option<WorkItemResult<B>>,
1572 impl<B: ExtraBackendMethods> Drop for Bomb<B> {
1573 fn drop(&mut self) {
1574 let worker_id = self.worker_id;
1575 let msg = match self.result.take() {
1576 Some(WorkItemResult::Compiled(m)) => {
1577 Message::Done::<B> { result: Ok(m), worker_id }
1579 Some(WorkItemResult::NeedsFatLTO(m)) => {
1580 Message::NeedsFatLTO::<B> { result: m, worker_id }
1582 Some(WorkItemResult::NeedsThinLTO(name, thin_buffer)) => {
1583 Message::NeedsThinLTO::<B> { name, thin_buffer, worker_id }
1585 None => Message::Done::<B> { result: Err(()), worker_id }
1587 drop(self.coordinator_send.send(Box::new(msg)));
1591 let mut bomb = Bomb::<B> {
1592 coordinator_send: cgcx.coordinator_send.clone(),
1594 worker_id: cgcx.worker,
1597 // Execute the work itself, and if it finishes successfully then flag
1598 // ourselves as a success as well.
1600 // Note that we ignore any `FatalError` coming out of `execute_work_item`,
1601 // as a diagnostic was already sent off to the main thread - just
1602 // surface that there was an error in this worker.
1604 let timeline = cgcx.time_graph.as_ref().map(|tg| {
1605 tg.start(time_graph::TimelineId(cgcx.worker),
1606 LLVM_WORK_PACKAGE_KIND,
1609 let mut timeline = timeline.unwrap_or(Timeline::noop());
1610 execute_work_item(&cgcx, work, &mut timeline).ok()
1615 pub fn run_assembler<B: ExtraBackendMethods>(
1616 cgcx: &CodegenContext<B>,
1621 let assembler = cgcx.assembler_cmd
1623 .expect("cgcx.assembler_cmd is missing?");
1625 let pname = &assembler.name;
1626 let mut cmd = assembler.cmd.clone();
1627 cmd.arg("-c").arg("-o").arg(object).arg(assembly);
1628 debug!("{:?}", cmd);
1630 match cmd.output() {
1632 if !prog.status.success() {
1633 let mut note = prog.stderr.clone();
1634 note.extend_from_slice(&prog.stdout);
1636 handler.struct_err(&format!("linking with `{}` failed: {}",
1639 .note(&format!("{:?}", &cmd))
1640 .note(str::from_utf8(¬e[..]).unwrap())
1642 handler.abort_if_errors();
1646 handler.err(&format!("could not exec the linker `{}`: {}", pname.display(), e));
1647 handler.abort_if_errors();
1653 enum SharedEmitterMessage {
1654 Diagnostic(Diagnostic),
1655 InlineAsmError(u32, String),
1661 pub struct SharedEmitter {
1662 sender: Sender<SharedEmitterMessage>,
1665 pub struct SharedEmitterMain {
1666 receiver: Receiver<SharedEmitterMessage>,
1669 impl SharedEmitter {
1670 pub fn new() -> (SharedEmitter, SharedEmitterMain) {
1671 let (sender, receiver) = channel();
1673 (SharedEmitter { sender }, SharedEmitterMain { receiver })
1676 pub fn inline_asm_error(&self, cookie: u32, msg: String) {
1677 drop(self.sender.send(SharedEmitterMessage::InlineAsmError(cookie, msg)));
1680 pub fn fatal(&self, msg: &str) {
1681 drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1685 impl Emitter for SharedEmitter {
1686 fn emit(&mut self, db: &DiagnosticBuilder) {
1687 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1689 code: db.code.clone(),
1692 for child in &db.children {
1693 drop(self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1694 msg: child.message(),
1699 drop(self.sender.send(SharedEmitterMessage::AbortIfErrors));
1703 impl SharedEmitterMain {
1704 pub fn check(&self, sess: &Session, blocking: bool) {
1706 let message = if blocking {
1707 match self.receiver.recv() {
1708 Ok(message) => Ok(message),
1712 match self.receiver.try_recv() {
1713 Ok(message) => Ok(message),
1719 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
1720 let handler = sess.diagnostic();
1723 handler.emit_with_code(&MultiSpan::new(),
1729 handler.emit(&MultiSpan::new(),
1735 Ok(SharedEmitterMessage::InlineAsmError(cookie, msg)) => {
1736 match Mark::from_u32(cookie).expn_info() {
1737 Some(ei) => sess.span_err(ei.call_site, &msg),
1738 None => sess.err(&msg),
1741 Ok(SharedEmitterMessage::AbortIfErrors) => {
1742 sess.abort_if_errors();
1744 Ok(SharedEmitterMessage::Fatal(msg)) => {
1756 pub struct OngoingCodegen<B: ExtraBackendMethods> {
1758 pub crate_name: Symbol,
1759 pub crate_hash: Svh,
1760 pub metadata: EncodedMetadata,
1761 pub windows_subsystem: Option<String>,
1762 pub linker_info: LinkerInfo,
1763 pub crate_info: CrateInfo,
1764 pub time_graph: Option<TimeGraph>,
1765 pub coordinator_send: Sender<Box<dyn Any + Send>>,
1766 pub codegen_worker_receive: Receiver<Message<B>>,
1767 pub shared_emitter_main: SharedEmitterMain,
1768 pub future: thread::JoinHandle<Result<CompiledModules, ()>>,
1769 pub output_filenames: Arc<OutputFilenames>,
1772 impl<B: ExtraBackendMethods> OngoingCodegen<B> {
1776 ) -> (CodegenResults, FxHashMap<WorkProductId, WorkProduct>) {
1777 self.shared_emitter_main.check(sess, true);
1778 let compiled_modules = match self.future.join() {
1779 Ok(Ok(compiled_modules)) => compiled_modules,
1781 sess.abort_if_errors();
1782 panic!("expected abort due to worker thread errors")
1785 bug!("panic during codegen/LLVM phase");
1789 sess.cgu_reuse_tracker.check_expected_reuse(sess);
1791 sess.abort_if_errors();
1793 if let Some(time_graph) = self.time_graph {
1794 time_graph.dump(&format!("{}-timings", self.crate_name));
1798 copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess,
1800 produce_final_output_artifacts(sess,
1802 &self.output_filenames);
1804 // FIXME: time_llvm_passes support - does this use a global context or
1806 if sess.codegen_units() == 1 && sess.time_llvm_passes() {
1807 self.backend.print_pass_timings()
1811 crate_name: self.crate_name,
1812 crate_hash: self.crate_hash,
1813 metadata: self.metadata,
1814 windows_subsystem: self.windows_subsystem,
1815 linker_info: self.linker_info,
1816 crate_info: self.crate_info,
1818 modules: compiled_modules.modules,
1819 allocator_module: compiled_modules.allocator_module,
1820 metadata_module: compiled_modules.metadata_module,
1824 pub fn submit_pre_codegened_module_to_llvm(&self,
1826 module: ModuleCodegen<B::Module>) {
1827 self.wait_for_signal_to_codegen_item();
1828 self.check_for_errors(tcx.sess);
1830 // These are generally cheap and won't through off scheduling.
1832 submit_codegened_module_to_llvm(&self.backend, tcx, module, cost);
1835 pub fn codegen_finished(&self, tcx: TyCtxt) {
1836 self.wait_for_signal_to_codegen_item();
1837 self.check_for_errors(tcx.sess);
1838 drop(self.coordinator_send.send(Box::new(Message::CodegenComplete::<B>)));
1841 /// Consumes this context indicating that codegen was entirely aborted, and
1842 /// we need to exit as quickly as possible.
1844 /// This method blocks the current thread until all worker threads have
1845 /// finished, and all worker threads should have exited or be real close to
1846 /// exiting at this point.
1847 pub fn codegen_aborted(self) {
1848 // Signal to the coordinator it should spawn no more work and start
1850 drop(self.coordinator_send.send(Box::new(Message::CodegenAborted::<B>)));
1851 drop(self.future.join());
1854 pub fn check_for_errors(&self, sess: &Session) {
1855 self.shared_emitter_main.check(sess, false);
1858 pub fn wait_for_signal_to_codegen_item(&self) {
1859 match self.codegen_worker_receive.recv() {
1860 Ok(Message::CodegenItem) => {
1863 Ok(_) => panic!("unexpected message"),
1865 // One of the LLVM threads must have panicked, fall through so
1866 // error handling can be reached.
1872 pub fn submit_codegened_module_to_llvm<B: ExtraBackendMethods>(
1875 module: ModuleCodegen<B::Module>,
1878 let llvm_work_item = WorkItem::Optimize(module);
1879 drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::CodegenDone::<B> {
1885 pub fn submit_post_lto_module_to_llvm<B: ExtraBackendMethods>(
1888 module: CachedModuleCodegen
1890 let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
1891 drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::CodegenDone::<B> {
1897 pub fn submit_pre_lto_module_to_llvm<B: ExtraBackendMethods>(
1900 module: CachedModuleCodegen
1902 let filename = pre_lto_bitcode_filename(&module.name);
1903 let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
1904 let file = fs::File::open(&bc_path).unwrap_or_else(|e| {
1905 panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e)
1909 memmap::Mmap::map(&file).unwrap_or_else(|e| {
1910 panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
1913 // Schedule the module to be loaded
1914 drop(tcx.tx_to_llvm_workers.lock().send(Box::new(Message::AddImportOnlyModule::<B> {
1915 module_data: SerializedModule::FromUncompressedFile(mmap),
1916 work_product: module.source,
1920 pub fn pre_lto_bitcode_filename(module_name: &str) -> String {
1921 format!("{}.{}", module_name, PRE_LTO_BC_EXT)
1924 fn msvc_imps_needed(tcx: TyCtxt) -> bool {
1925 // This should never be true (because it's not supported). If it is true,
1926 // something is wrong with commandline arg validation.
1927 assert!(!(tcx.sess.opts.cg.linker_plugin_lto.enabled() &&
1928 tcx.sess.target.target.options.is_like_msvc &&
1929 tcx.sess.opts.cg.prefer_dynamic));
1931 tcx.sess.target.target.options.is_like_msvc &&
1932 tcx.sess.crate_types.borrow().iter().any(|ct| *ct == config::CrateType::Rlib) &&
1933 // ThinLTO can't handle this workaround in all cases, so we don't
1934 // emit the `__imp_` symbols. Instead we make them unnecessary by disallowing
1935 // dynamic linking when linker plugin LTO is enabled.
1936 !tcx.sess.opts.cg.linker_plugin_lto.enabled()