Truly independent web browser
LibJS: Compile JIT code on several threads
Andreas Kling2a4467a0a5c2
diff --git a/Libraries/LibJS/JIT/ARCHITECTURE.md b/Libraries/LibJS/JIT/ARCHITECTURE.mdindex d38ce492909..28312a0936f 100644--- a/Libraries/LibJS/JIT/ARCHITECTURE.md+++ b/Libraries/LibJS/JIT/ARCHITECTURE.md@@ -12,8 +12,8 @@ snapshots, installs code, enters it and translates its state back into interpretLibJS has two tiers: the bytecode interpreter, whose instructions keep per-site caches andfeedback, and this optimizing JIT. An executable that uses up its tier-up budget (calls and loop-iterations) is snapshotted and compiled on the compile thread. The interpreter keeps running it-meanwhile; the main thread installs the code when the job finishes. Loops that run long enough+iterations) is snapshotted and compiled on one of the compile threads. The interpreter keeps running+it meanwhile; the main thread installs the code when the job finishes. Loops that run long enoughenter compiled code at their back edges (on-stack replacement).There is no baseline tier. The interpreter's caches are the baseline: the JIT translates what they@@ -414,6 +414,7 @@ LIBJS_JIT=threshold=100,help ./Build/release/bin/js script.js| `threshold=N` | 400 | How many invocations make a function hot, after its warm-up. Loop iterations count as a fraction of an invocation. || `warmup=N` | 8 | How many invocations a function runs before the interpreter collects feedback for it. || `sync` | off | Compile on the main thread when a function gets hot, at the same points in every run, instead of on a compile thread. |+| `compile-threads=N` | 0 | How many threads compile hot functions; 0 starts one per processor core but one, up to 8. || `inline-budget=N` | 250 | How many bytecode instructions the inlined callees of one compile may have together. || `inline-max-size=N` | 30 | How many bytecode instructions one inlined callee may have. || `inline-depth=N` | 5 | How deeply inlined calls may nest; 0 turns inlining off. |diff --git a/Libraries/LibJS/JIT/Rust/src/options.rs b/Libraries/LibJS/JIT/Rust/src/options.rsindex 61b2332d4f5..4153099b721 100644--- a/Libraries/LibJS/JIT/Rust/src/options.rs+++ b/Libraries/LibJS/JIT/Rust/src/options.rs@@ -29,6 +29,10 @@ pub struct Options {/// Compile synchronously when an executable tiers up.pub sync: bool,+ /// How many threads compile asynchronously, or 0 for one per processor core but one (see+ /// `compile_thread_count()`).+ pub compile_threads: u32,+/// List the options and the values in effect on stderr.pub help: bool,@@ -96,6 +100,7 @@ impl Default for Options {threshold: 400,warmup: 8,sync: false,+ compile_threads: 0,help: false,dump_ir: false,dump_passes: false,@@ -180,6 +185,14 @@ const DEFINITIONS: &[Definition] = &[setting: Setting::Switch(|options| &mut options.sync),description: "Compile on the main thread when a function gets hot, at the same points in every run.",},+ Definition {+ name: "compile-threads",+ setting: Setting::Number {+ field: |options| &mut options.compile_threads,+ bare: None,+ },+ description: "How many threads compile hot functions; 0 starts one per processor core but one.",+ },Definition {name: "inline-budget",setting: Setting::Number {@@ -345,6 +358,9 @@ impl Definition {}}+/// The most threads "compile-threads=0" starts.+const MAX_AUTOMATIC_COMPILE_THREADS: usize = 8;+impl Options {/// The options LIBJS_JIT holds, or the defaults if it is not set. A value with an option that is not one of/// these, or not written as one, is rejected: the process exits with a message that says why. With "help", the@@ -403,6 +419,16 @@ impl Options {help}+ /// How many threads compile asynchronously: `compile_threads`, or with 0, one per processor core but the one the+ /// running code needs, up to `MAX_AUTOMATIC_COMPILE_THREADS`.+ pub fn compile_thread_count(&self) -> usize {+ if self.compile_threads != 0 {+ return self.compile_threads as usize;+ }+ let cores = std::thread::available_parallelism().map_or(1, core::num::NonZeroUsize::get);+ cores.saturating_sub(1).clamp(1, MAX_AUTOMATIC_COMPILE_THREADS)+ }+/// Whether the interpreter collects feedback and counts down tier-up budgets. Only the JIT and the feedback dump/// need either.pub fn collects_feedback(&self) -> bool {@@ -433,7 +459,7 @@ mod tests {#[test]fn every_option_parses() {let options = Options::parse(- "threshold=1,warmup=2,sync,inline-budget=3,inline-max-size=4,inline-depth=0,dump-ir,dump-passes,dump-asm,\+ "threshold=1,warmup=2,sync,compile-threads=9,inline-budget=3,inline-max-size=4,inline-depth=0,dump-ir,dump-passes,dump-asm,\dump-feedback,verify-ir,log-exits,perf-map,coverage=/tmp/coverage,seed=18446744073709551615,\stress-exits=6,stress-osr,stress-registers,random-thresholds,stress-install,stress-invalidate=7,help",)@@ -443,6 +469,7 @@ mod tests {threshold: 1,warmup: 2,sync: true,+ compile_threads: 9,help: true,dump_ir: true,dump_passes: true,@@ -525,7 +552,7 @@ mod tests {assert!(help.contains(&definition.syntax()), "{}", definition.name);}assert!(help.ends_with(- "In effect: LIBJS_JIT=on,threshold=50,warmup=8,inline-budget=250,inline-max-size=30,inline-depth=5,\+ "In effect: LIBJS_JIT=on,threshold=50,warmup=8,compile-threads=0,inline-budget=250,inline-max-size=30,inline-depth=5,\seed=1,stress-exits=0,stress-invalidate=0\n"));}diff --git a/Libraries/LibJS/Rust/src/jit/code.rs b/Libraries/LibJS/Rust/src/jit/code.rsindex 4e6a22e7c78..c9944e748d4 100644--- a/Libraries/LibJS/Rust/src/jit/code.rs+++ b/Libraries/LibJS/Rust/src/jit/code.rs@@ -59,7 +59,7 @@ pub type EntryTrampoline = unsafe extern "C" fn(*const Vm, *mut ExecutionContextpub enum CompileState {/// Not compiled, or the code was discarded.None = 0,- /// A compile job for the executable is running on the compile thread.+ /// A compile job for the executable is running on a compile thread.Queued = 1,Installed = crate::layout::executable::JIT_COMPILE_STATE_INSTALLED,/// The code was discarded while JIT code was still running frames of it. It stays attached (but is not entered)diff --git a/Libraries/LibJS/Rust/src/jit/compile_queue.rs b/Libraries/LibJS/Rust/src/jit/compile_queue.rsindex 2fd78490dc7..e2da5edbc60 100644--- a/Libraries/LibJS/Rust/src/jit/compile_queue.rs+++ b/Libraries/LibJS/Rust/src/jit/compile_queue.rs@@ -4,9 +4,10 @@* SPDX-License-Identifier: BSD-2-Clause*/-//! The compile thread. Only snapshots go to it and only compile results come back: the compiler never sees the heap.+//! The compile threads. Only snapshots go to them and only compile results come back: the compiler never sees the heap.use std::sync::mpsc::{Receiver, Sender, channel};+use std::sync::{Arc, Mutex};use libjs_jit::CompileFailure;use libjs_jit::code::CompiledCode;@@ -14,35 +15,54 @@ use libjs_jit::snapshot::Snapshot;pub type CompileResult = Result<CompiledCode, CompileFailure>;-/// A thread that compiles the snapshots it is sent, one at a time, in order. Dropping the queue lets the thread end-/// once it is done with the job it compiles; the results of abandoned jobs are dropped.+/// Threads that compile the snapshots they are sent, each taking the oldest job no other thread took yet. Jobs finish+/// in any order. Dropping the queue lets the threads end once they are done with the jobs they compile; the results of+/// abandoned jobs are dropped.pub struct CompileQueue {jobs: Sender<(u64, Box<Snapshot>)>,results: Receiver<(u64, CompileResult)>,}impl CompileQueue {- pub fn start() -> Self {+ pub fn start(thread_count: usize) -> Self {let (jobs, job_receiver) = channel::<(u64, Box<Snapshot>)>();+ let job_receiver = Arc::new(Mutex::new(job_receiver));let (result_sender, results) = channel();- std::thread::Builder::new()- .name("LibJS JIT".to_string())- .spawn(move || {- while let Ok((id, snapshot)) = job_receiver.recv() {- let result = libjs_jit::compile(&snapshot);- if result_sender.send((id, result)).is_err() {- return;+ for index in 0..thread_count.max(1) {+ let job_receiver = Arc::clone(&job_receiver);+ let result_sender = result_sender.clone();+ let spawned = std::thread::Builder::new()+ .name("LibJS JIT".to_string())+ .spawn(move || {+ loop {+ // NB: The lock is held only while waiting for a job, so the other threads compile meanwhile.+ let job = job_receiver+ .lock()+ .expect("no compile thread panics while waiting")+ .recv();+ let Ok((id, snapshot)) = job else {+ return;+ };+ let result = libjs_jit::compile(&snapshot);+ if result_sender.send((id, result)).is_err() {+ return;+ }}- }- })- .expect("starting the JIT compile thread");+ });+ // NB: The queue needs one thread. If the process cannot start more, it compiles on those it started.+ if index == 0 {+ spawned.expect("starting a JIT compile thread");+ } else if spawned.is_err() {+ break;+ }+ }Self { jobs, results }}pub fn submit(&self, id: u64, snapshot: Box<Snapshot>) {self.jobs.send((id, snapshot))- .expect("the compile thread runs while the queue lives");+ .expect("the compile threads run while the queue lives");}/// The results of the jobs that finished since the last call, waiting for one to finish if none has. The queue must@@ -51,7 +71,7 @@ impl CompileQueue {let mut finished = vec![self.results.recv()- .expect("the compile thread runs while the queue lives"),+ .expect("the compile threads run while the queue lives"),];finished.extend(self.results.try_iter());finisheddiff --git a/Libraries/LibJS/Rust/src/jit/mod.rs b/Libraries/LibJS/Rust/src/jit/mod.rsindex 62a1a43e0a0..71c94a66b74 100644--- a/Libraries/LibJS/Rust/src/jit/mod.rs+++ b/Libraries/LibJS/Rust/src/jit/mod.rs@@ -6,7 +6,7 @@//! The runtime side of the optimizing JIT: its options, the interpreter tiers executables move through as they get//! warm, the tier-up policy, and the glue between the runtime and the `libjs_jit` compiler: snapshots of executables-//! for compile jobs, the compile thread, installing the code, and entering and leaving it.+//! for compile jobs, the compile threads, installing the code, and entering and leaving it.pub mod allocation;pub mod calls;@@ -117,7 +117,7 @@ impl InterpreterTier {pub const ALL: [InterpreterTier; 4] = [Self::Plain, Self::WarmingUp, Self::Unprofiled, Self::Profiling];}-/// A compile job running on the compile thread. The VM keeps the executable and every cell its snapshot refers to+/// A compile job running on a compile thread. The VM keeps the executable and every cell its snapshot refers to/// alive until the job's code is installed or the job is abandoned.pub struct CompileJob {pub executable: Gc<Executable>,@@ -182,9 +182,9 @@ pub struct JitState {pub(crate) function_environment_free_lists: allocation::FunctionEnvironmentFreeLists,/// The memory the VM's JIT code lives in.code_allocator: Rc<RefCell<CodeAllocator>>,- /// The compile thread, started by the first asynchronous compile job.+ /// The compile threads, started by the first asynchronous compile job.compile_queue: OnceCell<CompileQueue>,- /// The compile jobs that run on the compile thread, by id.+ /// The compile jobs that run on the compile threads, by id.jobs: RefCell<HashMap<u64, CompileJob>>,next_job_id: Cell<u64>,/// The addresses of the runtime functions JIT code calls, looked up the first time a compile job needs them.@@ -370,10 +370,11 @@ impl JitState {}pub(crate) fn compile_queue(&self) -> &CompileQueue {- self.compile_queue.get_or_init(CompileQueue::start)+ self.compile_queue+ .get_or_init(|| CompileQueue::start(self.options.compile_thread_count()))}- /// The compile thread, if a compile job started it.+ /// The compile threads, if a compile job started them.pub(crate) fn started_compile_queue(&self) -> Option<&CompileQueue> {self.compile_queue.get()}diff --git a/Libraries/LibJS/Rust/src/jit/tier_up.rs b/Libraries/LibJS/Rust/src/jit/tier_up.rsindex d81e3d989e5..1a5ab9fc640 100644--- a/Libraries/LibJS/Rust/src/jit/tier_up.rs+++ b/Libraries/LibJS/Rust/src/jit/tier_up.rs@@ -329,7 +329,7 @@ fn finish_compile(}}-/// Compiles `executable`, whose frames run `function`: right away if `sync`, otherwise on the compile thread, whose+/// Compiles `executable`, whose frames run `function`: right away if `sync`, otherwise on a compile thread, whose/// code a later tier-up check installs.fn compile(vm: &Vm,diff --git a/Tests/LibJS/JIT/modes.py b/Tests/LibJS/JIT/modes.pyindex 1d5831a22d0..18aaa075e4d 100644--- a/Tests/LibJS/JIT/modes.py+++ b/Tests/LibJS/JIT/modes.py@@ -59,7 +59,7 @@ MODES = [Mode("async","on,warmup=1,threshold=4,stress-install,seed={seed}",- "Compile on the compile thread, installing the code after a random number of tier-up checks.",+ "Compile on the compile threads, installing the code after a random number of tier-up checks.",),Mode("default", "on", "The JIT with its default options, as the browser runs it."),]