Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Run linking and incremental saving / finalizing in parallel #121880

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 14 additions & 15 deletions compiler/rustc_codegen_cranelift/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,16 @@ extern crate rustc_target;
extern crate rustc_driver;

use std::any::Any;
use std::cell::{Cell, RefCell};
use std::cell::Cell;
use std::sync::Arc;
use std::sync::OnceLock;

use cranelift_codegen::isa::TargetIsa;
use cranelift_codegen::settings::{self, Configurable};
use rustc_codegen_ssa::traits::CodegenBackend;
use rustc_codegen_ssa::CodegenResults;
use rustc_data_structures::profiling::SelfProfilerRef;
use rustc_data_structures::sync::{downcast_box_any_dyn_send, DynSend};
use rustc_errors::ErrorGuaranteed;
use rustc_metadata::EncodedMetadata;
use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
Expand Down Expand Up @@ -165,7 +167,7 @@ impl CodegenCx {
}

pub struct CraneliftCodegenBackend {
pub config: RefCell<Option<BackendConfig>>,
pub config: OnceLock<BackendConfig>,
}

impl CodegenBackend for CraneliftCodegenBackend {
Expand All @@ -183,12 +185,10 @@ impl CodegenBackend for CraneliftCodegenBackend {
}
}

let mut config = self.config.borrow_mut();
if config.is_none() {
let new_config = BackendConfig::from_opts(&sess.opts.cg.llvm_args)
.unwrap_or_else(|err| sess.dcx().fatal(err));
*config = Some(new_config);
}
self.config.get_or_init(|| {
BackendConfig::from_opts(&sess.opts.cg.llvm_args)
.unwrap_or_else(|err| sess.dcx().fatal(err))
});
}

