Skip to content

Truly independent web browser

LibJS: Make megamorphic named puts through the VM's keyed store cache

Andreas Kling7908f4990df2
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/named.rs b/Libraries/LibJS/JIT/Rust/src/builder/named.rs
index 8d0d2d987bf..56399ca5eb7 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/named.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/named.rs
@@ -17,6 +17,7 @@ use super::GraphBuilder;
use super::checks::SlowPaths;
use crate::CompileFailure;
use crate::bytecode::Instruction;
+use crate::bytecode::PUT_KIND_NORMAL;
use crate::code::Dependency;
use crate::code::Repr;
use crate::ir::BranchCondition;
@@ -49,15 +50,27 @@ impl GraphBuilder<'_> {
/// Builds `PutById` (`Handling::Expanded`): stores and additions the
/// cache has for objects.
pub(super) fn build_put_by_id(&mut self, instruction: &Instruction) -> Result<Flow, CompileFailure> {
- let Instruction::PutById { base, src, cache, .. } = *instruction else {
+ let Instruction::PutById {
+ base,
+ property,
+ src,
+ kind,
+ cache,
+ } = *instruction
+ else {
unreachable!("only PutById is built here");
};
let mut slow_paths = self.start_slow_paths(None)?;
let object = self.read(base)?;
let value = self.read(src)?;
let executable = self.function.index;
+ let property = if kind == PUT_KIND_NORMAL { property.0 } else { u32::MAX };
let stored = self.emit(
- Op::ProbePropertyStore { executable, cache },
+ Op::ProbePropertyStore {
+ executable,
+ cache,
+ property,
+ },
vec![object, value],
Some(Repr::Bool),
);
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
index 0d53e66e99e..120e0d1f4ad 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
@@ -1830,8 +1830,12 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
Op::ProbeGlobalCache { cache } => self.emit_probe_global_cache(node_id, *cache)?,
Op::ProbeHasProperty { own } => self.emit_probe_has_property(node_id, *own),
Op::ProbeGlobalStore { cache } => self.emit_probe_global_store(node_id, *cache)?,
- Op::ProbePropertyStore { executable, cache } => {
- self.emit_probe_property_store(node_id, *executable, *cache)?;
+ Op::ProbePropertyStore {
+ executable,
+ cache,
+ property,
+ } => {
+ self.emit_probe_property_store(node_id, *executable, *cache, *property)?;
}
Op::CallSlowPath {
opcode,
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/probes/keyed.rs b/Libraries/LibJS/JIT/Rust/src/codegen/probes/keyed.rs
index e4321a6612a..5e29b4f304f 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/probes/keyed.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/probes/keyed.rs
@@ -26,6 +26,15 @@ use crate::ir::NodeId;
use crate::ir::value;
use crate::snapshot::PropertyCacheKind;
+/// The name a lookup in a VM-wide keyed cache is for: the string in a
+/// register, or a name whose identity (the storage word of its fly string)
+/// is known when compiling.
+#[derive(Debug, Clone, Copy)]
+pub(in crate::codegen) enum KeyName {
+ Value(Gpr),
+ Identity(u64),
+}
+
impl<M: PortableMacroAssembler> Codegen<'_, M> {
/// Looks up the own data property that the string `key` names on the
/// object in `base` in the VM's keyed property lookup cache, like the
@@ -48,7 +57,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
let missing = (layout.keyed_lookup_cache_prototype_chain_validity != 0).then(|| self.masm.new_label());
let Some(property) = self.emit_vm_keyed_cache_probe(
base,
- key,
+ KeyName::Value(key),
&registers,
layout.keyed_lookup_cache_entries,
entry_type,
@@ -84,18 +93,18 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
self.masm.jump(done);
}
- /// Stores `source` into the writable own data property that the string
- /// `key` names on the object in `base`, or adds it, if the VM's keyed
+ /// Stores `source` into the writable own data property that `key` names
+ /// on the object in `base`, or adds it, if the VM's keyed
/// property store cache has the change or the addition (see
/// `RuntimeLayout::keyed_store_cache_entries`), and jumps to `done`, or
/// jumps to `miss`. Uses `storage` for additions, and clobbers the cache
/// registers and the scratch register.
#[allow(clippy::too_many_arguments)]
- fn emit_keyed_store_cache_put(
+ pub(super) fn emit_keyed_store_cache_put(
&mut self,
node: NodeId,
base: Gpr,
- key: Gpr,
+ key: KeyName,
source: Gpr,
registers: CacheRegisters,
storage: Gpr,
@@ -140,7 +149,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
self.masm.jump(done);
}
- /// Finds the entry for the string `key` and the shape of the object in
+ /// Finds the entry for `key` and the shape of the object in
/// `base` in a VM-wide keyed cache with `entries` (laid out like the
/// keyed property lookup cache's), with `entry_type` and the shape's
/// dictionary generation, and returns the address of the named property
@@ -154,7 +163,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
fn emit_vm_keyed_cache_probe(
&mut self,
base: Gpr,
- key: Gpr,
+ key: KeyName,
registers: &CacheRegisters,
entries: u64,
entry_type: u32,
@@ -187,7 +196,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
Some(Address::indexed(shape, scratch, Scale::Eight, 0))
}
- /// Finds the entry for the string `key` and the shape of the object in
+ /// Finds the entry for `key` and the shape of the object in
/// `base` in a VM-wide keyed cache with `entries` (laid out like the
/// keyed property lookup cache's), for the shape's dictionary
/// generation, and puts its address in the object register and the
@@ -197,7 +206,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
pub(in crate::codegen) fn emit_vm_keyed_cache_entry(
&mut self,
base: Gpr,
- key: Gpr,
+ key: KeyName,
registers: &CacheRegisters,
entries: u64,
miss: Label,
@@ -212,10 +221,15 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
// The identity of a string's name is the word of its storage, if that is a fly string; no entry has the
// storage word of another string.
let name = entry;
- self.branch_on_tag(Condition::NotEqual, key, value::STRING_TAG, scratch, miss);
- self.emit_unbox_cell(name, key);
- self.masm
- .load64(name, &Address::new(name, layout.primitive_string_storage as i32));
+ match key {
+ KeyName::Value(key) => {
+ self.branch_on_tag(Condition::NotEqual, key, value::STRING_TAG, scratch, miss);
+ self.emit_unbox_cell(name, key);
+ self.masm
+ .load64(name, &Address::new(name, layout.primitive_string_storage as i32));
+ }
+ KeyName::Identity(identity) => self.masm.move_imm64(name, identity),
+ }
self.emit_unbox_cell(object, base);
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.
@@ -554,7 +568,16 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
self.masm.jump(stored);
self.masm.bind(store_cache);
- self.emit_keyed_store_cache_put(node, base, key, source, registers, storage, fail, stored);
+ self.emit_keyed_store_cache_put(
+ node,
+ base,
+ KeyName::Value(key),
+ source,
+ registers,
+ storage,
+ fail,
+ stored,
+ );
self.masm.bind(stored);
self.masm.move_imm32(output, 1);
self.bind_probe_failure(output, 0, failure, done);
@@ -605,7 +628,13 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
if !own {
self.emit_has_element(object, key, &registers, output, probe, done);
}
- if self.emit_vm_keyed_cache_entry(object, key, &registers, layout.keyed_lookup_cache_entries, probe) {
+ if self.emit_vm_keyed_cache_entry(
+ object,
+ KeyName::Value(key),
+ &registers,
+ layout.keyed_lookup_cache_entries,
+ probe,
+ ) {
let (entry, absent) = (registers.object, self.masm.new_label());
self.masm.branch32_memory_imm(
Condition::NotEqual,
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/probes/property.rs b/Libraries/LibJS/JIT/Rust/src/codegen/probes/property.rs
index 6c5cbf0e7ce..cf268bf0d7e 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/probes/property.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/probes/property.rs
@@ -12,6 +12,7 @@
use super::super::Codegen;
use super::super::checked_i32;
use super::super::slow_path_calls::slow_path_saved_registers;
+use super::keyed::KeyName;
use super::megamorphic::MegamorphicKey;
use crate::CompileFailure;
use crate::asm::Address;
@@ -61,7 +62,8 @@ pub(in crate::codegen) struct DeferredVmCacheProbe {
}
/// 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).
+/// `emit_vm_named_cache_get()` (and for its lessons, the cache of the get) for
+/// gets and of `emit_keyed_store_cache_put()` for puts.
pub(in crate::codegen) enum VmCacheProbe {
Get {
executable: u32,
@@ -72,6 +74,14 @@ pub(in crate::codegen) enum VmCacheProbe {
miss: Label,
fail: Label,
},
+ Put {
+ base: Gpr,
+ name: u64,
+ source: Gpr,
+ storage: Gpr,
+ miss: Label,
+ stored: Label,
+ },
}
/// The bytes of the record the `PutById` cache probe takes: the base and
@@ -375,15 +385,9 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
self.masm.bind(is_object);
self.emit_unbox_cell(object, base);
self.masm.bind(have_object);
- // 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);
+ // NB: The runtime also fills the VM's keyed lookup cache for the names of megamorphic caches (see
+ // `get_with_property_lookup_cache()`).
+ let vm_cache_name = self.megamorphic_cache_name(executable, cache_index, property);
let vm_cache = vm_cache_name.map(|_| self.masm.new_label());
self.probe_cache_entry(&registers, executable, cache_index, vm_cache.unwrap_or(probe))?;
let present = self.masm.new_label();
@@ -445,6 +449,21 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
Ok(())
}
+ /// The identity of the name at index `property` of the property key
+ /// table of `executable` (see `Op::ProbePropertyCache`), if property
+ /// lookup cache `cache_index` was megamorphic: such caches see more
+ /// shapes than their hash tables hold, so their accesses also look in
+ /// the VM's keyed caches.
+ fn megamorphic_cache_name(&self, executable: u32, cache_index: u32, property: u32) -> Option<u64> {
+ let snapshot = &self.executables[executable as usize];
+ 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)
+ }
+
/// 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
@@ -570,6 +589,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
node: NodeId,
executable: u32,
cache_index: u32,
+ name_index: u32,
) -> Result<(), CompileFailure> {
let scratch = self.pinned.scratch;
let layout = self.runtime.layout;
@@ -638,7 +658,9 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
// The entry for the object's shape among the others.
self.masm.bind(others);
- self.probe_cache_entry(&registers, executable, cache_index, probe)?;
+ let vm_cache_name = self.megamorphic_cache_name(executable, cache_index, name_index);
+ let vm_cache = vm_cache_name.map(|_| self.masm.new_label());
+ self.probe_cache_entry(&registers, executable, cache_index, vm_cache.unwrap_or(probe))?;
self.masm.branch32_memory_imm(
Condition::NotEqual,
&Address::new(entry, layout.property_lookup_cache_entry_type as i32),
@@ -649,6 +671,20 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
let storage = self.temp(node, 3);
let fields = self.site_addition_entry_fields();
self.emit_add_own_property(node, &registers, fields, source, storage, probe);
+ 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::Put {
+ base,
+ name,
+ source,
+ storage,
+ miss: probe,
+ stored,
+ },
+ });
+ }
self.masm.bind(stored);
self.masm.move_imm32(output, 1);
self.bind_probe_failure(output, 0, failure, done);
@@ -774,6 +810,17 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
self.emit_vm_cache_lesson(deferred.node, &registers, executable, cache, name, done)?;
}
}
+ VmCacheProbe::Put {
+ base,
+ name,
+ source,
+ storage,
+ miss,
+ stored,
+ } => {
+ let key = KeyName::Identity(name);
+ self.emit_keyed_store_cache_put(deferred.node, base, key, source, registers, storage, miss, stored);
+ }
}
}
Ok(())
diff --git a/Libraries/LibJS/JIT/Rust/src/ir/dump.rs b/Libraries/LibJS/JIT/Rust/src/ir/dump.rs
index f770924e5c2..07dd5e72fa2 100644
--- a/Libraries/LibJS/JIT/Rust/src/ir/dump.rs
+++ b/Libraries/LibJS/JIT/Rust/src/ir/dump.rs
@@ -364,7 +364,7 @@ fn op_text(layout: &FrameLayout, op: &Op, inputs: &str) -> String {
Op::ProbePropertyCache { executable, cache, .. }
| Op::ProbeKeyedCache { executable, cache }
| Op::ProbeKeyedStore { executable, cache }
- | Op::ProbePropertyStore { executable, cache } => {
+ | Op::ProbePropertyStore { executable, cache, .. } => {
let cache = if *executable == 0 {
format!("cache {cache}")
} else {
diff --git a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs b/Libraries/LibJS/JIT/Rust/src/ir/mod.rs
index f51121aa649..1de5ad0ed47 100644
--- a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/ir/mod.rs
@@ -1276,10 +1276,15 @@ define_ops! {
/// input 0 (or adds it) that an entry of property lookup cache `cache`
/// of executable `executable` has for the object's shape, like the
/// interpreter's `PutById` handler, as a `Repr::Bool` telling whether it
- /// did. Other values than objects are not stored to.
+ /// did. Other values than objects are not stored to. `property` is the
+ /// index of the property's name in the executable's property key table,
+ /// or `u32::MAX` for puts of another kind than a normal one:
+ /// megamorphic caches with one also look in the VM's keyed store cache,
+ /// which the runtime fills for them.
ProbePropertyStore {
executable: u32,
cache: u32,
+ property: u32,
},
/// Stores input 2 into the writable own data property that the string or
/// symbol input 1 names on the object in input 0 (or adds it), where
diff --git a/Libraries/LibJS/Rust/src/interpreter/slow_paths/property_access.rs b/Libraries/LibJS/Rust/src/interpreter/slow_paths/property_access.rs
index 29d327d40d1..506cf8fc224 100644
--- a/Libraries/LibJS/Rust/src/interpreter/slow_paths/property_access.rs
+++ b/Libraries/LibJS/Rust/src/interpreter/slow_paths/property_access.rs
@@ -218,6 +218,21 @@ pub fn put_by_id(vm: &Vm, pc: u32, instruction: &op::PutById, values: &mut op::P
let executable = vm.current_executable();
let property_key = executable.get_property_key(&instruction.property);
let cache = executable.property_lookup_cache(instruction.cache as usize);
+ // NB: A megamorphic put sees more shapes than its hash tables hold, so it goes through the VM's keyed property
+ // store cache, which has room for many more.
+ if cache.is_megamorphic()
+ && base.is_object()
+ && base.as_object().is_cacheable_across_realms()
+ && property_key.is_string()
+ && put_kind_from_operand(instruction.kind) == PutKind::Normal
+ {
+ asm_try!(
+ vm,
+ pc,
+ put_by_value_with_keyed_store_cache(vm, pc, base, 0, value, property_key, Some(cache))
+ );
+ return SlowPathControl::continue_at(pc + op::PutById::LENGTH);
+ }
asm_try!(
vm,
pc,
@@ -495,7 +510,7 @@ pub fn put_by_value(
asm_try!(
vm,
pc,
- put_by_value_with_keyed_store_cache(vm, pc, base, property, value, &property_key)
+ put_by_value_with_keyed_store_cache(vm, pc, base, property.0, value, &property_key, None)
);
return SlowPathControl::continue_at(pc + op::PutByValue::LENGTH);
}
@@ -522,14 +537,17 @@ pub fn put_by_value(
/// property store cache, which remembers the writable own data properties such puts change and the properties they
/// add by shape and name, like the keyed property lookup cache does for gets. A put it does not know is made with an
/// empty cache of its own, and remembered: as a change or an addition if that cache could have made it, or as a put
-/// to make generically otherwise, so that other puts it cannot make only pay for the lookup.
+/// to make generically otherwise, so that other puts it cannot make only pay for the lookup. `cache_key` is the key the
+/// entries of that cache are for (see PropertyLookupCacheEntry::key; 0 for named puts). The changes and additions it
+/// makes or learns are also remembered in `site_cache`, the instruction's own cache, if one is given.
fn put_by_value_with_keyed_store_cache(
vm: &Vm,
pc: u32,
base: Value,
- key: Value,
+ cache_key: u64,
value: Value,
property_key: &PropertyKey,
+ site_cache: Option<&PropertyLookupCache>,
) -> ThrowCompletionOr<()> {
let object = base.as_object();
let name = property_key.as_string();
@@ -551,6 +569,19 @@ fn put_by_value_with_keyed_store_cache(
)
};
let shape_key = ShapeKey::of(shape);
+ // NB: The instruction's own cache learns the puts this cache makes for it, like the caches of megamorphic gets do
+ // (see `get_by_value_with_keyed_cache()`), so that its compiled code finds the entry inline again.
+ let remember = |entry: &KeyedPropertyLookup| {
+ if let Some(site_cache) = site_cache {
+ site_cache.update(entry.entry_type, |site_entry| {
+ site_entry.shape = Some(shape_key);
+ site_entry.property_offset = entry.property_offset;
+ site_entry.writes_data_property = entry.entry_type == PropertyLookupCacheEntryType::ChangeOwnProperty;
+ site_entry.new_shape = entry.new_shape;
+ site_entry.prototype_chain_validity = entry.prototype_chain_validity;
+ });
+ }
+ };
if let Some(entry) = store_cache.lookup(index, shape, name)
&& entry.shape_key() == Some(shape_key)
{
@@ -558,6 +589,7 @@ fn put_by_value_with_keyed_store_cache(
PropertyLookupCacheEntryType::ChangeOwnProperty => {
if !object.get_direct(entry.property_offset).is_accessor() {
object.put_direct_from_cache(entry.property_offset, value);
+ remember(&entry);
return Ok(());
}
}
@@ -571,6 +603,7 @@ fn put_by_value_with_keyed_store_cache(
{
object.unsafe_set_shape(new_shape);
object.initialize_direct(entry.property_offset, value);
+ remember(&entry);
return Ok(());
}
}
@@ -580,9 +613,15 @@ fn put_by_value_with_keyed_store_cache(
let scratch_cache = vm.keyed_property_store_scratch_cache();
scratch_cache.forget_entries();
- generic_put(Some(scratch_cache), key.0)?;
+ generic_put(Some(scratch_cache), cache_key)?;
let entry = scratch_cache.first_entry().unwrap_or_default();
scratch_cache.forget_entries();
+ // NB: Two names whose entries share a slot of this cache would otherwise miss both caches all the time.
+ if let Some(site_cache) = site_cache
+ && entry.entry_type != PropertyLookupCacheEntryType::Empty
+ {
+ site_cache.update(entry.entry_type, |site_entry| *site_entry = entry);
+ }
// NB: Puts the cache does not make are remembered with another type, for the shape they found.
let mut lookup = KeyedPropertyLookup::for_shape(shape_key);
match entry.entry_type {
diff --git a/Tests/LibJS/JIT/programs/megamorphic-named-puts.js b/Tests/LibJS/JIT/programs/megamorphic-named-puts.js
new file mode 100644
index 00000000000..d7248fdbcad
--- /dev/null
+++ b/Tests/LibJS/JIT/programs/megamorphic-named-puts.js
@@ -0,0 +1,50 @@
+// Named puts that see more shapes than their caches hold go through the VM's keyed property store cache: changes of
+// own properties, additions, setters of the prototype chain, read-only and frozen objects and dictionaries, while the
+// prototype changes under them.
+"use strict";
+const proto = {};
+let setterCalls = 0;
+function make(i) {
+ const o = Object.create(proto);
+ o["k" + (i % 40)] = i;
+ if (i % 2 === 0) o.x = 0;
+ if (i % 9 === 0) Object.defineProperty(o, "x", { value: "fixed", writable: false, configurable: true });
+ if (i % 13 === 0) {
+ o.gone = 1;
+ delete o.gone;
+ }
+ if (i % 17 === 0) Object.freeze(o);
+ return o;
+}
+
+function write(o, v) {
+ try {
+ o.x = v;
+ return "ok";
+ } catch (e) {
+ return e.constructor.name;
+ }
+}
+
+const objects = [];
+for (let i = 0; i < 80; i++) objects.push(make(i));
+const out = [];
+for (let round = 0; round < 60; round++) {
+ if (round === 20)
+ Object.defineProperty(proto, "x", {
+ set(v) {
+ setterCalls++;
+ },
+ configurable: true,
+ });
+ if (round === 35) delete proto.x;
+ if (round === 45) Object.defineProperty(proto, "x", { value: "proto", writable: false, configurable: true });
+ let s = "";
+ for (const o of objects) s += write(o, round) + ":" + o.x + ":" + Object.keys(o).length + ",";
+ 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(setterCalls, hash);