Skip to content

Truly independent web browser

LibJS/JIT: Stop walking the stack for every remembered frame on exits

Andreas Klingd026b6427516
diff --git a/Libraries/LibJS/Rust/src/jit/code.rs b/Libraries/LibJS/Rust/src/jit/code.rs
index f73fcf64b17..bb947bd5d6d 100644
--- a/Libraries/LibJS/Rust/src/jit/code.rs
+++ b/Libraries/LibJS/Rust/src/jit/code.rs
@@ -9,7 +9,7 @@
use core::cell::{Cell, OnceCell, RefCell};
use core::ffi::c_void;
use core::ops::ControlFlow;
-use core::ptr::NonNull;
+use std::collections::HashMap;
use libjs_jit::bytecode::{EnvironmentCoordinate, decode_instruction};
pub use libjs_jit::code::INLINED_CALL_SITE_BIT;
@@ -136,8 +136,11 @@ pub struct JitCode {
exit_count: Cell<u32>,
/// The frames of the executable running in the interpreter after the code exited into them or was installed
/// in them, and how many more tier-up checks each may make at back edges from where it reaches no on-stack
- /// replacement entry before the code is discarded. Frame addresses are identities only, never dereferenced.
- interpreted_frames: RefCell<Vec<(usize, u32)>>,
+ /// replacement entry before the code is discarded, by frame id (see Vm::frame_id_of()). Unlike frame addresses,
+ /// ids are never reused by later frames.
+ interpreted_frames: RefCell<HashMap<u64, u32>>,
+ /// How many frames `interpreted_frames` holds before forget_inactive_interpreted_frames() looks for returned ones.
+ interpreted_frame_count_to_forget_at: Cell<usize>,
memory: ExecutableMemory,
entry: JitEntry,
sites: Vec<Site>,
@@ -208,7 +211,8 @@ impl JitCode {
.collect();
Self {
exit_count: Cell::new(0),
- interpreted_frames: RefCell::new(Vec::new()),
+ interpreted_frames: RefCell::new(HashMap::new()),
+ interpreted_frame_count_to_forget_at: Cell::new(MIN_INTERPRETED_FRAME_COUNT_TO_FORGET_AT),
memory,
entry,
sites,
@@ -370,41 +374,43 @@ impl JitCode {
/// Notes that `frame`, a frame of the code's executable, runs in the interpreter after the code exited into it or
/// was installed in it, and may make `checks` tier-up checks at back edges from where it reaches no on-stack
/// replacement entry before the code is discarded.
- pub fn note_interpreted_frame(&self, frame: NonNull<ExecutionContext>, checks: u32) {
- let identity = frame.as_ptr() as usize;
- let mut frames = self.interpreted_frames.borrow_mut();
- if let Some((_, left)) = frames.iter_mut().find(|(frame, _)| *frame == identity) {
- *left = checks;
- } else {
- frames.push((identity, checks));
- }
+ pub fn note_interpreted_frame(&self, vm: &Vm, frame: &ExecutionContext, checks: u32) {
+ self.interpreted_frames
+ .borrow_mut()
+ .insert(vm.frame_id_of(frame), checks);
}
- /// Forgets returned frames before an exit records another one, so a long-lived callee's code cannot accumulate
- /// identities of frames materialized by exits from many different inlined callers.
+ /// Forgets frames that returned, so that a long-lived callee's code cannot accumulate the ids of frames
+ /// materialized by exits from many different inlined callers. Finding the live frames walks the stack, so it
+ /// only happens once the code remembers twice as many frames as were live the last time: unwinding a deep
+ /// recursion exits in every frame, and a walk at each exit made that quadratic in the depth.
pub fn forget_inactive_interpreted_frames(&self, vm: &Vm) {
- self.interpreted_frames.borrow_mut().retain(|(identity, _)| {
- let mut live = false;
- vm.for_each_live_execution_context(|frame| {
- if core::ptr::from_ref(frame) as usize == *identity {
- live = true;
- ControlFlow::Break(())
- } else {
- ControlFlow::Continue(())
- }
- });
- live
+ let mut frames = self.interpreted_frames.borrow_mut();
+ if frames.len() < self.interpreted_frame_count_to_forget_at.get() {
+ return;
+ }
+ let mut live_frames = HashMap::new();
+ vm.for_each_live_execution_context(|frame| {
+ if let Some(checks) = frames.remove(&frame.frame_id.get()) {
+ live_frames.insert(frame.frame_id.get(), checks);
+ }
+ if frames.is_empty() {
+ ControlFlow::Break(())
+ } else {
+ ControlFlow::Continue(())
+ }
});
+ *frames = live_frames;
+ self.interpreted_frame_count_to_forget_at
+ .set((frames.len() * 2).max(MIN_INTERPRETED_FRAME_COUNT_TO_FORGET_AT));
}
/// Counts a tier-up check of `frame` at a back edge from where it reaches no on-stack replacement entry, and
/// returns whether the frame made all it may. Other frames that run in the interpreter finish there like before.
- pub fn count_fruitless_loop_check(&self, frame: NonNull<ExecutionContext>) -> bool {
+ pub fn count_fruitless_loop_check(&self, frame: &ExecutionContext) -> bool {
let mut frames = self.interpreted_frames.borrow_mut();
- let Some((_, left)) = frames
- .iter_mut()
- .find(|(identity, _)| *identity == frame.as_ptr() as usize)
- else {
+ // NB: Frames without an id were never noted.
+ let Some(left) = frames.get_mut(&frame.frame_id.get()) else {
return false;
};
*left = left.saturating_sub(1);
@@ -482,6 +488,9 @@ pub const FRUITLESS_LOOP_CHECKS_AFTER_EXIT: u32 = 8;
/// rather than at a loop nested in others, where the code optimizes less.
pub const FRUITLESS_LOOP_CHECKS_AFTER_INSTALL: u32 = 256;
+/// How many frames JIT code remembers running in the interpreter at least before it looks for returned ones to forget.
+const MIN_INTERPRETED_FRAME_COUNT_TO_FORGET_AT: usize = 64;
+
/// 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
diff --git a/Libraries/LibJS/Rust/src/jit/entry_exit.rs b/Libraries/LibJS/Rust/src/jit/entry_exit.rs
index 1e4176d0123..c88ece5624b 100644
--- a/Libraries/LibJS/Rust/src/jit/entry_exit.rs
+++ b/Libraries/LibJS/Rust/src/jit/entry_exit.rs
@@ -97,7 +97,7 @@ pub fn enter_jit_code_at_loop(vm: &Vm, frame: NonNull<ExecutionContext>, pc: u32
} else if !code.may_reach_osr_entry_from(pc)
&& (runs_once
|| code.exit_count() >= EXIT_COUNT_BEFORE_DISCARD_FROM_LOOP
- || code.count_fruitless_loop_check(frame))
+ || code.count_fruitless_loop_check(frame_ref))
{
// NB: The frame may have exited into this loop, and no later iteration of a loop it is in reaches an entry.
// Once the code is detached, a later check here compiles the executable again, with what the exits
diff --git a/Libraries/LibJS/Rust/src/jit/tier_up.rs b/Libraries/LibJS/Rust/src/jit/tier_up.rs
index cfc754c08d0..f6e3c6725ac 100644
--- a/Libraries/LibJS/Rust/src/jit/tier_up.rs
+++ b/Libraries/LibJS/Rust/src/jit/tier_up.rs
@@ -373,7 +373,7 @@ fn install(
// past the loop the code has an on-stack replacement entry at.
vm.for_each_live_execution_context(|frame| {
if !frame.runs_jit_code.get() && frame.executable.get().is_some() && executable_of(frame) == executable {
- code.note_interpreted_frame(NonNull::from(frame), FRUITLESS_LOOP_CHECKS_AFTER_INSTALL);
+ code.note_interpreted_frame(vm, frame, FRUITLESS_LOOP_CHECKS_AFTER_INSTALL);
}
ControlFlow::Continue(())
});
diff --git a/Libraries/LibJS/Rust/src/jit/translate.rs b/Libraries/LibJS/Rust/src/jit/translate.rs
index 426b74fb0f0..2819f1a2962 100644
--- a/Libraries/LibJS/Rust/src/jit/translate.rs
+++ b/Libraries/LibJS/Rust/src/jit/translate.rs
@@ -667,7 +667,7 @@ pub(super) fn exit(vm: &Vm, root: NonNull<ExecutionContext>, code: &JitCode, ind
loop {
if let Some(frame_code) = executable_of(frame_of(frame)).jit_code(vm) {
frame_code.forget_inactive_interpreted_frames(vm);
- frame_code.note_interpreted_frame(frame, FRUITLESS_LOOP_CHECKS_AFTER_EXIT);
+ frame_code.note_interpreted_frame(vm, frame_of(frame), FRUITLESS_LOOP_CHECKS_AFTER_EXIT);
}
if frame == root {
break;
diff --git a/Tests/LibJS/Runtime/jit/regress/deep-recursion-exits.js b/Tests/LibJS/Runtime/jit/regress/deep-recursion-exits.js
new file mode 100644
index 00000000000..2853f882bcc
--- /dev/null
+++ b/Tests/LibJS/Runtime/jit/regress/deep-recursion-exits.js
@@ -0,0 +1,18 @@
+// Unwinding a deep recursion that catches the stack overflow exits compiled code in every frame, at an addition that
+// never ran before. Each exit looked for the frames its code remembered among all live frames, one stack walk per
+// remembered frame, so measuring the stack depth like this took minutes.
+
+test("measuring the stack depth with a recursion that catches the stack overflow finishes", () => {
+ function depth(warm) {
+ if (warm) return 0;
+ try {
+ return 1 + depth(false);
+ } catch {
+ return 1;
+ }
+ }
+ jit.prepare(depth);
+ depth(true);
+ expect(jit.compile(depth)).toBe(jit.enabled);
+ expect(depth(false)).toBeGreaterThan(1000);
+});