diff --git a/Cargo.lock b/Cargo.lock index f8f3dfce90c4e..479d2d833dd6b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3836,6 +3836,7 @@ dependencies = [ "rustc_structures", "rustc_symbol_mangling", "rustc_target", + "rustc_thread_pool", "rustc_trait_selection", "serde_json", "smallvec", diff --git a/compiler/rustc_codegen_ssa/Cargo.toml b/compiler/rustc_codegen_ssa/Cargo.toml index 188bd29cc6042..4f19b9b58f800 100644 --- a/compiler/rustc_codegen_ssa/Cargo.toml +++ b/compiler/rustc_codegen_ssa/Cargo.toml @@ -1,7 +1,7 @@ [package] +edition = "2024" name = "rustc_codegen_ssa" version = "0.0.0" -edition = "2024" [dependencies] # tidy-alphabetical-start @@ -35,6 +35,7 @@ rustc_span = { path = "../rustc_span" } rustc_structures = { path = "../rustc_structures" } rustc_symbol_mangling = { path = "../rustc_symbol_mangling" } rustc_target = { path = "../rustc_target" } +rustc_thread_pool = { path = "../rustc_thread_pool" } rustc_trait_selection = { path = "../rustc_trait_selection" } serde_json = "1.0.59" smallvec = { version = "1.8.1", features = ["union", "may_dangle"] } @@ -50,10 +51,20 @@ libc = "0.2.50" # tidy-alphabetical-end [dependencies.object] -version = "0.39.1" default-features = false -features = ["read_core", "elf", "macho", "pe", "xcoff", "unaligned", "archive", "write", "wasm"] +features = [ + "read_core", + "elf", + "macho", + "pe", + "xcoff", + "unaligned", + "archive", + "write", + "wasm", +] +version = "0.39.1" [target.'cfg(windows)'.dependencies.windows] -version = "0.61.0" features = ["Win32_Globalization"] +version = "0.61.0" diff --git a/compiler/rustc_codegen_ssa/src/back/write.rs b/compiler/rustc_codegen_ssa/src/back/write.rs index 24fcab7218f7e..6bbc16cb2a1bb 100644 --- a/compiler/rustc_codegen_ssa/src/back/write.rs +++ b/compiler/rustc_codegen_ssa/src/back/write.rs @@ -3,12 +3,13 @@ use std::num::NonZero; use std::panic::AssertUnwindSafe; use std::path::{Path, PathBuf}; use std::sync::Arc; -use std::sync::mpsc::{Receiver, Sender, channel}; +use std::sync::mpmc::{Receiver, Sender, channel}; use std::{assert_matches, fs, io, str, thread}; use rustc_abi::Size; use rustc_data_structures::jobserver::{self, Acquired}; use rustc_data_structures::profiling::{SelfProfilerRef, VerboseTimingGuard}; +use rustc_data_structures::sync::{self, DynSend, DynSync, IntoDynSyncSend}; use rustc_errors::emitter::Emitter; use rustc_errors::{ Diag, DiagCtxt, DiagCtxtHandle, DiagInner, FatalError, FatalErrorMarker, Level, @@ -425,16 +426,65 @@ pub(crate) fn start_async_codegen( let (shared_emitter, shared_emitter_main) = SharedEmitter::new(); let (codegen_worker_send, codegen_worker_receive) = channel(); + let sess = tcx.sess; + let prof = sess.prof.clone(); + let incr_comp_session = + tcx.incr_comp_session.map(|incr_comp_session| incr_comp_session.borrow()); + let stack_size = sess.opts.recommended_stack_size; + + let remark_dir = if let Some(ref dir) = sess.opts.unstable_opts.remark_dir { + let result = fs::create_dir_all(dir).and_then(|_| dir.canonicalize()); + match result { + Ok(dir) => Some(dir), + Err(error) => sess.dcx().emit_fatal(ErrorCreatingRemarkDir { error }), + } + } else { + None + }; + + let parallel = match sess.opts.jobs.backend { + JobsMode::Parallel(n) if backend.supports_parallel() => Some(n), + _ => None, + }; + + let cgcx = CodegenContext { + crate_types: tcx.crate_types().to_vec(), + lto: sess.lto(), + use_linker_plugin_lto: sess.opts.cg.linker_plugin_lto.enabled(), + dylib_lto: sess.opts.unstable_opts.dylib_lto, + prefer_dynamic: sess.opts.cg.prefer_dynamic, + fewer_names: sess.fewer_names(), + save_temps: sess.opts.cg.save_temps, + time_trace: sess.opts.unstable_opts.llvm_time_trace, + remark: sess.opts.cg.remark.clone(), + remark_dir, + output_filenames: Arc::clone(tcx.output_filenames(())), + module_config: regular_config, + msvc_imps_needed: msvc_imps_needed(tcx), + is_pe_coff: tcx.sess.target.is_like_windows, + target_can_use_split_dwarf: tcx.sess.target_can_use_split_dwarf(), + target_arch: tcx.sess.target.arch.to_string(), + target_is_like_darwin: tcx.sess.target.is_like_darwin, + target_is_like_aix: tcx.sess.target.is_like_aix, + target_is_like_gpu: tcx.sess.target.is_like_gpu, + rust_eh_personality_symbol: rustc_symbol_mangling::eh_personality_symbol(tcx), + split_debuginfo: tcx.sess.split_debuginfo(), + split_dwarf_kind: tcx.sess.opts.unstable_opts.split_dwarf_kind, + parallel, + pointer_size: tcx.data_layout.pointer_size(), + }; + + let work_ctx = LlvmWorkContext { cgcx, prof, incr_comp_session, stack_size, shared_emitter }; + let coordinator_thread = start_executing_work( backend.clone(), tcx, - shared_emitter, codegen_worker_send, coordinator_receive, - regular_config, allocator_config, allocator_module, coordinator_send.clone(), + work_ctx.clone(), ); OngoingCodegen { @@ -448,6 +498,7 @@ pub(crate) fn start_async_codegen( phantom: PhantomData, }, output_filenames: Arc::clone(tcx.output_filenames(())), + work_ctx, } } @@ -1204,19 +1255,16 @@ enum MainThreadState { fn start_executing_work( backend: B, tcx: TyCtxt<'_>, - shared_emitter: SharedEmitter, codegen_worker_send: Sender, coordinator_receive: Receiver>, - regular_config: Arc, allocator_config: Arc, mut allocator_module: Option>, coordinator_send: Sender>, + work_ctx: LlvmWorkContext, ) -> thread::JoinHandle, ()>> { let sess = tcx.sess; - let prof = sess.prof.clone(); - let incr_comp_session = - tcx.incr_comp_session.map(|incr_comp_session| incr_comp_session.borrow()); - + let LlvmWorkContext { cgcx, prof, incr_comp_session, stack_size, shared_emitter } = work_ctx; + let parallel = cgcx.parallel; // Compute the set of symbols we need to retain when doing thin local LTO (if we need to) let exported_symbols_for_lto = if sess.lto() == Lto::ThinLocal { lto::exported_symbols_for_lto(tcx, &[]) } else { vec![] }; @@ -1229,10 +1277,7 @@ fn start_executing_work( // Note that using `jobserver::Proxy` is not necessary here, the code below always acquires // tokens before releasing them, so we can never accidentally release the last token // permanently held by rustc process. - let parallel = match sess.opts.jobs.backend { - JobsMode::Parallel(n) if backend.supports_parallel() => Some(n), - _ => None, - }; + let jobserver_helper = parallel.map(|_| { let coordinator_send2 = coordinator_send.clone(); jobserver::client() @@ -1244,45 +1289,6 @@ fn start_executing_work( let tm_factory = backend.target_machine_factory(tcx.sess); - let remark_dir = if let Some(ref dir) = sess.opts.unstable_opts.remark_dir { - let result = fs::create_dir_all(dir).and_then(|_| dir.canonicalize()); - match result { - Ok(dir) => Some(dir), - Err(error) => sess.dcx().emit_fatal(ErrorCreatingRemarkDir { error }), - } - } else { - None - }; - - let stack_size = sess.opts.recommended_stack_size; - - let cgcx = CodegenContext { - crate_types: tcx.crate_types().to_vec(), - lto: sess.lto(), - use_linker_plugin_lto: sess.opts.cg.linker_plugin_lto.enabled(), - dylib_lto: sess.opts.unstable_opts.dylib_lto, - prefer_dynamic: sess.opts.cg.prefer_dynamic, - fewer_names: sess.fewer_names(), - save_temps: sess.opts.cg.save_temps, - time_trace: sess.opts.unstable_opts.llvm_time_trace, - remark: sess.opts.cg.remark.clone(), - remark_dir, - output_filenames: Arc::clone(tcx.output_filenames(())), - module_config: regular_config, - msvc_imps_needed: msvc_imps_needed(tcx), - is_pe_coff: tcx.sess.target.is_like_windows, - target_can_use_split_dwarf: tcx.sess.target_can_use_split_dwarf(), - target_arch: tcx.sess.target.arch.to_string(), - target_is_like_darwin: tcx.sess.target.is_like_darwin, - target_is_like_aix: tcx.sess.target.is_like_aix, - target_is_like_gpu: tcx.sess.target.is_like_gpu, - rust_eh_personality_symbol: rustc_symbol_mangling::eh_personality_symbol(tcx), - split_debuginfo: tcx.sess.split_debuginfo(), - split_dwarf_kind: tcx.sess.opts.unstable_opts.split_dwarf_kind, - parallel, - pointer_size: tcx.data_layout.pointer_size(), - }; - // This is the "main loop" of parallel work happening for parallel codegen. // It's here that we manage parallelism, schedule work, and work with // messages coming from clients. @@ -1502,15 +1508,18 @@ fn start_executing_work( let (item, _) = work_items.pop().expect("queue empty - queue_full_enough() broken?"); main_thread_state = MainThreadState::Lending; + if llvm_start_time.is_none() { + llvm_start_time = Some(prof.verbose_generic_activity("LLVM_passes")); + } spawn_work( &cgcx, &prof, incr_comp_session.as_ref(), shared_emitter.clone(), coordinator_send.clone(), - &mut llvm_start_time, item, stack_size, + false, ); } } @@ -1529,15 +1538,19 @@ fn start_executing_work( MainThreadState::Idle => { if let Some((item, _)) = work_items.pop() { main_thread_state = MainThreadState::Lending; + if llvm_start_time.is_none() { + llvm_start_time = + Some(prof.verbose_generic_activity("LLVM_passes")); + } spawn_work( &cgcx, &prof, incr_comp_session.as_ref(), shared_emitter.clone(), coordinator_send.clone(), - &mut llvm_start_time, item, stack_size, + false, ); } else { // There is no unstarted work, so let the main thread @@ -1574,15 +1587,18 @@ fn start_executing_work( while running_with_own_token < tokens.len() && let Some((item, _)) = work_items.pop() { + if llvm_start_time.is_none() { + llvm_start_time = Some(prof.verbose_generic_activity("LLVM_passes")); + } spawn_work( &cgcx, &prof, incr_comp_session.as_ref(), shared_emitter.clone(), coordinator_send.clone(), - &mut llvm_start_time, item, stack_size, + false, ); running_with_own_token += 1; } @@ -1670,7 +1686,7 @@ fn start_executing_work( if main_thread_state == MainThreadState::Lending { main_thread_state = MainThreadState::Idle; } else { - running_with_own_token -= 1; + running_with_own_token = running_with_own_token.saturating_sub(1) } match result { @@ -1847,14 +1863,10 @@ fn spawn_work<'a, B: WriteBackendMethods>( incr_comp_session: Option<&BorrowedIncrCompSession>, shared_emitter: SharedEmitter, coordinator_send: Sender>, - llvm_start_time: &mut Option>, work: WorkItem, stack_size: usize, + blocking: bool, ) { - if llvm_start_time.is_none() { - *llvm_start_time = Some(prof.verbose_generic_activity("LLVM_passes")); - } - let old_incr_comp_session_dir = incr_comp_session .and_then(|incr_comp_session| incr_comp_session.old_session_directory.clone()); let new_incr_comp_session_dir = @@ -1900,11 +1912,15 @@ fn spawn_work<'a, B: WriteBackendMethods>( }; drop(coordinator_send.send(msg)); }; - std::thread::Builder::new() - .name(name) - .stack_size(stack_size) - .spawn(f) - .expect("failed to spawn work thread"); + if blocking { + f(); + } else { + std::thread::Builder::new() + .name(name) + .stack_size(stack_size) + .spawn(f) + .expect("failed to spawn work thread"); + } } fn spawn_thin_lto_work( @@ -1982,6 +1998,13 @@ pub struct SharedEmitter { sender: Sender, } +unsafe impl DynSend for SharedEmitter {} +unsafe impl DynSync for SharedEmitter {} +fn _assert_emitter_fields() { + sync::assert_dyn_sync::>>(); + sync::assert_dyn_send::>>(); +} + pub struct SharedEmitterMain { receiver: Receiver, } @@ -2104,6 +2127,16 @@ pub struct OngoingCodegen { pub(crate) coordinator: Coordinator, codegen_worker_receive: Receiver, shared_emitter_main: SharedEmitterMain, + work_ctx: LlvmWorkContext, +} + +#[derive(Clone)] +struct LlvmWorkContext { + cgcx: CodegenContext, + prof: SelfProfilerRef, + incr_comp_session: Option, + stack_size: usize, + shared_emitter: SharedEmitter, } impl OngoingCodegen { @@ -2113,6 +2146,8 @@ impl OngoingCodegen { incr_comp_session: Option<&IncrCompSession>, crate_info: &CrateInfo, ) -> (CompiledModules, WorkProductMap) { + // This contains the last shared emitter sender + drop(self.work_ctx); self.shared_emitter_main.check(sess, true); let maybe_lto_modules = sess.time("join_worker_thread", || match self.coordinator.join() { @@ -2232,53 +2267,66 @@ impl OngoingCodegen { } } } -} -pub(crate) fn submit_codegened_module_to_llvm( - coordinator: &Coordinator, - module: ModuleCodegen, - cost: u64, -) { - let llvm_work_item = WorkItem::Optimize(module); - drop(coordinator.sender.send(Message::CodegenDone:: { llvm_work_item, cost })); -} + pub(crate) fn submit_codegened_module_to_llvm( + &self, + module: ModuleCodegen, + cost: u64, + blocking: bool, + ) { + let llvm_work_item = WorkItem::Optimize(module); + + if blocking { + spawn_work( + &self.work_ctx.cgcx, + &self.work_ctx.prof, + self.work_ctx.incr_comp_session.as_ref(), + self.work_ctx.shared_emitter.clone(), + self.coordinator.sender.clone(), + llvm_work_item, + self.work_ctx.stack_size, + true, + ); + } else { + drop(self.coordinator.sender.send(Message::CodegenDone:: { llvm_work_item, cost })); + } + } -pub(crate) fn submit_post_lto_module_to_llvm( - coordinator: &Coordinator, - module: CachedModuleCodegen, -) { - let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module); - drop(coordinator.sender.send(Message::CodegenDone:: { llvm_work_item, cost: 0 })); -} + pub(crate) fn submit_post_lto_module_to_llvm(&self, module: CachedModuleCodegen) { + let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module); + drop(self.coordinator.sender.send(Message::CodegenDone:: { llvm_work_item, cost: 0 })); + } -pub(crate) fn submit_pre_lto_module_to_llvm( - tcx: TyCtxt<'_>, - coordinator: &Coordinator, - module: CachedModuleCodegen, -) { - let filename = pre_lto_bitcode_filename(&module.name); - let old_bitcode_path = - in_old_incr_comp_dir_sess(tcx.incr_comp_session.unwrap(), &filename).unwrap(); - let bitcode_path = in_incr_comp_dir_sess(tcx.incr_comp_session.unwrap(), &filename); - - match link_or_copy(&old_bitcode_path, &bitcode_path) { - Ok(_) => {} - Err(error) => { - tcx.sess.dcx().emit_err(diagnostics::CopyPathBuf { - source_file: old_bitcode_path, - output_path: bitcode_path, - error, - }); - return; + pub(crate) fn submit_pre_lto_module_to_llvm( + &self, + tcx: TyCtxt<'_>, + module: CachedModuleCodegen, + ) { + let filename = pre_lto_bitcode_filename(&module.name); + let old_bitcode_path = + in_old_incr_comp_dir_sess(tcx.incr_comp_session.unwrap(), &filename).unwrap(); + let bitcode_path = in_incr_comp_dir_sess(tcx.incr_comp_session.unwrap(), &filename); + + match link_or_copy(&old_bitcode_path, &bitcode_path) { + Ok(_) => {} + Err(error) => { + tcx.sess.dcx().emit_err(diagnostics::CopyPathBuf { + source_file: old_bitcode_path, + output_path: bitcode_path, + error, + }); + return; + } } - } - // Schedule the module to be loaded - drop( - coordinator - .sender - .send(Message::AddImportOnlyModule:: { bitcode_path, work_product: module.source }), - ); + // Schedule the module to be loaded + drop( + self.coordinator.sender.send(Message::AddImportOnlyModule:: { + bitcode_path, + work_product: module.source, + }), + ); + } } fn pre_lto_bitcode_filename(module_name: &str) -> String { diff --git a/compiler/rustc_codegen_ssa/src/base.rs b/compiler/rustc_codegen_ssa/src/base.rs index e165bb0ce4d4d..70189a8b39e88 100644 --- a/compiler/rustc_codegen_ssa/src/base.rs +++ b/compiler/rustc_codegen_ssa/src/base.rs @@ -13,9 +13,10 @@ use rustc_attr_ir::lang_items::LangItem; use rustc_attr_ir::target::Target; use rustc_attr_ir::{DebuggerVisualizerType, EiiDecl, EiiImpl, find_attr}; use rustc_crate_store::CrateSourceFlags; -use rustc_data_structures::fx::{FxHashMap, FxIndexMap, FxIndexSet}; +use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; +use rustc_data_structures::jobserver::proxy; use rustc_data_structures::profiling::{get_resident_set_size, print_time_passes_entry}; -use rustc_data_structures::sync::{IntoDynSyncSend, par_map}; +use rustc_data_structures::sync::{self, IntoDynSyncSend, Registry, par_map}; use rustc_data_structures::unord::UnordMap; use rustc_hir as hir; use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE}; @@ -27,12 +28,13 @@ use rustc_middle::mir::interpret::{CTFE_ALLOC_SALT, ErrorHandled, Scalar}; use rustc_middle::mir::{BinOp, ConstValue}; use rustc_middle::mono::{CodegenUnit, CodegenUnitNameBuilder, MonoItem, MonoItemPartitions}; use rustc_middle::ty::layout::{HasTyCtxt, HasTypingEnv, LayoutOf, TyAndLayout}; -use rustc_middle::ty::{self, Instance, PatternKind, Ty, TyCtxt, UintTy, Unnormalized}; +use rustc_middle::ty::{self, Instance, PatternKind, Ty, TyCtxt, UintTy, Unnormalized, tls}; use rustc_session::config::{self, EntryFnType, JobsMode}; use rustc_span::{DUMMY_SP, Symbol, bug, span_bug}; use rustc_structures::CrateType; use rustc_symbol_mangling::mangle_internal_symbol; use rustc_target::spec::{Arch, Os, Target as TargetSpec}; +use rustc_thread_pool::ThreadPoolBuilder; use rustc_trait_selection::infer::{BoundRegionConversionTime, TyCtxtInferExt}; use rustc_trait_selection::traits::{ObligationCause, ObligationCtxt}; use tracing::{debug, info}; @@ -41,7 +43,6 @@ use crate::assert_module_sources::CguReuse; use crate::back::link::are_upstream_rust_objects_already_included; use crate::back::write::{ ComputedLtoType, ModuleConfig, OngoingCodegen, compute_per_cgu_lto_type, start_async_codegen, - submit_codegened_module_to_llvm, submit_post_lto_module_to_llvm, submit_pre_lto_module_to_llvm, }; use crate::common::{self, IntPredicate, RealPredicate}; use crate::meth::VirtualIndex; @@ -808,70 +809,103 @@ pub fn codegen_crate< let mut total_codegen_time = Duration::new(0, 0); let start_rss = tcx.sess.opts.unstable_opts.time_passes.then(|| get_resident_set_size()); - // The non-parallel compiler can only translate codegen units to LLVM IR - // on a single thread, leading to a staircase effect where the N LLVM - // threads have to wait on the single codegen threads to generate work - // for them. The parallel compiler does not have this restriction, so - // we can pre-load the LLVM queue in parallel before handing off - // coordination to the OnGoingCodegen scheduler. - // - // This likely is a temporary measure. Once we don't have to support the - // non-parallel compiler anymore, we can compile CGUs end-to-end in - // parallel and get rid of the complicated scheduling logic. - let mut pre_compiled_cgus = if let JobsMode::Parallel(threads) = tcx.sess.opts.jobs.frontend { - tcx.sess.time("compile_first_CGU_batch", || { - // Try to find one CGU to compile per thread. - let cgus: Vec<_> = cgu_reuse - .iter() - .enumerate() - .filter(|&(_, reuse)| reuse == &CguReuse::No) - .take(threads.get()) - .collect(); - - // Compile the found CGUs in parallel. - let start_time = Instant::now(); - - let pre_compiled_cgus = par_map(cgus, |(i, _)| { - let module = - backend.compile_codegen_unit(tcx, codegen_units[i].name(), bitcode_needed); - (i, IntoDynSyncSend(module)) + let proof = sync::check_dyn_thread_safe(); + if let Some(proof) = proof + && let JobsMode::Parallel(backend_threads) = tcx.sess.opts.jobs.backend + { + // Creating a new thread pool discards all thread-local variables from the current thread pool, + // so we have to manually feed them back in + rustc_span::with_session_globals(|session_globals| { + tls::with_context(|icx| { + let tcx = proof.derive(tcx); + let icx = proof.derive(icx); + let codegen = IntoDynSyncSend(&ongoing_codegen); + + let registry = Registry::current(); + let session_globals = proof.derive(session_globals); + + let proxy = proxy(); + let proxy_ = proxy.clone(); + + ThreadPoolBuilder::new() + .thread_name(|_| "codegen".to_string()) + .num_threads(backend_threads.get()) + .acquire_thread_handler(move || proxy.acquire_thread()) + .release_thread_handler(move || proxy_.release_thread()) + .stack_size(tcx.sess.opts.recommended_stack_size) + .build_scoped( + move |thread: rustc_thread_pool::ThreadBuilder| { + // Register the thread for use with the `WorkerLocal` type. + registry.register(); + + rustc_span::set_session_globals_then(session_globals.into_inner(), || { + thread.run() + }) + }, + |pool: &rustc_thread_pool::ThreadPool| { + // Compile the found CGUs in parallel. + pool.install(|| { + tls::enter_context(*icx, || { + let start_time = Instant::now(); + let _timer = tcx.sess.prof.verbose_generic_activity("LLVM_passes"); + + let () = par_map(codegen_units.iter().zip(cgu_reuse.iter()), |(cgu, cgu_reuse)| { + match cgu_reuse { + CguReuse::No => { + let (module, cost) = + backend.compile_codegen_unit(*tcx, cgu.name(), bitcode_needed); + // This will unwind if there are errors, which triggers our `AbortCodegenOnDrop` + // guard. Unfortunately, just skipping the `submit_codegened_module_to_llvm` makes + // compilation hang on post-monomorphization errors. + tcx.dcx().abort_if_errors(); + + codegen.submit_codegened_module_to_llvm(module, cost, true); + } + CguReuse::PreLto | CguReuse::PostLto => {} + } + }); + total_codegen_time += start_time.elapsed(); + }); + }); + }, + ) + .unwrap_or_else(|err| { + let mut diag = tcx.dcx().struct_fatal(format!( + "failed to spawn compiler thread pool: could not create {backend_threads} threads ({err})", + )); + diag.help( + "try lowering `--jobs-backend` or checking the operating system's resource limits", + ); + diag.emit_fatal() + }); }); - - total_codegen_time += start_time.elapsed(); - - pre_compiled_cgus - }) - } else { - FxHashMap::default() - }; + }); + } for (i, cgu) in codegen_units.iter().enumerate() { + let cgu_reuse = cgu_reuse[i]; + if proof.is_some() && matches!(cgu_reuse, CguReuse::No) { + continue; + } + ongoing_codegen.wait_for_signal_to_codegen_item(); ongoing_codegen.check_for_errors(tcx.sess); - let cgu_reuse = cgu_reuse[i]; - match cgu_reuse { CguReuse::No => { - let (module, cost) = if let Some(cgu) = pre_compiled_cgus.remove(&i) { - cgu.0 - } else { - let start_time = Instant::now(); - let module = backend.compile_codegen_unit(tcx, cgu.name(), bitcode_needed); - total_codegen_time += start_time.elapsed(); - module - }; + let start_time = Instant::now(); + let (module, cost) = backend.compile_codegen_unit(tcx, cgu.name(), bitcode_needed); + total_codegen_time += start_time.elapsed(); // This will unwind if there are errors, which triggers our `AbortCodegenOnDrop` // guard. Unfortunately, just skipping the `submit_codegened_module_to_llvm` makes // compilation hang on post-monomorphization errors. tcx.dcx().abort_if_errors(); - submit_codegened_module_to_llvm(&ongoing_codegen.coordinator, module, cost); + ongoing_codegen.submit_codegened_module_to_llvm(module, cost, false); } CguReuse::PreLto => { - submit_pre_lto_module_to_llvm( + ongoing_codegen.submit_pre_lto_module_to_llvm( tcx, - &ongoing_codegen.coordinator, CachedModuleCodegen { name: cgu.name().to_string(), source: cgu.previous_work_product(tcx), @@ -883,13 +917,10 @@ pub fn codegen_crate< tcx.dcx().abort_if_errors(); } CguReuse::PostLto => { - submit_post_lto_module_to_llvm( - &ongoing_codegen.coordinator, - CachedModuleCodegen { - name: cgu.name().to_string(), - source: cgu.previous_work_product(tcx), - }, - ); + ongoing_codegen.submit_post_lto_module_to_llvm(CachedModuleCodegen { + name: cgu.name().to_string(), + source: cgu.previous_work_product(tcx), + }); } } } diff --git a/compiler/rustc_codegen_ssa/src/lib.rs b/compiler/rustc_codegen_ssa/src/lib.rs index d19b80897a21d..a9f85eae0f8f7 100644 --- a/compiler/rustc_codegen_ssa/src/lib.rs +++ b/compiler/rustc_codegen_ssa/src/lib.rs @@ -1,6 +1,7 @@ // tidy-alphabetical-start #![feature(deref_patterns)] #![feature(file_buffered)] +#![feature(mpmc_channel)] #![feature(negative_impls)] #![feature(option_into_flat_iter)] #![feature(trait_alias)] diff --git a/compiler/rustc_data_structures/src/jobserver.rs b/compiler/rustc_data_structures/src/jobserver.rs index ce29e5a2f8244..858249e7c6076 100644 --- a/compiler/rustc_data_structures/src/jobserver.rs +++ b/compiler/rustc_data_structures/src/jobserver.rs @@ -100,8 +100,14 @@ pub struct Proxy { wake_pending: Condvar, } +static PROXY: OnceLock> = OnceLock::new(); + +pub fn proxy() -> Arc { + PROXY.get_or_init(Proxy::new).clone() +} + impl Proxy { - pub fn new() -> Arc { + fn new() -> Arc { let proxy = Arc::new(Proxy { client: client(), // Assume that the main thread is actively doing work when it creates the proxy. diff --git a/compiler/rustc_interface/src/util.rs b/compiler/rustc_interface/src/util.rs index d1110ecf33cb7..2d2d177ee0cd2 100644 --- a/compiler/rustc_interface/src/util.rs +++ b/compiler/rustc_interface/src/util.rs @@ -15,7 +15,7 @@ use rustc_codegen_ssa::target_features::internal_target_features; use rustc_codegen_ssa::traits::CodegenBackend; use rustc_codegen_ssa::{CompiledModules, CrateInfo, TargetConfig}; use rustc_data_structures::base_n::{CASE_INSENSITIVE, ToBaseN}; -use rustc_data_structures::jobserver::Proxy; +use rustc_data_structures::jobserver::proxy; use rustc_data_structures::sync; use rustc_metadata::{DylibError, EncodedMetadata, load_symbol_from_dylib}; use rustc_middle::dep_graph::WorkProductMap; @@ -252,7 +252,7 @@ pub(crate) fn run_in_thread_pool_with_globals R + Send, let thread_stack_size = init_stack_size(thread_builder_diag); let jobs_frontend = jobs.frontend.limit(); - let registry = sync::Registry::new(jobs_frontend); + let registry = sync::Registry::new(jobs_frontend.saturating_add(jobs.backend.limit().get())); let Some(proof) = sync::check_dyn_thread_safe() else { assert_eq!(jobs_frontend.get(), 1); @@ -273,7 +273,7 @@ pub(crate) fn run_in_thread_pool_with_globals R + Send, let current_gcx = proof.derive(CurrentGcx::new()); let current_gcx2 = current_gcx.clone(); - let proxy = Proxy::new(); + let proxy = proxy(); // Explicitly drop and join helper thread before rustc exits, // so all job server tokens are returned. diff --git a/compiler/rustc_session/src/session.rs b/compiler/rustc_session/src/session.rs index 6b7e2214f26d9..83b7bef9d3e61 100644 --- a/compiler/rustc_session/src/session.rs +++ b/compiler/rustc_session/src/session.rs @@ -1921,6 +1921,7 @@ impl Drop for IncrCompSession { } /// A runtime tracked borrow of the incr comp session. Can be sent to worker threads. +#[derive(Clone)] pub struct BorrowedIncrCompSession { pub old_session_directory: Option, pub new_session_directory: PathBuf,