Skip to content

Truly independent web browser

LibJS: Keep compiling code whose exits keep teaching it new sites

Andreas Klingb15b72b95bde
diff --git a/Libraries/LibJS/Rust/src/jit/code.rs b/Libraries/LibJS/Rust/src/jit/code.rs
index f36cff0871e..495830e4f27 100644
--- a/Libraries/LibJS/Rust/src/jit/code.rs
+++ b/Libraries/LibJS/Rust/src/jit/code.rs
@@ -87,6 +87,11 @@ impl CompileState {
pub struct SnapshotExecutable {
pub executable: Gc<Executable>,
pub function: Option<InlinedFunction>,
+ /// How many sites where JIT code exited the executable had recorded when the code was compiled, which the code
+ /// knew of (see `Executable::add_jit_exit_site()`). The sites are only ever appended to.
+ pub known_exit_sites: usize,
+ /// For the compiled executable, how many sites in inlined builtins it had recorded then.
+ pub known_builtin_exit_sites: usize,
}
/// The function object of an inlined executable, which its materialized frames run.
@@ -294,6 +299,11 @@ pub struct ExecutableJitState {
builtin_exit_sites: RefCell<Vec<(u64, u32, ExitKind)>>,
/// How often the executable's code was discarded.
discard_count: Cell<u32>,
+ /// How often in a row the executable's code was discarded without its exits having been at a site the code did not
+ /// know of, so that a recompile would learn nothing from them.
+ fruitless_discard_count: Cell<u32>,
+ /// Whether exits of the executable's code recorded a site it did not know of since its code was last discarded.
+ learned_exit_site: Cell<bool>,
/// Whether the executable is refused once its discarded code is detached, because it was refused while frames
/// still ran that code (see `refuse_jit_compile_once_detached()`).
refused_once_detached: Cell<bool>,
@@ -321,8 +331,16 @@ pub const EXIT_COUNT_BEFORE_DISCARD: u32 = 10;
/// costs more than code that exits as often elsewhere.
pub const EXIT_COUNT_BEFORE_DISCARD_FROM_LOOP: u32 = 5;
-/// An executable whose code was discarded this often is not compiled again.
-pub const MAX_DISCARD_COUNT: u32 = 8;
+/// An executable whose code was discarded this often in a row without its exits teaching it anything is not compiled
+/// again. Discards after exits at sites the code did not know of make progress: each site is recorded once, and
+/// recompiles no longer speculate there, so code that keeps reaching new paths (like a dispatcher whose program moves
+/// on to new phases) keeps being compiled.
+pub const MAX_FRUITLESS_DISCARD_COUNT: u32 = 8;
+
+/// An executable whose code was discarded this often, whatever its exits taught it, is not compiled again either: each
+/// recompile compiles the whole executable, so code that keeps reaching new sites would otherwise cost compile time
+/// without bound.
+pub const MAX_DISCARD_COUNT: u32 = 64;
impl Executable {
pub fn jit_compile_state(&self) -> CompileState {
@@ -398,28 +416,48 @@ impl Executable {
self.jit_state().exit_sites.borrow().clone()
}
- pub fn add_jit_exit_site(&self, site: (u32, ExitKind)) {
+ pub fn jit_exit_site_count(&self) -> usize {
+ self.jit_state().exit_sites.borrow().len()
+ }
+
+ /// Records a site where JIT code exited, and returns its index among the sites.
+ pub fn add_jit_exit_site(&self, site: (u32, ExitKind)) -> usize {
let mut sites = self.jit_state().exit_sites.borrow_mut();
- if !sites.contains(&site) {
- sites.push(site);
+ if let Some(index) = sites.iter().position(|recorded| *recorded == site) {
+ return index;
}
+ sites.push(site);
+ sites.len() - 1
}
pub fn jit_builtin_exit_sites(&self) -> Vec<(u64, u32, ExitKind)> {
self.jit_state().builtin_exit_sites.borrow().clone()
}
- pub fn add_jit_builtin_exit_site(&self, site: (u64, u32, ExitKind)) {
+ pub fn jit_builtin_exit_site_count(&self) -> usize {
+ self.jit_state().builtin_exit_sites.borrow().len()
+ }
+
+ /// Records a site where JIT code exited in an inlined builtin, and returns its index among those sites.
+ pub fn add_jit_builtin_exit_site(&self, site: (u64, u32, ExitKind)) -> usize {
let mut sites = self.jit_state().builtin_exit_sites.borrow_mut();
- if !sites.contains(&site) {
- sites.push(site);
+ if let Some(index) = sites.iter().position(|recorded| *recorded == site) {
+ return index;
}
+ sites.push(site);
+ sites.len() - 1
}
pub fn jit_discard_count(&self) -> u32 {
self.jit_state().discard_count.get()
}
+ /// Notes that an exit of the executable's installed code was at a site the code did not know of, which a
+ /// recompile learns from (see `MAX_FRUITLESS_DISCARD_COUNT`).
+ pub fn note_learned_jit_exit_site(&self) {
+ self.jit_state().learned_exit_site.set(true);
+ }
+
/// Makes new frames of the executable run in its JIT code. Frames of it that run in the interpreter count down
/// `tier_up_budget` from here, and continue in the code at an on-stack replacement entry once it runs out.
pub fn install_jit_code(&self, vm: &Vm, code: Box<JitCode>, tier_up_budget: i32) {
@@ -497,7 +535,17 @@ impl Executable {
super::describe_executable(self)
);
}
- if discard_count >= MAX_DISCARD_COUNT || state.refused_once_detached.get() {
+ if state.learned_exit_site.replace(false) {
+ state.fruitless_discard_count.set(0);
+ } else {
+ state
+ .fruitless_discard_count
+ .set(state.fruitless_discard_count.get() + 1);
+ }
+ if discard_count >= MAX_DISCARD_COUNT
+ || state.fruitless_discard_count.get() >= MAX_FRUITLESS_DISCARD_COUNT
+ || state.refused_once_detached.get()
+ {
super::tier_up::refuse_jit_compile(vm, self);
return;
}
diff --git a/Libraries/LibJS/Rust/src/jit/snapshot.rs b/Libraries/LibJS/Rust/src/jit/snapshot.rs
index cb4dac65e9f..3f0f70733d1 100644
--- a/Libraries/LibJS/Rust/src/jit/snapshot.rs
+++ b/Libraries/LibJS/Rust/src/jit/snapshot.rs
@@ -1241,6 +1241,8 @@ pub fn capture_snapshot(
.map(|entry| SnapshotExecutable {
executable: entry.executable,
function: entry.function,
+ known_exit_sites: entry.executable.jit_exit_site_count(),
+ known_builtin_exit_sites: entry.executable.jit_builtin_exit_site_count(),
})
.collect(),
}
diff --git a/Libraries/LibJS/Rust/src/jit/translate.rs b/Libraries/LibJS/Rust/src/jit/translate.rs
index 6d7e14edb95..87f1473dfe4 100644
--- a/Libraries/LibJS/Rust/src/jit/translate.rs
+++ b/Libraries/LibJS/Rust/src/jit/translate.rs
@@ -559,14 +559,23 @@ pub(super) fn exit(vm: &Vm, root: NonNull<ExecutionContext>, code: &JitCode, ind
}
// NB: Exits in inlined builtins count for the code they were inlined into only.
// NB: Invalidated code was discarded, and its recompile sees that what it depended on no longer holds.
- if kind == libjs_jit::code::ExitKind::Invalidated {
- } else if matches!(
- code.snapshot_executable(frame_state.executable).function,
- Some(InlinedFunction::Builtin(_))
- ) {
- compiled_executable.add_jit_builtin_exit_site((executable.as_ptr() as u64, frame_state.pc, kind));
+ let snapshot_executable = code.snapshot_executable(frame_state.executable);
+ let learned = if kind == libjs_jit::code::ExitKind::Invalidated {
+ false
+ } else if matches!(snapshot_executable.function, Some(InlinedFunction::Builtin(_))) {
+ let index = compiled_executable.add_jit_builtin_exit_site((executable.as_ptr() as u64, frame_state.pc, kind));
+ index >= code.snapshot_executable(0).known_builtin_exit_sites
} else {
- executable.add_jit_exit_site((frame_state.pc, kind));
+ // NB: Sites in inlined callees are their executables', but the compiled code learns from them too.
+ executable.add_jit_exit_site((frame_state.pc, kind)) >= snapshot_executable.known_exit_sites
+ };
+ // NB: What code that was discarded already learns counts for no later code.
+ let is_installed_code = compiled_executable.jit_compile_state() == CompileState::Installed
+ && compiled_executable
+ .jit_code(vm)
+ .is_some_and(|installed| core::ptr::eq(installed, code));
+ if learned && is_installed_code {
+ compiled_executable.note_learned_jit_exit_site();
}
if code.count_exit() >= EXIT_COUNT_BEFORE_DISCARD
diff --git a/Tests/LibJS/Runtime/jit/discarded-code.js b/Tests/LibJS/Runtime/jit/discarded-code.js
index 77a2d5ff570..6d5b0ad6f9b 100644
--- a/Tests/LibJS/Runtime/jit/discarded-code.js
+++ b/Tests/LibJS/Runtime/jit/discarded-code.js
@@ -56,3 +56,76 @@ describe("discarded JIT code", () => {
expect(total).toBe(20 + 499500 + 12497500);
});
});
+
+describe("recompiles after discarded code", () => {
+ test("code that exits where it reaches code that never ran is compiled again", () => {
+ // NB: Like the per-frame step of an emulator, which reaches new branches as the program it runs goes on.
+ const cases = Array.from(
+ { length: 16 },
+ (_, phase) => `case ${phase}: x = (x ^ ${phase}) + ${phase} | 0; break;`
+ );
+ const step = new Function("phase", "x", `switch (phase) { ${cases.join(" ")} } return x;`);
+ jit.prepare(step);
+ for (let i = 0; i < 10; ++i) step(0, i);
+ expect(jit.compile(step)).toBe(jit.enabled);
+ for (let phase = 1; phase < 16; ++phase) {
+ for (let i = 0; i < 20; ++i) expect(step(phase, i)).toBe(((i ^ phase) + phase) | 0);
+ expect(jit.compile(step)).toBe(jit.enabled);
+ }
+ // NB: Exits forced at random checks may come before the ones at sites that never ran, which then go unrecorded.
+ if (!jit.forcesExits) expect(jit.discardCount(step)).toBe(jit.enabled ? 15 : 0);
+ });
+
+ test("code that keeps learning is not compiled anymore after many discards", () => {
+ const cases = Array.from(
+ { length: 80 },
+ (_, phase) => `case ${phase}: x = (x ^ ${phase}) + ${phase} | 0; break;`
+ );
+ const step = new Function("phase", "x", `switch (phase) { ${cases.join(" ")} } return x;`);
+ jit.prepare(step);
+ for (let i = 0; i < 10; ++i) step(0, i);
+ for (let phase = 0; phase < 80; ++phase) {
+ for (let i = 0; i < 20; ++i) expect(step(phase, i)).toBe(((i ^ phase) + phase) | 0);
+ jit.compile(step);
+ }
+ if (jit.enabled && !jit.forcesExits) {
+ expect(jit.discardCount(step)).toBe(64);
+ expect(jit.compile(step)).toBeFalse();
+ }
+ expect(step(79, 1)).toBe(((1 ^ 79) + 79) | 0);
+ });
+
+ test("discards that teach the code something start the count of fruitless discards over", () => {
+ const step = new Function(
+ "phase",
+ "x",
+ "switch (phase) { case 0: return x + 1 | 0; case 1: return x ^ 3; } return x;"
+ );
+ jit.prepare(step);
+ for (let i = 0; i < 10; ++i) step(0, i);
+ for (let i = 0; i < 7; ++i) {
+ expect(jit.compile(step)).toBe(jit.enabled);
+ jit.discard(step);
+ }
+ // The code exits where it reaches the case that never ran, which a recompile learns from.
+ expect(jit.compile(step)).toBe(jit.enabled);
+ for (let i = 0; i < 20; ++i) expect(step(1, i)).toBe(i ^ 3);
+ for (let i = 0; i < 7; ++i) {
+ expect(jit.compile(step)).toBe(jit.enabled);
+ jit.discard(step);
+ }
+ expect(jit.compile(step)).toBe(jit.enabled);
+ });
+
+ test("code discarded again and again without new exits is not compiled anymore", () => {
+ const add = new Function("a", "b", "return a + b;");
+ jit.prepare(add);
+ for (let i = 0; i < 10; ++i) add(i, 1);
+ for (let i = 0; i < 8; ++i) {
+ expect(jit.compile(add)).toBe(jit.enabled);
+ jit.discard(add);
+ }
+ expect(jit.compile(add)).toBeFalse();
+ expect(add(2, 3)).toBe(5);
+ });
+});