Truly independent web browser
LibJS: Look up megamorphic named gets in the VM's keyed cache
Andreas Kling03bed6456cb3
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/named.rs b/Libraries/LibJS/JIT/Rust/src/builder/named.rsindex ad1991d1447..8d0d2d987bf 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/named.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/named.rs@@ -28,12 +28,19 @@ impl GraphBuilder<'_> {/// Builds `GetById` (`Handling::Expanded`): the property the cache has/// for the value (see `Op::ProbePropertyCache`).pub(super) fn build_get_by_id(&mut self, instruction: &Instruction) -> Result<Flow, CompileFailure> {- let Instruction::GetById { dst, base, cache, .. } = *instruction else {+ let Instruction::GetById {+ dst,+ base,+ property,+ cache,+ ..+ } = *instruction+ else {unreachable!("only GetById is built here");};let mut slow_paths = self.start_slow_paths(Some(Repr::Tagged))?;let value = self.read(base)?;- let property = self.probe_property_cache(&mut slow_paths, value, cache);+ let property = self.probe_property_cache(&mut slow_paths, value, cache, property.0);let result = self.join_slow_paths(slow_paths, Some(property));self.write(dst, result.expect("GetById has a value"))?;Ok(Flow::Continue)@@ -86,15 +93,23 @@ impl GraphBuilder<'_> {self.block = iterator_object;}- let return_method = self.probe_property_cache(&mut slow_paths, iterator, cache);+ let return_method = self.probe_property_cache(&mut slow_paths, iterator, cache, u32::MAX);self.branch_to_slow_path(&mut slow_paths, BranchCondition::Nullish, vec![return_method], true);self.join_slow_paths(slow_paths, None);Ok(Flow::Continue)}/// The property that cache `cache` of the instruction has for the value- /// `object`, taking a slow path where it has none.- fn probe_property_cache(&mut self, slow_paths: &mut SlowPaths, object: NodeId, cache: u32) -> NodeId {+ /// `object`, taking a slow path where it has none. `property` is the+ /// index of its name in the property key table, if it has one there (see+ /// `Op::ProbePropertyCache`).+ fn probe_property_cache(+ &mut self,+ slow_paths: &mut SlowPaths,+ object: NodeId,+ cache: u32,+ property: u32,+ ) -> NodeId {// NB: The probe looks up the properties of strings, numbers and// booleans in their prototypes, whose addresses it embeds.let snapshot = &self.function.executable;@@ -108,7 +123,11 @@ impl GraphBuilder<'_> {}let executable = self.function.index;let property = self.emit(- Op::ProbePropertyCache { executable, cache },+ Op::ProbePropertyCache {+ executable,+ cache,+ property,+ },vec![object],Some(Repr::Tagged),);@@ -139,7 +158,7 @@ impl GraphBuilder<'_> {let length = builder.emit(Op::LoadElementsLength, vec![array], Some(Repr::Int32));builder.end_with_length(slow_paths, length);builder.block = named;- let length = builder.probe_property_cache(slow_paths, value, cache);+ let length = builder.probe_property_cache(slow_paths, value, cache, u32::MAX);builder.end_hot_path(slow_paths, vec![length]);} else {let address = builder.emit(Op::StringAddress, vec![value], Some(Repr::Pointer));diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rs b/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rsindex 387d0299aeb..275e69bc030 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rs@@ -131,6 +131,7 @@ fn generate_stub<M: PortableMacroAssembler>(runtime: &RuntimeInfo, construct: boannotations: Vec::new(),block: BlockId(0),deferred_cache_probes: Vec::new(),+ deferred_vm_cache_probes: Vec::new(),leave_arguments: Vec::new(),leave_stubs: Vec::new(),leave_frame: None,diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rsindex d0cd8428100..0d53e66e99e 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs@@ -299,6 +299,7 @@ struct Codegen<'a, M: PortableMacroAssembler> {/// The block being emitted.block: BlockId,deferred_cache_probes: Vec<probes::DeferredCacheProbe>,+ deferred_vm_cache_probes: Vec<probes::DeferredVmCacheProbe>,deferred_allocations: Vec<allocation::DeferredAllocation>,deferred_storage_growths: Vec<named_storage::DeferredStorageGrowth>,/// `InitializeNamed` nodes whose constant the allocation of their object@@ -460,6 +461,7 @@ pub fn generate<M: PortableMacroAssembler>(annotations: Vec::new(),block: BlockId(0),deferred_cache_probes: Vec::new(),+ deferred_vm_cache_probes: Vec::new(),deferred_allocations: Vec::new(),deferred_storage_growths: Vec::new(),absorbed_initializations: Vec::new(),@@ -1816,8 +1818,12 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {}self.masm.jump(exit);}- Op::ProbePropertyCache { executable, cache } => {- self.emit_probe_property_cache(node_id, *executable, *cache)?;+ Op::ProbePropertyCache {+ executable,+ cache,+ property,+ } => {+ self.emit_probe_property_cache(node_id, *executable, *cache, *property)?;}Op::ProbeKeyedCache { executable, cache } => self.emit_probe_keyed_cache(node_id, *executable, *cache)?,Op::ProbeKeyedStore { executable, cache } => self.emit_probe_keyed_store(node_id, *executable, *cache)?,diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/probes.rs b/Libraries/LibJS/JIT/Rust/src/codegen/probes.rsindex 2cdc398a0c3..6c6d88194b6 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/probes.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/probes.rs@@ -14,6 +14,7 @@ mod property;pub(super) use property::CacheRegisters;pub(super) use property::DeferredCacheProbe;+pub(super) use property::DeferredVmCacheProbe;pub(super) use property::PUT_BY_ID_RECORD_BYTES;use super::Codegen;diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/probes/property.rs b/Libraries/LibJS/JIT/Rust/src/codegen/probes/property.rsindex f5b51e02fd9..6c5cbf0e7ce 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/probes/property.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/probes/property.rs@@ -51,6 +51,29 @@ pub(in crate::codegen) struct DeferredCacheProbe {pub(in crate::codegen) miss: Label,}+/// A probe of the VM's keyed caches for a megamorphic named access, out of+/// line: the hit path of the access's own cache stays as short as without+/// it. It starts at `entry`, where the access's own cache had no entry.+pub(in crate::codegen) struct DeferredVmCacheProbe {+ pub(in crate::codegen) node: NodeId,+ pub(in crate::codegen) entry: Label,+ pub(in crate::codegen) probe: VmCacheProbe,+}++/// What a `DeferredVmCacheProbe` does with its arguments, which are those of+/// `emit_vm_named_cache_get()` (and for its lessons, the cache of the get).+pub(in crate::codegen) enum VmCacheProbe {+ Get {+ executable: u32,+ cache: u32,+ name: u64,+ output: Gpr,+ done: Label,+ miss: Label,+ fail: Label,+ },+}+/// The bytes of the record the `PutById` cache probe takes: the base and/// the value.pub(in crate::codegen) const PUT_BY_ID_RECORD_BYTES: u32 = 16;@@ -300,6 +323,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {node: NodeId,executable: u32,cache_index: u32,+ property: u32,) -> Result<(), CompileFailure> {let output = self.output(node);let scratch = self.pinned.scratch;@@ -351,7 +375,17 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {self.masm.bind(is_object);self.emit_unbox_cell(object, base);self.masm.bind(have_object);- self.probe_cache_entry(®isters, executable, cache_index, probe)?;+ // NB: Megamorphic caches see more shapes than their hash tables hold, so the runtime also fills the VM's keyed+ // lookup cache for their names (see `get_with_property_lookup_cache()`).+ let snapshot = &self.executables[executable as usize];+ let vm_cache_name = snapshot+ .property_caches+ .get(cache_index as usize)+ .filter(|cache| cache.kind == PropertyCacheKind::Megamorphic)+ .and_then(|_| snapshot.property_key_names.get(property as usize).copied())+ .filter(|name| *name != 0);+ let vm_cache = vm_cache_name.map(|_| self.masm.new_label());+ self.probe_cache_entry(®isters, executable, cache_index, vm_cache.unwrap_or(probe))?;let present = self.masm.new_label();self.masm.branch32_memory_imm(Condition::NotEqual,@@ -392,10 +426,138 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {self.masm.load64(entry, &property);self.branch_on_tag(Condition::Equal, entry, value::ACCESSOR_TAG, self.pinned.scratch, fail);self.masm.move64(output, entry);+ if let (Some(name), Some(vm_cache)) = (vm_cache_name, vm_cache) {+ self.deferred_vm_cache_probes.push(DeferredVmCacheProbe {+ node,+ entry: vm_cache,+ probe: VmCacheProbe::Get {+ executable,+ cache: cache_index,+ name,+ output,+ done,+ miss: probe,+ fail,+ },+ });+ }self.bind_probe_failure(output, value::EMPTY, failure, done);Ok(())}+ /// Looks up the property whose name has the identity `name` on the+ /// object in the object register in the VM's keyed property lookup+ /// cache, like the runtime's keyed get does: puts the data property it+ /// has (own, or of an unchanged prototype chain), or `undefined` where+ /// the entry says the object and its prototype chain have no such+ /// property, in `output` and jumps to `done`. Jumps to `fail` for+ /// accessors, and to `miss` where the cache has no such entry. Clobbers+ /// the cache registers and the scratch register.+ fn emit_vm_named_cache_get(+ &mut self,+ registers: &CacheRegisters,+ name: u64,+ output: Gpr,+ done: Label,+ miss: Label,+ fail: Label,+ ) {+ let CacheRegisters { object, shape, entry } = *registers;+ let scratch = self.pinned.scratch;+ let layout = self.runtime.layout;+ if layout.keyed_lookup_cache_entries == 0+ || layout.keyed_lookup_cache_prototype == 0+ || layout.keyed_lookup_cache_prototype_chain_validity == 0+ {+ self.masm.jump(miss);+ return;+ }+ self.emit_load_compressed_cell(shape, &Address::new(object, self.runtime.offsets.object_shape as i32));+ // The entry: the top bits of the Fibonacci hash of the shape and the name.+ let entry_size_log2 = layout.keyed_lookup_cache_entry_size.trailing_zeros();+ let bits = layout.keyed_lookup_cache_index_bits;+ self.masm.move_imm64(scratch, u64::from(name as u32));+ self.masm.xor32(scratch, scratch, shape);+ self.masm.mul32_imm(+ scratch,+ scratch,+ layout.property_lookup_cache_megamorphic_hash_multiplier,+ );+ self.masm+ .shr32_imm(scratch, scratch, (32 - bits - entry_size_log2) as u8);+ self.masm+ .and32_imm(scratch, scratch, ((1u32 << bits) - 1) << entry_size_log2);+ self.masm.move_imm64(entry, layout.keyed_lookup_cache_entries);+ self.masm.add64(entry, entry, scratch);+ self.masm.move_imm64(scratch, name);+ self.masm.branch64_memory(+ Condition::NotEqual,+ &Address::new(entry, layout.keyed_lookup_cache_name as i32),+ scratch,+ miss,+ );+ self.masm.branch64_memory(+ Condition::NotEqual,+ &Address::new(entry, layout.keyed_lookup_cache_shape as i32),+ shape,+ miss,+ );+ let expected = Address::new(entry, layout.keyed_lookup_cache_dictionary_generation as i32);+ self.branch_unless_dictionary_generation_is(shape, expected, [scratch, shape], miss);++ let (own, inherited) = (self.masm.new_label(), self.masm.new_label());+ self.masm.load32(+ scratch,+ &Address::new(entry, layout.keyed_lookup_cache_entry_type as i32),+ );+ self.masm.branch32_imm(+ Condition::Equal,+ scratch,+ layout.property_lookup_cache_entry_type_get_own_property as i32,+ own,+ );+ self.masm.branch32_imm(+ Condition::Equal,+ scratch,+ layout.property_lookup_cache_entry_type_get_property_in_prototype_chain as i32,+ inherited,+ );+ self.masm.branch32_imm(+ Condition::NotEqual,+ scratch,+ layout.property_lookup_cache_entry_type_get_missing_property as i32,+ miss,+ );+ let validity = Address::new(entry, layout.keyed_lookup_cache_prototype_chain_validity as i32);+ self.branch_unless_property_absence_applies(object, shape, &validity, miss);+ self.masm.move_imm64(output, value::UNDEFINED);+ self.masm.jump(done);++ // Properties found in a prototype need its chain to be unchanged.+ self.masm.bind(inherited);+ self.masm.load64(shape, &validity);+ self.masm.branch_test64(Condition::Zero, shape, u64::MAX, miss);+ self.branch_unless_prototype_chain_valid(shape, miss);+ self.masm+ .load64(object, &Address::new(entry, layout.keyed_lookup_cache_prototype as i32));++ // NB: Accessors take the slow path, which calls them.+ self.masm.bind(own);+ self.masm.load32(+ scratch,+ &Address::new(entry, layout.keyed_lookup_cache_property_offset as i32),+ );+ self.masm.load64(+ shape,+ &Address::new(object, self.runtime.offsets.object_named_properties as i32),+ );+ self.masm+ .load64(entry, &Address::indexed(shape, scratch, Scale::Eight, 0));+ self.branch_on_tag(Condition::Equal, entry, value::ACCESSOR_TAG, scratch, fail);+ self.masm.move64(output, entry);+ self.masm.jump(done);+ }+/// A `ProbePropertyStore` node: stores like the interpreter's `PutById`/// handler, and also adds properties through `AddOwnProperty` entries./// The most recently used entry is checked first; the entry for the@@ -588,6 +750,95 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {}}+ /// The probes of the VM's keyed caches of megamorphic named accesses, out+ /// of line.+ pub(in crate::codegen) fn emit_deferred_vm_cache_probes(&mut self) -> Result<(), CompileFailure> {+ for deferred in std::mem::take(&mut self.deferred_vm_cache_probes) {+ self.emitting = Some(deferred.node);+ self.masm.bind(deferred.entry);+ let registers = self.cache_registers(deferred.node);+ match deferred.probe {+ VmCacheProbe::Get {+ executable,+ cache,+ name,+ output,+ done,+ miss,+ fail,+ } => {+ let lesson = (self.runtime.remember_vm_cache_get != 0).then(|| self.masm.new_label());+ self.emit_vm_named_cache_get(®isters, name, output, lesson.unwrap_or(done), miss, fail);+ if let Some(lesson) = lesson {+ self.masm.bind(lesson);+ self.emit_vm_cache_lesson(deferred.node, ®isters, executable, cache, name, done)?;+ }+ }+ }+ }+ Ok(())+ }++ /// After a megamorphic named get found its property in the VM's keyed+ /// property lookup cache, having missed the tables of its cache, which+ /// is property lookup cache `cache_index` of `executable`: copies that+ /// entry into the tables (see `remember_vm_cache_get()` of the runtime)+ /// while they take such lessons, so that the get finds the property+ /// inline the next time, and continues at `done` with the value of the+ /// property still in the node's output register, which the call saves.+ /// Clobbers the cache registers and the scratch register.+ fn emit_vm_cache_lesson(+ &mut self,+ node: NodeId,+ registers: &CacheRegisters,+ executable: u32,+ cache_index: u32,+ name: u64,+ done: Label,+ ) -> Result<(), CompileFailure> {+ let layout = self.runtime.layout;+ let CacheRegisters { shape, entry, .. } = *registers;+ // NB: The cache is megamorphic unless something cleared it since.+ self.property_cache_address(entry, executable, cache_index)?;+ self.masm.load64(entry, &Address::new(entry, 0));+ self.masm.move64(shape, entry);+ self.masm+ .and64_imm(shape, shape, !layout.property_lookup_cache_data_pointer_mask);+ self.masm.branch64_imm(+ Condition::NotEqual,+ shape,+ layout.property_lookup_cache_megamorphic_tag as i64,+ done,+ );+ self.masm+ .and64_imm(entry, entry, layout.property_lookup_cache_data_pointer_mask);+ self.masm.load32(+ shape,+ &Address::new(entry, layout.property_lookup_cache_megamorphic_vm_cache_lessons as i32),+ );+ self.masm.branch32_imm(+ Condition::AboveOrEqual,+ shape,+ layout.property_lookup_cache_megamorphic_max_vm_cache_lessons as i32,+ done,+ );++ let arguments = M::ARGUMENT_GPRS;+ let saved = slow_path_saved_registers::<M>().iter().collect::<Vec<_>>();+ self.emit_save_registers(&saved);+ let base = self.input(node, 0);+ if base != arguments[1] {+ self.masm.move64(arguments[1], base);+ }+ self.property_cache_address(arguments[2], executable, cache_index)?;+ self.masm.move_imm64(arguments[3], name);+ self.masm.move64(arguments[0], self.pinned.vm);+ self.masm.call_absolute(self.runtime.remember_vm_cache_get);+ self.emit_restore_registers(&saved, None);+ self.masm.jump(done);+ Ok(())+ }+/// The runtime probes of the cache probe nodes, out of line.pub(in crate::codegen) fn emit_deferred_cache_probes(&mut self) -> Result<(), CompileFailure> {for deferred in std::mem::take(&mut self.deferred_cache_probes) {diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/slow_path_calls.rs b/Libraries/LibJS/JIT/Rust/src/codegen/slow_path_calls.rsindex 5be1725f55c..13921c459f4 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/slow_path_calls.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/slow_path_calls.rs@@ -63,6 +63,7 @@ pub(super) fn slow_path_saved_registers_of<M: PortableMacroAssembler>(allocationimpl<M: PortableMacroAssembler> Codegen<'_, M> {/// The out of line code of nodes, after the last block.pub(super) fn emit_deferred_code(&mut self) -> Result<(), CompileFailure> {+ self.emit_deferred_vm_cache_probes()?;self.emit_deferred_cache_probes()?;self.emit_deferred_allocations();self.emit_deferred_storage_growths();diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs b/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rsindex 89a433c19c3..a7a92838061 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs@@ -1427,6 +1427,7 @@ fn fake_object_layout() -> RuntimeLayout {property_lookup_cache_entry_type_add_own_property: 1,property_lookup_cache_entry_type_get_own_property: 3,property_lookup_cache_entry_type_change_own_property: 2,+ property_lookup_cache_entry_type_get_property_in_prototype_chain: 5,// NB: Fake cells keep their class in their first word: the mask// keeps every bit, so the block of a fake cell is the cell.cell_block_mask: u64::MAX,@@ -1447,6 +1448,7 @@ fn fake_object_layout() -> RuntimeLayout {keyed_lookup_cache_dictionary_generation: 8,keyed_lookup_cache_shape: 16,keyed_lookup_cache_name: 40,+ keyed_lookup_cache_prototype: 0,keyed_lookup_cache_prototype_chain_validity: 0,keyed_lookup_cache_new_shape: 0,property_lookup_cache_polymorphic_tag: 1,@@ -1458,6 +1460,8 @@ fn fake_object_layout() -> RuntimeLayout {property_lookup_cache_megamorphic_tag: 2,property_lookup_cache_megamorphic_primary_entries: 64,property_lookup_cache_megamorphic_secondary_entries: 64 + 16 * 64,+ property_lookup_cache_megamorphic_vm_cache_lessons: 64 + 32 * 64 + 4,+ property_lookup_cache_megamorphic_max_vm_cache_lessons: 16,property_lookup_cache_megamorphic_index_bits: 4,property_lookup_cache_megamorphic_hash_multiplier: 0x9e37_79b9,try_get_by_id_cache: fake_try_get_by_id_cache as *const () as u64,diff --git a/Libraries/LibJS/JIT/Rust/src/ir/dump.rs b/Libraries/LibJS/JIT/Rust/src/ir/dump.rsindex 1ab23f324eb..f770924e5c2 100644--- a/Libraries/LibJS/JIT/Rust/src/ir/dump.rs+++ b/Libraries/LibJS/JIT/Rust/src/ir/dump.rs@@ -361,7 +361,7 @@ fn op_text(layout: &FrameLayout, op: &Op, inputs: &str) -> String {Op::ProbeGlobalCache { cache } | Op::ProbeGlobalStore { cache } => {with_inputs(&format!("{} cache {cache}", op.name()))}- Op::ProbePropertyCache { executable, cache }+ Op::ProbePropertyCache { executable, cache, .. }| Op::ProbeKeyedCache { executable, cache }| Op::ProbeKeyedStore { executable, cache }| Op::ProbePropertyStore { executable, cache } => {diff --git a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs b/Libraries/LibJS/JIT/Rust/src/ir/mod.rsindex 2fd67441d2f..f51121aa649 100644--- a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/ir/mod.rs@@ -1251,10 +1251,14 @@ define_ops! {/// shape, and for strings, numbers and booleans, for the shape of their/// prototype. The empty value if the cache has none, or for other/// values. Probing the cache is one step: its entries change as the- /// interpreter runs.+ /// interpreter runs. `property` is the index of the property's name in+ /// the executable's property key table, or `u32::MAX` if the access+ /// has none there: megamorphic caches with one also look in the VM's+ /// keyed property lookup cache, which the runtime fills for them.ProbePropertyCache {executable: u32,cache: u32,+ property: u32,},/// The value of the own data property (or, for a missing property,/// `undefined`) that the string or symbol input 1 names on the object indiff --git a/Libraries/LibJS/JIT/Rust/src/snapshot.rs b/Libraries/LibJS/JIT/Rust/src/snapshot.rsindex ff21a472872..8e9dfd14142 100644--- a/Libraries/LibJS/JIT/Rust/src/snapshot.rs+++ b/Libraries/LibJS/JIT/Rust/src/snapshot.rs@@ -137,6 +137,9 @@ pub struct ExecutableSnapshot {/// For the compiled function only: its identifier table, as the words of/// its `Utf16FlyString`s, which the executable keeps alive.pub identifiers: Vec<u64>,+ /// The property key table, as the words of the `Utf16FlyString`s of its+ /// string keys (which the executable keeps alive), or 0 for symbols.+ pub property_key_names: Vec<u64>,/// The global variables of the executable's realm that its `GetGlobal`/// and `SetGlobal` instructions access, if code may access them directly.pub globals: Option<GlobalsSnapshot>,@@ -1109,6 +1112,11 @@ pub struct RuntimeInfo {/// `function` makes it, or the empty value if that function is of/// another realm.pub to_object: u64,+ /// `void libjs_jit_remember_vm_cache_get(VM*, u64 base, PropertyLookupCache*,+ /// u64 name)`: copies the entry of the VM's keyed property lookup cache+ /// that a megamorphic named get of `base` found after missing+ /// the tables of its cache into those tables, or 0.+ pub remember_vm_cache_get: u64,/// `u64 libjs_jit_array_create(VM*, u32 length, u64 function)`:/// ArrayCreate(length) as the builtin `function` (the Array constructor)/// makes it, or the empty value if that function is of another realm.@@ -2063,6 +2071,8 @@ pub struct RuntimeLayout {pub property_lookup_cache_entry_type_get_own_property: u32,/// `PropertyLookupCache::Entry::Type::ChangeOwnProperty`.pub property_lookup_cache_entry_type_change_own_property: u32,+ /// `PropertyLookupCache::Entry::Type::GetPropertyInPrototypeChain`.+ pub property_lookup_cache_entry_type_get_property_in_prototype_chain: u32,/// The mask that rounds the address of a cell down to its block, and/// where the block holds the class of its cells. A block of an allocator/// that classes share holds that class with `block_class_tail_tag` set,@@ -2106,6 +2116,10 @@ pub struct RuntimeLayout {pub keyed_lookup_cache_dictionary_generation: u32,pub keyed_lookup_cache_shape: u32,pub keyed_lookup_cache_name: u32,+ /// The offset in an entry of the object (a cell pointer) that holds the+ /// property of a `GetPropertyInPrototypeChain` entry, or 0 if JIT code+ /// does not use such entries.+ pub keyed_lookup_cache_prototype: u32,/// The offset in an entry of the prototype chain validity (a cell/// pointer, or null for shapes without a prototype) that a/// `GetMissingProperty` entry relies on, or 0 if JIT code does not use@@ -2135,6 +2149,13 @@ pub struct RuntimeLayout {pub property_lookup_cache_megamorphic_primary_entries: u32,/// `PropertyLookupCache::MegamorphicData::secondary_entries` (entries).pub property_lookup_cache_megamorphic_secondary_entries: u32,+ /// `PropertyLookupCache::MegamorphicData::vm_cache_lessons` (u32): how+ /// many entries compiled code copied into the tables from the VM's keyed+ /// property lookup cache.+ pub property_lookup_cache_megamorphic_vm_cache_lessons: u32,+ /// `MAX_MEGAMORPHIC_VM_CACHE_LESSONS`: how many such entries a cache+ /// takes.+ pub property_lookup_cache_megamorphic_max_vm_cache_lessons: u32,/// `PropertyLookupCache::megamorphic_index_bits`: the size of both/// megamorphic tables is two to this power.pub property_lookup_cache_megamorphic_index_bits: u32,diff --git a/Libraries/LibJS/Rust/src/bytecode/executable.rs b/Libraries/LibJS/Rust/src/bytecode/executable.rsindex 91c124d4a6c..487bfe9ae85 100644--- a/Libraries/LibJS/Rust/src/bytecode/executable.rs+++ b/Libraries/LibJS/Rust/src/bytecode/executable.rs@@ -234,6 +234,11 @@ pub const MEGAMORPHIC_DATA_TAG: usize = 2;/// How many (shape, key) pairs a megamorphic cache of a keyed access may miss and learn before it gives up (see/// PropertyLookupCache::is_keyed_generic()).const MAX_KEYED_MEGAMORPHIC_MISSES: u32 = 1024;+/// How many entries JIT code may copy into the tables of a megamorphic cache of a named access from the VM's keyed+/// property lookup cache, where it found them after missing the tables (see+/// PropertyLookupCache::take_vm_cache_lesson()). An access whose tables keep missing sees more shapes than they hold,+/// and then only uses the VM's cache.+pub const MAX_MEGAMORPHIC_VM_CACHE_LESSONS: u32 = 16;/// Which tier a property lookup cache is in.#[derive(Clone, Copy, Debug, PartialEq, Eq)]@@ -286,6 +291,8 @@ struct MegamorphicData {secondary_entries: [PropertyLookupCacheEntry; MEGAMORPHIC_SECONDARY_CACHE_SIZE],/// Misses of a keyed access (see MAX_KEYED_MEGAMORPHIC_MISSES).keyed_misses: Cell<u32>,+ /// Entries JIT code copied from the VM's keyed property lookup cache (see MAX_MEGAMORPHIC_VM_CACHE_LESSONS).+ vm_cache_lessons: Cell<u32>,}const _: () = assert!(align_of::<MonomorphicData>() > PROPERTY_LOOKUP_CACHE_DATA_TAG_MASK);@@ -298,6 +305,7 @@ const _: () = assert!(core::mem::offset_of!(MegamorphicData, entry) == 0);/// Where the hash tables of a megamorphic cache's data are, for JIT code that probes them.pub const MEGAMORPHIC_PRIMARY_ENTRIES_OFFSET: usize = core::mem::offset_of!(MegamorphicData, primary_entries);pub const MEGAMORPHIC_SECONDARY_ENTRIES_OFFSET: usize = core::mem::offset_of!(MegamorphicData, secondary_entries);+pub const MEGAMORPHIC_VM_CACHE_LESSONS_OFFSET: usize = core::mem::offset_of!(MegamorphicData, vm_cache_lessons);/// Fibonacci hashing of the low 32 bits of the shape pointer, mixed with the key of keyed caches: the indices are the/// top bits of the product, which takes a multiply and a shift.@@ -394,12 +402,31 @@ impl PropertyLookupCache {self.data_pointer(MEGAMORPHIC_DATA_TAG)}+ /// Whether this megamorphic cache may learn one more entry from the VM's keyed property lookup cache (see+ /// MAX_MEGAMORPHIC_VM_CACHE_LESSONS), counting it if so.+ pub fn take_vm_cache_lesson(&self) -> bool {+ let Some(data) = self.megamorphic_data() else {+ return false;+ };+ let lessons = data.vm_cache_lessons.get();+ if lessons >= MAX_MEGAMORPHIC_VM_CACHE_LESSONS {+ return false;+ }+ data.vm_cache_lessons.set(lessons + 1);+ true+ }+fn set_data<T>(&self, data: Box<T>, tag: usize) {let address = Box::into_raw(data).expose_provenance();assert!(address & PROPERTY_LOOKUP_CACHE_DATA_TAG_MASK == 0);self.data.set(address | tag);}+ /// Whether this cache keeps the entries of more shapes than a polymorphic cache can hold in hash tables.+ pub fn is_megamorphic(&self) -> bool {+ self.megamorphic_data().is_some()+ }+/// Whether this is the cache of a keyed access that saw too many (shape, key) pairs to keep track of. Such a cache/// stays empty, so its accesses go straight to their slow paths.pub fn is_keyed_generic(&self) -> bool {@@ -607,6 +634,7 @@ impl PropertyLookupCache {primary_entries: core::array::from_fn(|_| PropertyLookupCacheEntry::new()),secondary_entries: core::array::from_fn(|_| PropertyLookupCacheEntry::new()),keyed_misses: Cell::new(0),+ vm_cache_lessons: Cell::new(0),});for entry in entries.iter().rev() {let entry = entry.get();@@ -967,6 +995,7 @@ pub struct KeyedPropertyLookupCacheLayout {pub shape_dictionary_generation: u32,pub shape: u32,pub property_name: u32,+ pub prototype: u32,pub prototype_chain_validity: u32,pub new_shape: u32,}@@ -992,7 +1021,11 @@ impl KeyedPropertyLookupCache {/// Fibonacci hash of the low 32 bits of the shape's address and the name's identity, which the interpreter computes/// the same way. Fly strings are interned, so the identity of the name stands in for the hash of its contents.pub fn entry_index_for(shape: Gc<Shape>, property_name: &Utf16FlyString) -> usize {- let hash = (shape.as_ptr().addr() as u32) ^ (property_name.raw_identity() as u32);+ Self::entry_index_for_name_identity(shape, property_name.raw_identity())+ }++ fn entry_index_for_name_identity(shape: Gc<Shape>, name_identity: usize) -> usize {+ let hash = (shape.as_ptr().addr() as u32) ^ (name_identity as u32);(hash.wrapping_mul(MEGAMORPHIC_HASH_MULTIPLIER) >> (32 - KEYED_PROPERTY_LOOKUP_CACHE_INDEX_BITS)) as usize}@@ -1009,6 +1042,7 @@ impl KeyedPropertyLookupCache {shape_dictionary_generation: (lookup + offset_of!(KeyedPropertyLookup, shape_dictionary_generation)) as u32,shape: (lookup + offset_of!(KeyedPropertyLookup, shape)) as u32,property_name: offset_of!(KeyedPropertyLookupCacheEntry, property_name) as u32,+ prototype: (lookup + offset_of!(KeyedPropertyLookup, prototype)) as u32,prototype_chain_validity: (lookup + offset_of!(KeyedPropertyLookup, prototype_chain_validity)) as u32,new_shape: (lookup + offset_of!(KeyedPropertyLookup, new_shape)) as u32,}@@ -1033,6 +1067,19 @@ impl KeyedPropertyLookupCache {.then_some(entry.lookup)}+ /// The entry for `shape` and the name whose identity (see Utf16FlyString::raw_identity()) is `name_identity`, as+ /// JIT code finds it.+ pub fn lookup_by_name_identity(&self, shape: Gc<Shape>, name_identity: usize) -> Option<KeyedPropertyLookup> {+ let entries = self.entries.borrow();+ let entry = &entries[Self::entry_index_for_name_identity(shape, name_identity)];+ (entry.lookup.shape == Some(shape)+ && entry+ .property_name+ .as_ref()+ .is_some_and(|name| name.raw_identity() == name_identity))+ .then_some(entry.lookup)+ }+pub fn set_entry(&self, index: usize, lookup: KeyedPropertyLookup, property_name: &Utf16FlyString) {let mut entries = self.entries.borrow_mut();let entry = &mut entries[index];@@ -1385,6 +1432,10 @@ impl Executable {&self.property_keys[index]}+ pub fn property_keys(&self) -> &[PropertyKey] {+ &self.property_keys+ }+/// The string that `index`, a field of an instruction of this executable, refers to.pub fn get_string(&self, index: &StringTableIndex) -> &Utf16FlyString {&self.code.string_table()[index.index_in(self.bytecode())]diff --git a/Libraries/LibJS/Rust/src/bytecode/property_access.rs b/Libraries/LibJS/Rust/src/bytecode/property_access.rsindex a4ba5398770..c54f7f2153e 100644--- a/Libraries/LibJS/Rust/src/bytecode/property_access.rs+++ b/Libraries/LibJS/Rust/src/bytecode/property_access.rs@@ -80,6 +80,23 @@ fn remember_keyed_lookup(site_cache: &PropertyLookupCache, site_cache_key: u64,});}+/// Copies the entry of the VM's keyed property lookup cache for the shape of `object` and the name whose identity is+/// `name_identity` into `site_cache`, the megamorphic cache of a named get whose compiled code missed its tables and+/// then found that entry. The tables then have it inline the next time, unless the get sees more shapes than they+/// hold (see MAX_MEGAMORPHIC_VM_CACHE_LESSONS).+pub fn remember_vm_cache_get(vm: &Vm, object: Gc<Object>, site_cache: &PropertyLookupCache, name_identity: usize) {+ let shape = object.shape();+ let Some(entry) = vm+ .keyed_property_lookup_cache()+ .lookup_by_name_identity(shape, name_identity)+ else {+ return;+ };+ if entry.shape_key() == Some(ShapeKey::of(shape)) && site_cache.take_vm_cache_lesson() {+ remember_keyed_lookup(site_cache, 0, &entry);+ }+}+/// Gets a property by a key that is not known statically. Lookups of string keys are cached in the VM's keyed property/// lookup cache, and also in `site_cache` under its key if one is given, so that the instruction can find them again/// by the identity of its key Value.@@ -389,6 +406,12 @@ pub fn get_with_property_lookup_cache(if vm.is_static_property_lookup_cache(cache) && !base_obj.is_cacheable_across_realms() {return base_obj.internal_get(vm, property_name, this_value, None, PropertyLookupPhase::OwnProperty);}+ // NB: A megamorphic named access sees more shapes than its hash tables hold, so it also looks in the VM's keyed+ // property lookup cache, which has room for many more.+ // Objects the keyed cache does not take keep using the access's own cache.+ if cache_key == 0 && cache.is_megamorphic() && property_name.is_string() && base_obj.is_cacheable_across_realms() {+ return get_by_value_with_keyed_cache(vm, base_obj, this_value, property_name, Some((cache, 0)));+ }let shape = base_obj.shape();let prototype_chain_validity = shape.prototype()diff --git a/Libraries/LibJS/Rust/src/jit/calls.rs b/Libraries/LibJS/Rust/src/jit/calls.rsindex 8f003601b30..0319bb4e8da 100644--- a/Libraries/LibJS/Rust/src/jit/calls.rs+++ b/Libraries/LibJS/Rust/src/jit/calls.rs@@ -17,10 +17,11 @@ use super::code::EntryStatus;use super::entry_exit::{can_enter_jit_code, enter_jit_code};use super::{frame_of, frames_above};use crate::bytecode::encoding::Operand;-use crate::bytecode::executable::Executable;+use crate::bytecode::executable::{Executable, PropertyLookupCache};use crate::bytecode::instruction::OpCode;use crate::bytecode::instruction_at;use crate::bytecode::op;+use crate::bytecode::property_access::remember_vm_cache_get;use crate::gc::root::MarkedVec;use crate::interpreter::runtime_functions::{Runtime, RuntimeFunctions, SlowPathControl, handle_asm_exception};use crate::interpreter::slow_paths;@@ -1459,6 +1460,30 @@ pub extern "C" fn libjs_jit_to_object(vm: &Vm, primitive: u64, function: u64) ->Value::from_object(primitive.to_object(vm).must()).0}+/// `void libjs_jit_remember_vm_cache_get(VM*, u64 base, PropertyLookupCache*, u64 name)`: copies the entry of the VM's+/// keyed property lookup cache that a megamorphic named get of `base` found after missing the tables of its cache into+/// those tables (see `remember_vm_cache_get()`), if `base` is an object. Runs no code.+///+/// # Safety+///+/// JIT code calls this with its VM, a value, the property lookup cache of the get and the identity of its name.+#[jit_abi]+pub unsafe extern "C" fn libjs_jit_remember_vm_cache_get(+ vm: &Vm,+ base: u64,+ cache: *const PropertyLookupCache,+ name: u64,+) {+ // NB: Gets of the properties of primitives find them on their prototypes, and their caches do not learn them.+ let base = Value::from_bits(base);+ if !base.is_object() {+ return;+ }+ // SAFETY: JIT code passes the address of a live property lookup cache.+ let cache = unsafe { &*cache };+ remember_vm_cache_get(vm, base.as_object(), cache, name as usize);+}+/// `u64 libjs_jit_array_create(VM*, u32 length, u64 function)`: ArrayCreate(length) as the builtin function `function`/// (the Array constructor) makes it, or the empty value if that function is of another realm.///diff --git a/Libraries/LibJS/Rust/src/jit/runtime_info.rs b/Libraries/LibJS/Rust/src/jit/runtime_info.rsindex cf5a91c3184..db3aef21f8c 100644--- a/Libraries/LibJS/Rust/src/jit/runtime_info.rs+++ b/Libraries/LibJS/Rust/src/jit/runtime_info.rs@@ -25,8 +25,9 @@ use super::entry_table::{JIT_ENTRY_SLOT_MASK, JIT_ENTRY_TABLE_OWNERS_OFFSET};use super::offset;use crate::build_configuration::{HEAP_REGION_OFFSET_MASK, PRIMITIVE_STORAGE_CAGE_OFFSET_MASK};use crate::bytecode::executable::{- MAX_NUMBER_OF_SHAPES_TO_REMEMBER, MEGAMORPHIC_DATA_TAG, MEGAMORPHIC_HASH_MULTIPLIER, MEGAMORPHIC_INDEX_BITS,- MEGAMORPHIC_PRIMARY_ENTRIES_OFFSET, MEGAMORPHIC_SECONDARY_ENTRIES_OFFSET,+ MAX_MEGAMORPHIC_VM_CACHE_LESSONS, MAX_NUMBER_OF_SHAPES_TO_REMEMBER, MEGAMORPHIC_DATA_TAG,+ MEGAMORPHIC_HASH_MULTIPLIER, MEGAMORPHIC_INDEX_BITS, MEGAMORPHIC_PRIMARY_ENTRIES_OFFSET,+ MEGAMORPHIC_SECONDARY_ENTRIES_OFFSET, MEGAMORPHIC_VM_CACHE_LESSONS_OFFSET,};use crate::gc::class::{BLOCK_CLASS_OFFSET, BLOCK_CLASS_TAIL_TAG, BLOCK_SIZE, Class, GcCell};use crate::gc::defer_gc::DeferGc;@@ -362,6 +363,8 @@ fn runtime_layout() -> RuntimeLayout {property_lookup_cache_entry_type_add_own_property: PropertyLookupCacheEntryType::AddOwnProperty as u32,property_lookup_cache_entry_type_get_own_property: PropertyLookupCacheEntryType::GetOwnProperty as u32,property_lookup_cache_entry_type_change_own_property: PropertyLookupCacheEntryType::ChangeOwnProperty as u32,+ property_lookup_cache_entry_type_get_property_in_prototype_chain:+ PropertyLookupCacheEntryType::GetPropertyInPrototypeChain as u32,cell_block_mask: !(BLOCK_SIZE as u64 - 1),block_class_offset: offset(BLOCK_CLASS_OFFSET),block_class_tail_tag: BLOCK_CLASS_TAIL_TAG as u64,@@ -383,6 +386,8 @@ fn runtime_layout() -> RuntimeLayout {property_lookup_cache_megamorphic_tag: MEGAMORPHIC_DATA_TAG as u64,property_lookup_cache_megamorphic_primary_entries: offset(MEGAMORPHIC_PRIMARY_ENTRIES_OFFSET),property_lookup_cache_megamorphic_secondary_entries: offset(MEGAMORPHIC_SECONDARY_ENTRIES_OFFSET),+ property_lookup_cache_megamorphic_vm_cache_lessons: offset(MEGAMORPHIC_VM_CACHE_LESSONS_OFFSET),+ property_lookup_cache_megamorphic_max_vm_cache_lessons: MAX_MEGAMORPHIC_VM_CACHE_LESSONS,property_lookup_cache_megamorphic_index_bits: MEGAMORPHIC_INDEX_BITS,property_lookup_cache_megamorphic_hash_multiplier: MEGAMORPHIC_HASH_MULTIPLIER,// NB: Filled in by runtime_info().@@ -397,6 +402,7 @@ fn runtime_layout() -> RuntimeLayout {keyed_lookup_cache_dictionary_generation: 0,keyed_lookup_cache_shape: 0,keyed_lookup_cache_name: 0,+ keyed_lookup_cache_prototype: 0,keyed_lookup_cache_prototype_chain_validity: 0,keyed_lookup_cache_new_shape: 0,}@@ -492,6 +498,7 @@ pub fn runtime_info(layout.keyed_lookup_cache_dictionary_generation = keyed_lookup_cache.shape_dictionary_generation;layout.keyed_lookup_cache_shape = keyed_lookup_cache.shape;layout.keyed_lookup_cache_name = keyed_lookup_cache.property_name;+ layout.keyed_lookup_cache_prototype = keyed_lookup_cache.prototype;layout.keyed_lookup_cache_prototype_chain_validity = keyed_lookup_cache.prototype_chain_validity;layout.keyed_lookup_cache_new_shape = keyed_lookup_cache.new_shape;layout.single_ascii_character_strings = vm.single_ascii_character_strings_address();@@ -547,6 +554,7 @@ pub fn runtime_info(helper_calls: HelperCallAddresses(super::helper_calls::address),float64_functions: Float64FunctionAddresses(super::calls::float64_function_address),to_object: jit_function_address!(super::calls::libjs_jit_to_object),+ remember_vm_cache_get: jit_function_address!(super::calls::libjs_jit_remember_vm_cache_get),array_create: jit_function_address!(super::calls::libjs_jit_array_create),intrinsic_helpers: IntrinsicHelpers {has_own_property: jit_function_address!(super::intrinsics::libjs_jit_has_own_property),diff --git a/Libraries/LibJS/Rust/src/jit/snapshot.rs b/Libraries/LibJS/Rust/src/jit/snapshot.rsindex 0c0ffb8b5b9..26c664d87c6 100644--- a/Libraries/LibJS/Rust/src/jit/snapshot.rs+++ b/Libraries/LibJS/Rust/src/jit/snapshot.rs@@ -1349,6 +1349,17 @@ impl SnapshotBuilder<'_> {} else {Vec::new()},+ property_key_names: executable+ .property_keys()+ .iter()+ .map(|key| {+ if key.is_string() {+ key.as_string().raw_identity() as u64+ } else {+ 0+ }+ })+ .collect(),}}diff --git a/Tests/LibJS/JIT/programs/megamorphic-named-gets.js b/Tests/LibJS/JIT/programs/megamorphic-named-gets.jsnew file mode 100644index 00000000000..55ddc82f983--- /dev/null+++ b/Tests/LibJS/JIT/programs/megamorphic-named-gets.js@@ -0,0 +1,52 @@+// Named gets that see more shapes than their caches hold find properties in the VM's keyed property lookup cache:+// own properties, properties of the prototype chain, missing properties and getters, of objects, dictionaries and+// primitives, while the prototypes change under them.+const proto = { inherited: "p" };+function make(i) {+ const o = Object.create(proto);+ o["k" + (i % 40)] = i;+ if (i % 3 === 0) o.own = "o" + i;+ if (i % 7 === 0)+ Object.defineProperty(o, "own", {+ get() {+ return "g" + i;+ },+ configurable: true,+ });+ if (i % 11 === 0) {+ o.gone = 1;+ delete o.gone;+ }+ return o;+}++function read(o) {+ return o.own + "/" + o.inherited + "/" + o.missing;+}++const objects = [];+for (let i = 0; i < 80; i++) objects.push(make(i));+const primitives = ["str", 1.5, 7, true];+let out = [];+for (let round = 0; round < 60; round++) {+ if (round === 20) proto.inherited = "changed";+ if (round === 30) proto.missing = "now here";+ if (round === 40) delete proto.missing;+ if (round === 45)+ Object.defineProperty(proto, "inherited", {+ get() {+ return "getter";+ },+ configurable: true,+ });+ if (round === 50) String.prototype.own = "string own";+ let s = "";+ for (const o of objects) s += read(o) + ",";+ for (const p of primitives) s += read(p) + ",";+ out.push(s);+}+let hash = 0;+for (const c of out.join("|")) hash = (hash * 31 + c.charCodeAt(0)) | 0;+print(out[0].slice(0, 200));+print(out[59].slice(-200));+print(hash);