fn target_features(&self, sess: &Session, _allow_unstable: bool) -> Vec<rustc_span::Symbol> {
Expand All @@ -213,9 +213,9 @@ impl CodegenBackend for CraneliftCodegenBackend {
tcx: TyCtxt<'_>,
metadata: EncodedMetadata,
need_metadata_module: bool,
) -> Box<dyn Any> {
) -> Box<dyn Any + DynSend> {
tcx.dcx().abort_if_errors();
let config = self.config.borrow().clone().unwrap();
let config = self.config.get().unwrap().clone();
match config.codegen_mode {
CodegenMode::Aot => driver::aot::run_aot(tcx, config, metadata, need_metadata_module),
CodegenMode::Jit | CodegenMode::JitLazy => {
Expand All @@ -230,14 +230,13 @@ impl CodegenBackend for CraneliftCodegenBackend {

fn join_codegen(
&self,
ongoing_codegen: Box<dyn Any>,
ongoing_codegen: Box<dyn Any + DynSend>,
sess: &Session,
_outputs: &OutputFilenames,
) -> (CodegenResults, FxIndexMap<WorkProductId, WorkProduct>) {
ongoing_codegen
.downcast::<driver::aot::OngoingCodegen>()
downcast_box_any_dyn_send::<driver::aot::OngoingCodegen>(ongoing_codegen)
.unwrap()
.join(sess, self.config.borrow().as_ref().unwrap())
.join(sess, self.config.get().unwrap())
}

fn link(
Expand Down Expand Up @@ -350,5 +349,5 @@ fn build_isa(sess: &Session, backend_config: &BackendConfig) -> Arc<dyn isa::Tar
/// This is the entrypoint for a hot plugged rustc_codegen_cranelift
#[no_mangle]
pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
Box::new(CraneliftCodegenBackend { config: RefCell::new(None) })
Box::new(CraneliftCodegenBackend { config: OnceLock::new() })
}
9 changes: 4 additions & 5 deletions compiler/rustc_codegen_gcc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ use rustc_codegen_ssa::base::codegen_crate;
use rustc_codegen_ssa::back::write::{CodegenContext, FatLtoInput, ModuleConfig, TargetMachineFactoryFn};
use rustc_codegen_ssa::back::lto::{LtoModuleCodegen, SerializedModule, ThinModule};
use rustc_data_structures::fx::FxIndexMap;
use rustc_data_structures::sync::IntoDynSyncSend;
use rustc_data_structures::sync::{downcast_box_any_dyn_send, DynSend, IntoDynSyncSend};
use rustc_codegen_ssa::traits::{CodegenBackend, ExtraBackendMethods, ThinBufferMethods, WriteBackendMethods};
use rustc_errors::{ErrorGuaranteed, DiagCtxt};
use rustc_metadata::EncodedMetadata;
Expand Down Expand Up @@ -210,16 +210,15 @@ impl CodegenBackend for GccCodegenBackend {
|tcx, ()| gcc_util::global_gcc_features(tcx.sess, true)
}

fn codegen_crate<'tcx>(&self, tcx: TyCtxt<'tcx>, metadata: EncodedMetadata, need_metadata_module: bool) -> Box<dyn Any> {
fn codegen_crate<'tcx>(&self, tcx: TyCtxt<'tcx>, metadata: EncodedMetadata, need_metadata_module: bool) -> Box<dyn Any + DynSend> {
let target_cpu = target_cpu(tcx.sess);
let res = codegen_crate(self.clone(), tcx, target_cpu.to_string(), metadata, need_metadata_module);

Box::new(res)
}

fn join_codegen(&self, ongoing_codegen: Box<dyn Any>, sess: &Session, _outputs: &OutputFilenames) -> (CodegenResults, FxIndexMap<WorkProductId, WorkProduct>) {
ongoing_codegen
.downcast::<rustc_codegen_ssa::back::write::OngoingCodegen<GccCodegenBackend>>()
fn join_codegen(&self, ongoing_codegen: Box<dyn Any + DynSend>, sess: &Session, _outputs: &OutputFilenames) -> (CodegenResults, FxIndexMap<WorkProductId, WorkProduct>) {
downcast_box_any_dyn_send::<rustc_codegen_ssa::back::write::OngoingCodegen<GccCodegenBackend>>( ongoing_codegen)
.expect("Expected GccCodegenBackend's OngoingCodegen, found Box<Any>")
.join(sess)
}
Expand Down
17 changes: 8 additions & 9 deletions compiler/rustc_codegen_llvm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ use rustc_codegen_ssa::traits::*;
use rustc_codegen_ssa::ModuleCodegen;
use rustc_codegen_ssa::{CodegenResults, CompiledModule};
use rustc_data_structures::fx::FxIndexMap;
use rustc_data_structures::sync::{downcast_box_any_dyn_send, DynSend};
use rustc_errors::{DiagCtxt, ErrorGuaranteed, FatalError};
use rustc_metadata::EncodedMetadata;
use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
Expand Down Expand Up @@ -250,9 +251,6 @@ impl WriteBackendMethods for LlvmCodegenBackend {
}
}

unsafe impl Send for LlvmCodegenBackend {} // Llvm is on a per-thread basis
unsafe impl Sync for LlvmCodegenBackend {}

impl LlvmCodegenBackend {
pub fn new() -> Box<dyn CodegenBackend> {
Box::new(LlvmCodegenBackend(()))
Expand Down Expand Up @@ -354,7 +352,7 @@ impl CodegenBackend for LlvmCodegenBackend {
tcx: TyCtxt<'tcx>,
metadata: EncodedMetadata,
need_metadata_module: bool,
) -> Box<dyn Any> {
) -> Box<dyn Any + DynSend> {
Box::new(rustc_codegen_ssa::base::codegen_crate(
LlvmCodegenBackend(()),
tcx,
Expand All @@ -366,14 +364,15 @@ impl CodegenBackend for LlvmCodegenBackend {

fn join_codegen(
&self,
ongoing_codegen: Box<dyn Any>,
ongoing_codegen: Box<dyn Any + DynSend>,
sess: &Session,
outputs: &OutputFilenames,
) -> (CodegenResults, FxIndexMap<WorkProductId, WorkProduct>) {
let (codegen_results, work_products) = ongoing_codegen
.downcast::<rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
.expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
.join(sess);
let (codegen_results, work_products) = downcast_box_any_dyn_send::<
rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>,
>(ongoing_codegen)
.expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<dyn Any + DynSend>")
.join(sess);

if sess.opts.unstable_opts.llvm_time_trace {
sess.time("llvm_dump_timing_file", || {
Expand Down
10 changes: 5 additions & 5 deletions compiler/rustc_codegen_ssa/src/traits/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ impl<'tcx, T> Backend<'tcx> for T where
{
}

pub trait CodegenBackend {
pub trait CodegenBackend: DynSync + DynSend {
/// Locale resources for diagnostic messages - a string the content of the Fluent resource.
/// Called before `init` so that all other functions are able to emit translatable diagnostics.
fn locale_resource(&self) -> &'static str;
Expand Down Expand Up @@ -90,16 +90,16 @@ pub trait CodegenBackend {
tcx: TyCtxt<'tcx>,
metadata: EncodedMetadata,
need_metadata_module: bool,
) -> Box<dyn Any>;
) -> Box<dyn Any + DynSend>;

/// This is called on the returned `Box<dyn Any>` from `codegen_backend`
/// This is called on the returned `Box<dyn Any + DynSend>` from `codegen_backend`
///
/// # Panics
///
/// Panics when the passed `Box<dyn Any>` was not returned by `codegen_backend`.
/// Panics when the passed `Box<dyn Any + DynSend>` was not returned by `codegen_backend`.
fn join_codegen(
&self,
ongoing_codegen: Box<dyn Any>,
ongoing_codegen: Box<dyn Any + DynSend>,
sess: &Session,
outputs: &OutputFilenames,
) -> (CodegenResults, FxIndexMap<WorkProductId, WorkProduct>);
Expand Down
27 changes: 26 additions & 1 deletion compiler/rustc_data_structures/src/marker.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::any::Any;

cfg_match! {
cfg(not(parallel_compiler)) => {
pub auto trait DynSend {}
Expand Down Expand Up @@ -67,6 +69,11 @@ cfg_match! {
[std::io::Stderr]
[std::io::Error]
[std::fs::File]
[std::sync::Condvar]
[jobserver_crate::Client]
[jobserver_crate::HelperThread]
[jobserver_crate::Acquired]
[Box<dyn Any + Send>]
[rustc_arena::DroplessArena]
[crate::memmap::Mmap]
[crate::profiling::SelfProfiler]
Expand All @@ -81,10 +88,14 @@ cfg_match! {

impl_dyn_send!(
[std::sync::atomic::AtomicPtr<T> where T]
[std::sync::Mutex<T> where T: ?Sized+ DynSend]
[std::sync::Mutex<T> where T: ?Sized + DynSend]
[std::sync::RwLock<T> where T: ?Sized + DynSend]
[std::sync::mpsc::Sender<T> where T: DynSend]
[std::sync::mpsc::Receiver<T> where T: DynSend]
[std::sync::Arc<T> where T: ?Sized + DynSync + DynSend]
[std::sync::OnceLock<T> where T: DynSend]
[std::sync::LazyLock<T, F> where T: DynSend, F: DynSend]
[std::thread::JoinHandle<T> where T]
[std::collections::HashSet<K, S> where K: DynSend, S: DynSend]
[std::collections::HashMap<K, V, S> where K: DynSend, V: DynSend, S: DynSend]
[std::collections::BTreeMap<K, V, A> where K: DynSend, V: DynSend, A: std::alloc::Allocator + Clone + DynSend]
Expand Down Expand Up @@ -139,6 +150,7 @@ cfg_match! {
[std::sync::atomic::AtomicU8]
[std::sync::atomic::AtomicU32]
[std::backtrace::Backtrace]
[std::sync::Condvar]
[std::io::Error]
[std::fs::File]
[jobserver_crate::Client]
Expand Down Expand Up @@ -170,6 +182,7 @@ cfg_match! {
[std::sync::OnceLock<T> where T: DynSend + DynSync]
[std::sync::Mutex<T> where T: ?Sized + DynSend]
[std::sync::Arc<T> where T: ?Sized + DynSync + DynSend]
[std::sync::RwLock<T> where T: ?Sized + DynSend + DynSync]
[std::sync::LazyLock<T, F> where T: DynSend + DynSync, F: DynSend]
[std::collections::HashSet<K, S> where K: DynSync, S: DynSync]
[std::collections::HashMap<K, V, S> where K: DynSync, V: DynSync, S: DynSync]
Expand Down Expand Up @@ -258,3 +271,15 @@ impl<T> std::ops::DerefMut for IntoDynSyncSend<T> {
&mut self.0
}
}

#[inline]
pub fn downcast_box_any_dyn_send<T: Any>(this: Box<dyn Any + DynSend>) -> Result<Box<T>, ()> {
if <dyn Any>::is::<T>(&*this) {
unsafe {
let (raw, alloc): (*mut (dyn Any + DynSend), _) = Box::into_raw_with_allocator(this);
Ok(Box::from_raw_in(raw as *mut T, alloc))
}
} else {
Err(())
}
}
3 changes: 3 additions & 0 deletions compiler/rustc_data_structures/src/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ pub use crate::marker::*;
use std::collections::HashMap;
use std::hash::{BuildHasher, Hash};

mod task;
pub use task::{task, Task};

mod lock;
pub use lock::{Lock, LockGuard, Mode};

Expand Down
102 changes: 102 additions & 0 deletions compiler/rustc_data_structures/src/sync/task.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
use crate::jobserver;
use crate::sync::{mode, DynSend, FromDyn, IntoDynSyncSend};
use parking_lot::Condvar;
use parking_lot::Mutex;
use std::any::Any;
use std::mem;
use std::panic::{self, AssertUnwindSafe};
use std::sync::Arc;

enum TaskState<T: DynSend + 'static> {
Unexecuted(Box<dyn FnOnce() -> T + DynSend>),
Running,
Joined,
Result(Result<T, IntoDynSyncSend<Box<dyn Any + Send + 'static>>>),
}

struct TaskData<T: DynSend + 'static> {
state: Mutex<TaskState<T>>,
waiter: Condvar,
}

#[must_use]
pub struct Task<T: DynSend + 'static> {
data: Arc<TaskData<T>>,
}

/// This attempts to run a closure in a background thread. It returns a `Task` type which
/// you must call `join` on to ensure that the closure runs.
pub fn task<T: DynSend>(f: impl FnOnce() -> T + DynSend + 'static) -> Task<T> {
let task = Task {
data: Arc::new(TaskData {
state: Mutex::new(TaskState::Unexecuted(Box::new(f))),
waiter: Condvar::new(),
}),
};

#[cfg(parallel_compiler)]
if mode::is_dyn_thread_safe() {
let data = FromDyn::from(task.data.clone());

// Try to execute the task on a separate thread.
rayon::spawn(move || {
let data = data.into_inner();
let mut state = data.state.lock();
if matches!(*state, TaskState::Unexecuted(..)) {
if let TaskState::Unexecuted(f) = mem::replace(&mut *state, TaskState::Running) {
drop(state);
let result = panic::catch_unwind(AssertUnwindSafe(f));

let unblock = {
let mut state = data.state.lock();
let unblock = matches!(*state, TaskState::Joined);
*state = TaskState::Result(result.map_err(|e| IntoDynSyncSend(e)));
unblock
};

if unblock {
rayon_core::mark_unblocked(&rayon_core::Registry::current());
}

data.waiter.notify_one();
}
}
});
}

task
}

#[inline]
fn unwind<T>(result: Result<T, IntoDynSyncSend<Box<dyn Any + Send + 'static>>>) -> T {
match result {
Ok(r) => r,
Err(err) => panic::resume_unwind(err.0),
}
}

impl<T: DynSend> Task<T> {
pub fn join(self) -> T {
let mut state_guard = self.data.state.lock();

match mem::replace(&mut *state_guard, TaskState::Joined) {
TaskState::Unexecuted(f) => f(),
TaskState::Result(result) => unwind(result),
TaskState::Running => {
#[cfg(parallel_compiler)]
rayon_core::mark_blocked();
jobserver::release_thread();

self.data.waiter.wait(&mut state_guard);

jobserver::acquire_thread();

match mem::replace(&mut *state_guard, TaskState::Joined) {
TaskState::Result(result) => unwind(result),
_ => panic!(),
}
}
TaskState::Joined => panic!(),
}
}
}
4 changes: 2 additions & 2 deletions compiler/rustc_driver_impl/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -461,8 +461,8 @@ fn run_compiler(
// Linking is done outside the `compiler.enter()` so that the
// `GlobalCtxt` within `Queries` can be freed as early as possible.
if let Some(linker) = linker {
let _timer = sess.timer("link");
linker.link(sess, codegen_backend)?
let _timer = sess.timer("waiting for linking");
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we keep a timer for the entire time linking takes?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We still have link_crate which covers the codegen backend part of linking.

linker.join()?;
}

if sess.opts.unstable_opts.print_fuel.is_some() {
Expand Down
Loading
Loading