Truly independent web browser
LibJS/JIT: Speculate on shapes again once the cache learned them
Andreas Kling480b71934c18
diff --git a/Libraries/LibJS/JIT/ARCHITECTURE.md b/Libraries/LibJS/JIT/ARCHITECTURE.mdindex f09651a519d..1f9e1ad49b7 100644--- a/Libraries/LibJS/JIT/ARCHITECTURE.md+++ b/Libraries/LibJS/JIT/ARCHITECTURE.md@@ -441,7 +441,14 @@ before, loads of the binding stay plain loads; for a captured binding, that holdloads. Closures are counted where they are created (`SharedFunctionInstanceData::closure_count()`),so compiled code only copies closure templates of functions that have several closures already.-To be written: exit reasons, recompiles, the rule that a failed speculation is never repeated.+**Shapes the caches learned.** A speculation that failed is never made again at the same place,+with one exception: a `BadShape` exit at an instruction whose property lookup cache the code+speculated on records how many entries the cache had when the code was compiled. Recompiles leave+the exit out of the sites they avoid once the cache has more (`Executable::jit_exit_sites_for_recompile()`),+since the interpreter added the shapes the code did not know. Each such exit needs a larger cache,+and caches stop growing once megamorphic, so this ends.++To be written: exit reasons, recompiles.## 10. The snapshot and the cachesdiff --git a/Libraries/LibJS/JIT/Rust/src/bytecode/instruction.rs b/Libraries/LibJS/JIT/Rust/src/bytecode/instruction.rsindex 35b810572fa..1d4eed52e3e 100644--- a/Libraries/LibJS/JIT/Rust/src/bytecode/instruction.rs+++ b/Libraries/LibJS/JIT/Rust/src/bytecode/instruction.rs@@ -175,6 +175,22 @@ pub struct DecodedInstruction {pub instruction: Instruction,}+impl Instruction {+ /// The property lookup cache whose entries compiled code speculates on+ /// for this instruction, as shape checks that exit with+ /// `ExitKind::BadShape`.+ pub fn speculated_property_lookup_cache(&self) -> Option<u32> {+ match *self {+ Instruction::GetById { cache, .. }+ | Instruction::PutById { cache, .. }+ | Instruction::GetLength { cache, .. }+ | Instruction::GetByValue { cache, .. }+ | Instruction::PutByValue { cache, .. } => Some(cache),+ _ => None,+ }+ }+}+impl DecodedInstruction {pub fn next_pc(&self) -> u32 {self.pc + self.lengthdiff --git a/Libraries/LibJS/Rust/src/jit/code.rs b/Libraries/LibJS/Rust/src/jit/code.rsindex bbcc9a62151..1c426822a76 100644--- a/Libraries/LibJS/Rust/src/jit/code.rs+++ b/Libraries/LibJS/Rust/src/jit/code.rs@@ -9,19 +9,20 @@use core::cell::{Cell, OnceCell, RefCell};use core::ffi::c_void;-use libjs_jit::bytecode::EnvironmentCoordinate;+use libjs_jit::bytecode::{EnvironmentCoordinate, decode_instruction};pub use libjs_jit::code::INLINED_CALL_SITE_BIT;use libjs_jit::code::{ExitKind, Site};use super::entry_table::{JIT_ENTRY_SLOT_MASK, JitEntryTable, NO_JIT_ENTRY_SLOT};use super::executable_memory::ExecutableMemory;-use crate::bytecode::executable::Executable;+use crate::bytecode::executable::{Executable, PropertyLookupCache, PropertyLookupCacheTier};use crate::gc::visitor::{Trace, Visitor};use crate::interpreter::vm::Vm;use crate::layout::cell::{CellHeader, Gc};use crate::layout::execution_context::ExecutionContext;use crate::layout::function_object::EcmascriptFunctionObject;use crate::layout::object::Object;+use crate::layout::property_lookup_cache::PropertyLookupCacheEntryType;use crate::runtime::native_javascript_backed_function::NativeJavaScriptBackedFunction;/// The status word of what JIT code returns, `libjs_jit::code::JitStatus`.@@ -84,7 +85,7 @@ impl CompileState {/// An executable of a compile job's snapshot, by index. Index 0 is the compiled executable (without a function); the/// others are inlining candidates, whose frames exits materialize.-#[derive(Clone, Copy)]+#[derive(Clone)]pub struct SnapshotExecutable {pub executable: Gc<Executable>,pub function: Option<InlinedFunction>,@@ -93,6 +94,23 @@ pub struct SnapshotExecutable {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 size of each property lookup cache of the executable when the code was compiled (see+ /// `speculated_cache_size()`): how many shapes the code speculated on there.+ pub property_cache_sizes: Box<[u8]>,+}++/// How many entries of a property lookup cache compiled code speculates on, or `u8::MAX` once the cache is megamorphic,+/// so that it no longer grows.+pub fn speculated_cache_size(cache: &PropertyLookupCache) -> u8 {+ if cache.tier() == PropertyLookupCacheTier::Megamorphic {+ return u8::MAX;+ }+ let entries = cache+ .entries()+ .iter()+ .filter(|entry| entry.get().entry_type != PropertyLookupCacheEntryType::Empty)+ .count();+ u8::try_from(entries).expect("caches that are not megamorphic have few entries")}/// The function object of an inlined executable, which its materialized frames run.@@ -331,8 +349,8 @@ impl JitCode {core::mem::take(&mut self.sites)}- pub fn snapshot_executable(&self, index: u32) -> SnapshotExecutable {- self.snapshot_executables[index as usize]+ pub fn snapshot_executable(&self, index: u32) -> &SnapshotExecutable {+ &self.snapshot_executables[index as usize]}/// How often the code exited.@@ -368,8 +386,12 @@ unsafe impl Trace for JitCode {/// The JIT state of an executable that the interpreter and JIT code do not read: they read the fields of its head.#[derive(Default)]pub struct ExecutableJitState {- /// Places where JIT code exited. Recompiles never repeat a speculation of the same kind at the same pc.+ /// Places where JIT code exited. Recompiles never repeat a speculation of the same kind at the same pc, but for+ /// shapes of a property lookup cache that learned more of them since (see `jit_exit_sites_for_recompile()`).exit_sites: RefCell<Vec<(u32, ExitKind)>>,+ /// For the pcs of `exit_sites` where JIT code exited with `ExitKind::BadShape` at an instruction whose property+ /// lookup cache it speculated on: the size the cache had when the last code that exited there was compiled.+ shape_exit_cache_sizes: RefCell<Vec<(u32, u8)>>,/// Places in builtins written in JavaScript where the executable's JIT code exited while running them inlined,/// by the address of the builtin's executable. Builtins are inlined into all their callers, so these are kept per/// caller: what failed in one caller says nothing about the others.@@ -512,6 +534,60 @@ impl Executable {self.jit_state().exit_sites.borrow().clone()}+ /// The sites where JIT code exited that recompiles do not speculate at again (see `jit_exit_sites()`). A bad shape+ /// at an instruction whose property lookup cache grew since the code that exited there was compiled is left out:+ /// the interpreter added the shapes the code did not know to the cache, so recompiles speculate on them all. Each+ /// such exit needs a larger cache, so this ends once the cache is megamorphic.+ pub fn jit_exit_sites_for_recompile(&self) -> Vec<(u32, ExitKind)> {+ let sizes = self.jit_state().shape_exit_cache_sizes.borrow();+ self.jit_exit_sites()+ .into_iter()+ .filter(|&(pc, kind)| {+ if kind != ExitKind::BadShape {+ return true;+ }+ let Some(&(_, size)) = sizes.iter().find(|(site, _)| *site == pc) else {+ return true;+ };+ self.speculated_property_lookup_cache(pc)+ .is_none_or(|cache| speculated_cache_size(cache) <= size)+ })+ .collect()+ }++ /// The property lookup cache that the instruction at `pc` speculates on (see+ /// `Instruction::speculated_property_lookup_cache()`), if it has one.+ fn speculated_property_lookup_cache(&self, pc: u32) -> Option<&PropertyLookupCache> {+ let decoded = decode_instruction(self.bytecode(), pc).ok()?;+ let index = decoded.instruction.speculated_property_lookup_cache()?;+ self.property_lookup_caches().get(index as usize)+ }++ /// Notes that JIT code compiled when the property lookup caches of the executable had `cache_sizes` exited with+ /// `ExitKind::BadShape` at `pc`. Returns whether that code speculated on more shapes there than the code that+ /// exited there before, so that a recompile learns from the exit.+ pub fn note_jit_shape_exit(&self, pc: u32, cache_sizes: &[u8]) -> bool {+ let Some(size) = decode_instruction(self.bytecode(), pc)+ .ok()+ .and_then(|decoded| decoded.instruction.speculated_property_lookup_cache())+ .and_then(|index| cache_sizes.get(index as usize).copied())+ else {+ return false;+ };+ let mut sizes = self.jit_state().shape_exit_cache_sizes.borrow_mut();+ match sizes.iter_mut().find(|(site, _)| *site == pc) {+ Some((_, recorded)) if *recorded >= size => false,+ Some((_, recorded)) => {+ *recorded = size;+ true+ }+ None => {+ sizes.push((pc, size));+ true+ }+ }+ }+pub fn jit_exit_site_count(&self) -> usize {self.jit_state().exit_sites.borrow().len()}diff --git a/Libraries/LibJS/Rust/src/jit/snapshot.rs b/Libraries/LibJS/Rust/src/jit/snapshot.rsindex 38da4c06d97..fc8369598bc 100644--- a/Libraries/LibJS/Rust/src/jit/snapshot.rs+++ b/Libraries/LibJS/Rust/src/jit/snapshot.rs@@ -27,7 +27,7 @@ use super::allocation::{allocation_infos, closure_template_snapshots, closure_templates, function_environment_template,lexical_environment_templates,};-use super::code::{CapturedBindingAccesses, InlinedFunction, SnapshotExecutable};+use super::code::{CapturedBindingAccesses, InlinedFunction, SnapshotExecutable, speculated_cache_size};use super::runtime_info::RAW_NATIVE_FUNCTIONS_RETURN_IN_REGISTERS;use crate::bytecode::executable::{Executable, PropertyLookupCacheEntryData, PropertyLookupCacheTier};use crate::bytecode::feedback::{CallFeedback, CallFeedbackForwarding, call_feedback_flags};@@ -994,7 +994,7 @@ impl SnapshotBuilder<'_> {handler_offset: handler.handler_offset,}).collect(),- exit_sites: executable.jit_exit_sites(),+ exit_sites: executable.jit_exit_sites_for_recompile(),builtin_exit_sites: if entry.function.is_none() {executable.jit_builtin_exit_sites()@@ -1324,6 +1324,12 @@ pub fn capture_snapshot(function: entry.function,known_exit_sites: entry.executable.jit_exit_site_count(),known_builtin_exit_sites: entry.executable.jit_builtin_exit_site_count(),+ property_cache_sizes: entry+ .executable+ .property_lookup_caches()+ .iter()+ .map(speculated_cache_size)+ .collect(),}).collect(),}diff --git a/Libraries/LibJS/Rust/src/jit/translate.rs b/Libraries/LibJS/Rust/src/jit/translate.rsindex d9bf26ece48..3ce5dec91e7 100644--- a/Libraries/LibJS/Rust/src/jit/translate.rs+++ b/Libraries/LibJS/Rust/src/jit/translate.rs@@ -669,7 +669,10 @@ pub(super) fn exit(vm: &Vm, root: NonNull<ExecutionContext>, code: &JitCode, indindex >= code.snapshot_executable(0).known_builtin_exit_sites} else {// 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+ let new_site = executable.add_jit_exit_site((frame_state.pc, kind)) >= snapshot_executable.known_exit_sites;+ let learned_shapes = kind == libjs_jit::code::ExitKind::BadShape+ && executable.note_jit_shape_exit(frame_state.pc, &snapshot_executable.property_cache_sizes);+ new_site || learned_shapes};if learned && is_installed_code(vm, &compiled_executable, code) {compiled_executable.note_learned_jit_exit_site();