Skip to content

Truly independent web browser

LibJS: Fill holes of holey arrays in JIT code

Aliaksandr Kalenik474a345c0232
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/keyed.rs b/Libraries/LibJS/JIT/Rust/src/builder/keyed.rs
index 54aa4ee17b5..e25b8242d88 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/keyed.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/keyed.rs
@@ -15,7 +15,8 @@
//! chain has no indexed properties. Strings give the
//! strings of their ASCII characters. Other keys probe the property lookup
//! caches. Everything else takes the instruction's slow path, and all paths
-//! join after the instruction. `PutByValue` is built the same way.
+//! join after the instruction. `PutByValue` is built the same way, and
+//! fills holes of arrays where that runs no code.
use super::Flow;
use super::GenericInfo;
@@ -27,6 +28,7 @@ use crate::bytecode::Operand;
use crate::bytecode::PUT_KIND_NORMAL;
use crate::code::ExitKind;
use crate::code::Repr;
+use crate::ir::BinaryOp;
use crate::ir::BlockId;
use crate::ir::BranchCondition;
use crate::ir::Comparison;
@@ -342,10 +344,11 @@ impl GraphBuilder<'_> {
return self.build_generic(instruction, info);
};
- // NB: Appends check that the prototype chain is the realm's default
- // one, and exit for arrays that push could not append to.
+ // NB: Appends and hole fills check that the prototype chain is the
+ // realm's default one. Appends exit for arrays that push could
+ // not append to, and hole fills take the slow path.
let appends = self.may_speculate(ExitKind::SlowPath);
- if appends {
+ if appends || kinds.contains(&ElementsKind::Holey) {
self.embed(self.runtime.array_prototype);
self.embed(self.runtime.object_prototype);
}
@@ -371,10 +374,9 @@ impl GraphBuilder<'_> {
} else {
builder.element_index_in_bounds(slow_paths, kind, address, index)
};
- // NB: Holes are filled by the slow path.
if kind == ElementsKind::Holey {
- let old = builder.emit(Op::LoadElementAt { kind }, vec![storage, index], Some(Repr::Tagged));
- builder.branch_if_empty(slow_paths, old);
+ builder.store_holey_element(slow_paths, address, index, stored);
+ return;
}
builder.store_element(kind, storage, index, stored);
builder.end_hot_path(slow_paths, Vec::new());
@@ -396,6 +398,38 @@ impl GraphBuilder<'_> {
Ok(Flow::Continue)
}
+ /// Stores `value` at the checked `index` of the holey elements of the
+ /// object at `address`. A hole takes a new element, which runs no code
+ /// where the object is an array with a plain prototype chain (see
+ /// `BranchCondition::HoleFillableArray`); other holes take a slow path.
+ fn store_holey_element(&mut self, slow_paths: &mut SlowPaths, address: NodeId, index: NodeId, value: NodeId) {
+ let kind = ElementsKind::Holey;
+ let old = self.emit(Op::LoadElementAt { kind }, vec![address, index], Some(Repr::Tagged));
+ let empty = self.constant(value::EMPTY);
+ let (hole, element) = self.branch_both_ways(BranchCondition::TaggedEquals { equal: true }, vec![old, empty]);
+
+ self.block = hole;
+ self.branch_to_slow_path(slow_paths, BranchCondition::HoleFillableArray, vec![address], true);
+ // NB: A store to the last index may make the elements packed, which
+ // the slow path does. The index is below the length, so the
+ // length is not 0.
+ let length = self.emit(Op::LoadElementsLength, vec![address], Some(Repr::Int32));
+ let one = self.int32_constant(1);
+ let last = self.emit(
+ Op::Int32WrappingBinary { op: BinaryOp::Sub },
+ vec![length, one],
+ Some(Repr::Int32),
+ );
+ let index_before_last =
+ self.branch_to_slow_path(slow_paths, BranchCondition::IndexInBounds, vec![index, last], true);
+ self.store_element(kind, address, index_before_last, value);
+ self.end_hot_path(slow_paths, Vec::new());
+
+ self.block = element;
+ self.store_element(kind, address, index, value);
+ self.end_hot_path(slow_paths, Vec::new());
+ }
+
/// `value` as elements of `kind` store it, taking a slow path for
/// values of typed arrays that are no numbers.
fn stored_element(&mut self, slow_paths: &mut SlowPaths, kind: ElementsKind, value: NodeId) -> NodeId {
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
index 456250f83d7..e2a0fcb2fd3 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
@@ -2194,7 +2194,8 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
| BranchCondition::Builtin(_)
| BranchCondition::PropertyIteratorCacheValid
| BranchCondition::BindingMutable { .. }
- | BranchCondition::NextBindingOfShape { .. } => {
+ | BranchCondition::NextBindingOfShape { .. }
+ | BranchCondition::HoleFillableArray => {
// NB: These take several tests, which go to `yes` or `no`.
let other = self.masm.new_label();
let (yes, no) = if invert { (other, target) } else { (target, other) };
@@ -2216,6 +2217,10 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
self.emit_next_binding_of_shape_test(node, input, name, flags, no);
self.masm.jump(yes);
}
+ BranchCondition::HoleFillableArray => {
+ self.branch_unless_plain_array(input, self.temp(node, 0), no);
+ self.masm.jump(yes);
+ }
_ => unreachable!(),
}
self.masm.bind(other);
diff --git a/Libraries/LibJS/JIT/Rust/src/ir/dump.rs b/Libraries/LibJS/JIT/Rust/src/ir/dump.rs
index f51aa7404a7..d281c70be38 100644
--- a/Libraries/LibJS/JIT/Rust/src/ir/dump.rs
+++ b/Libraries/LibJS/JIT/Rust/src/ir/dump.rs
@@ -74,6 +74,7 @@ fn condition_text(condition: BranchCondition) -> String {
BranchCondition::IndexInBounds => "IndexInBounds".to_string(),
BranchCondition::MagicalLength => "MagicalLength".to_string(),
BranchCondition::Extensible => "Extensible".to_string(),
+ BranchCondition::HoleFillableArray => "HoleFillableArray".to_string(),
BranchCondition::ArrayIterator => "ArrayIterator".to_string(),
BranchCondition::PlainArrayPrototypeChain => "PlainArrayPrototypeChain".to_string(),
BranchCondition::Shape(shape) => format!("Shape {}", shapes_text(std::iter::once(&shape))),
diff --git a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs b/Libraries/LibJS/JIT/Rust/src/ir/mod.rs
index 6268111d3b1..913085853a5 100644
--- a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/ir/mod.rs
@@ -129,6 +129,13 @@ pub enum BranchCondition {
MagicalLength,
/// The input is the `Repr::Pointer` of an object: is it extensible?
Extensible,
+ /// The input is the `Repr::Pointer` of an object: is it an array that a
+ /// `[[Set]]` of an element it does not have defines that element on
+ /// without running any code, because it is extensible, does not
+ /// interfere with indexed access, is no proxy target, and its prototype
+ /// chain is the realm's default one without indexed properties (like
+ /// `Op::CheckAppendableArray` checks, whatever its length and storage)?
+ HoleFillableArray,
/// The input is the `Repr::Pointer` of an object: is it an array
/// iterator over values, like `%Array.prototype.values%` makes?
ArrayIterator,
diff --git a/Libraries/LibJS/JIT/Rust/src/passes/simplify.rs b/Libraries/LibJS/JIT/Rust/src/passes/simplify.rs
index d2ed86c22c6..23720f56579 100644
--- a/Libraries/LibJS/JIT/Rust/src/passes/simplify.rs
+++ b/Libraries/LibJS/JIT/Rust/src/passes/simplify.rs
@@ -276,6 +276,7 @@ fn constant_condition(graph: &Graph, condition: BranchCondition, input: NodeId,
| BranchCondition::IndexInBounds
| BranchCondition::MagicalLength
| BranchCondition::Extensible
+ | BranchCondition::HoleFillableArray
| BranchCondition::ArrayIterator
| BranchCondition::PlainArrayPrototypeChain
| BranchCondition::Shape(_) => None,
diff --git a/Libraries/LibJS/JIT/Rust/src/passes/verify.rs b/Libraries/LibJS/JIT/Rust/src/passes/verify.rs
index 11a5f113b16..0f035c34839 100644
--- a/Libraries/LibJS/JIT/Rust/src/passes/verify.rs
+++ b/Libraries/LibJS/JIT/Rust/src/passes/verify.rs
@@ -481,6 +481,7 @@ fn branch_input_reprs(condition: crate::ir::BranchCondition) -> Vec<Repr> {
crate::ir::BranchCondition::ResolvedString
| crate::ir::BranchCondition::MagicalLength
| crate::ir::BranchCondition::Extensible
+ | crate::ir::BranchCondition::HoleFillableArray
| crate::ir::BranchCondition::ArrayIterator
| crate::ir::BranchCondition::PlainArrayPrototypeChain => vec![Repr::Pointer],
crate::ir::BranchCondition::Shape(_) => vec![Repr::Tagged, Repr::Pointer],
diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs
index f4fe9d3b927..18cb15f4321 100644
--- a/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs
@@ -422,6 +422,11 @@ fn constraints(node: &Node, registers: &RegisterSet) -> Constraints {
condition: BranchCondition::BindingMutable { .. } | BranchCondition::NextBindingOfShape { .. },
..
} => constraints.temps = 2,
+ // The array's prototypes.
+ Op::Branch {
+ condition: BranchCondition::HoleFillableArray,
+ ..
+ } => constraints.temps = 1,
// The environment's binding values (and their count).
Op::StoreEnvironmentBinding { .. } | Op::AppendEnvironmentBinding => constraints.temps = 1,
// The array, then its prototypes.
diff --git a/Tests/LibJS/JIT/ir/hole-filling-stores.js b/Tests/LibJS/JIT/ir/hole-filling-stores.js
new file mode 100644
index 00000000000..1b3cd3aa9d6
--- /dev/null
+++ b/Tests/LibJS/JIT/ir/hole-filling-stores.js
@@ -0,0 +1,33 @@
+// Stores into holes of holey arrays fill them inline where the array can get
+// a new element without running any code. Holes of other objects, stores that
+// need more storage, and stores to the last index, which may make the
+// elements packed, take the slow path, in cold blocks.
+
+function fill(n) {
+ const a = new Array(n);
+ for (let i = 0; i < n; ++i) a[i] = i;
+ return a;
+}
+jit.prepare(fill);
+for (let i = 0; i < 10; ++i) fill(20);
+jit.compile(fill);
+
+// CHECK-FUNCTION: fill
+// CHECK-PASS: frame initialization
+// CHECK: BranchElementsKind Holey
+// CHECK: [[ADDRESS:v[0-9]+]]:pointer = CellAddress
+// CHECK-NEXT: [[LENGTH:v[0-9]+]]:int32 = LoadElementsLength ([[ADDRESS]])
+// CHECK: [[OLD:v[0-9]+]] = LoadElementAt Holey ([[ADDRESS]], [[INDEX:v[0-9]+]])
+// CHECK-NEXT: BranchTaggedEquals ([[OLD]], #empty)
+// CHECK-NOT: cold
+// CHECK: BranchHoleFillableArray ([[ADDRESS]])
+// CHECK-NOT: cold
+// CHECK: [[LAST:v[0-9]+]]:int32 = Int32WrappingSub ([[LENGTH]], #i32:1)
+// CHECK-NEXT: BranchIndexInBounds ([[INDEX]], [[LAST]])
+// CHECK-NOT: cold
+// CHECK: StoreElementAt Holey ([[ADDRESS]], [[INDEX]],
+// CHECK-NOT: CallSlowPath
+// CHECK: cold:
+// CHECK-NOT: StoreElementAt
+// CHECK: CallSlowPath PutByValue
+// CHECK-COUNT-1: CallSlowPath PutByValue
diff --git a/Tests/LibJS/Runtime/jit/hole-filling-stores-prototype-setters.js b/Tests/LibJS/Runtime/jit/hole-filling-stores-prototype-setters.js
new file mode 100644
index 00000000000..b26c143ee25
--- /dev/null
+++ b/Tests/LibJS/Runtime/jit/hole-filling-stores-prototype-setters.js
@@ -0,0 +1,114 @@
+// JIT code stores into the holes of holey arrays inline only where their
+// prototype chain has no indexed properties. Each test compiles the stores
+// first, and then gives %Array.prototype% or %Object.prototype% an indexed
+// property. Indexed properties of %Object.prototype% stay in effect after they
+// are deleted, so that test comes last, and this file is of its own.
+
+const iterations = 100;
+
+function store(array, index, value) {
+ array[index] = value;
+}
+
+function strictStore(array, index, value) {
+ "use strict";
+ array[index] = value;
+}
+
+function warmUp() {
+ for (let i = 0; i < iterations; ++i) {
+ const array = new Array(16);
+ for (let j = 0; j < 16; ++j) store(array, j, j);
+ const strictArray = new Array(16);
+ for (let j = 0; j < 16; ++j) strictStore(strictArray, j, j);
+ }
+}
+
+// An array with holes inside the capacity of its storage, so that stores into
+// them do not need to grow it.
+function holeyArray(length) {
+ const array = new Array(length);
+ array[0] = 0;
+ return array;
+}
+
+function removeArrayPrototypeElement(index) {
+ delete Array.prototype[index];
+ Array.prototype.length = 0;
+}
+
+describe("Hole-filling stores in JIT code with indexed properties on prototypes", () => {
+ test("a setter on Array.prototype", () => {
+ warmUp();
+ const calls = [];
+ Object.defineProperty(Array.prototype, 2, {
+ set(value) {
+ calls.push([this, value]);
+ },
+ configurable: true,
+ });
+ try {
+ const array = holeyArray(8);
+ store(array, 2, "x");
+ strictStore(array, 2, "y");
+ expect(calls).toEqual([
+ [array, "x"],
+ [array, "y"],
+ ]);
+ expect(Object.hasOwn(array, 2)).toBeFalse();
+ store(array, 3, "z");
+ expect(array[3]).toBe("z");
+ } finally {
+ removeArrayPrototypeElement(2);
+ }
+ const array = holeyArray(8);
+ store(array, 2, "x");
+ expect(array[2]).toBe("x");
+ expect(calls.length).toBe(2);
+ });
+
+ test("a read-only element of Array.prototype", () => {
+ warmUp();
+ Object.defineProperty(Array.prototype, 3, { value: "read-only", configurable: true });
+ try {
+ const array = holeyArray(8);
+ store(array, 3, "x");
+ expect(Object.hasOwn(array, 3)).toBeFalse();
+ expect(array[3]).toBe("read-only");
+ expect(() => strictStore(array, 3, "x")).toThrow(TypeError);
+ expect(Object.hasOwn(array, 3)).toBeFalse();
+ } finally {
+ removeArrayPrototypeElement(3);
+ }
+ const array = holeyArray(8);
+ store(array, 3, "x");
+ expect(array[3]).toBe("x");
+ });
+
+ test("a setter on Object.prototype", () => {
+ warmUp();
+ const calls = [];
+ Object.defineProperty(Object.prototype, 4, {
+ set(value) {
+ calls.push([this, value]);
+ },
+ configurable: true,
+ });
+ try {
+ const array = holeyArray(8);
+ store(array, 4, "x");
+ strictStore(array, 4, "y");
+ expect(calls).toEqual([
+ [array, "x"],
+ [array, "y"],
+ ]);
+ expect(Object.hasOwn(array, 4)).toBeFalse();
+ } finally {
+ delete Object.prototype[4];
+ }
+ const array = holeyArray(8);
+ store(array, 4, "x");
+ expect(array[4]).toBe("x");
+ expect(calls.length).toBe(2);
+ });
+});
diff --git a/Tests/LibJS/Runtime/jit/hole-filling-stores.js b/Tests/LibJS/Runtime/jit/hole-filling-stores.js
new file mode 100644
index 00000000000..c6d3b3852ed
--- /dev/null
+++ b/Tests/LibJS/Runtime/jit/hole-filling-stores.js
@@ -0,0 +1,188 @@
+// JIT code stores into the holes of holey arrays inline, when nothing could
+// observe the difference. These tests run every function many times, so that
+// with a low JIT threshold they are compiled.
+
+const iterations = 100;
+
+function store(array, index, value) {
+ array[index] = value;
+}
+
+function strictStore(array, index, value) {
+ "use strict";
+ array[index] = value;
+}
+
+function fill(values) {
+ const array = new Array(values.length);
+ for (let i = 0; i < values.length; ++i) store(array, i, values[i]);
+ return array;
+}
+
+function warmUp() {
+ const values = Array.from({ length: 16 }, (_, i) => i);
+ for (let i = 0; i < iterations; ++i) {
+ fill(values);
+ const array = new Array(values.length);
+ for (let j = 0; j < values.length; ++j) strictStore(array, j, j);
+ }
+}
+
+// An array with holes inside the capacity of its storage, so that stores into
+// them do not need to grow it.
+function holeyArray(length) {
+ const array = new Array(length);
+ array[0] = 0;
+ return array;
+}
+
+describe("Hole-filling stores in JIT code", () => {
+ test("filling every hole", () => {
+ const kinds = [i => i, i => `${i}`, i => ({ i }), () => undefined];
+ for (let count = 0; count <= iterations; ++count) {
+ for (const kind of kinds) {
+ const values = Array.from({ length: count }, (_, i) => kind(i));
+ const array = fill(values);
+ expect(array.length).toBe(count);
+ for (let i = 0; i < count; ++i) {
+ expect(Object.hasOwn(array, i)).toBeTrue();
+ expect(array[i]).toBe(values[i]);
+ }
+ expect(array).toEqual(values);
+ expect([...array]).toEqual(values);
+ expect(Object.keys(array)).toEqual(Object.keys(values));
+ }
+ }
+ });
+
+ test("overwriting elements of holey arrays", () => {
+ warmUp();
+ const array = holeyArray(8);
+ store(array, 2, "a");
+ store(array, 2, "b");
+ strictStore(array, 3, "c");
+ strictStore(array, 3, "d");
+ expect(array[2]).toBe("b");
+ expect(array[3]).toBe("d");
+ expect(Object.keys(array)).toEqual(["0", "2", "3"]);
+ });
+
+ test("filling some holes leaves the others", () => {
+ warmUp();
+ for (let count = 0; count <= 40; ++count) {
+ const array = new Array(count);
+ for (let i = 0; i < count; i += 2) store(array, i, i);
+ expect(array.length).toBe(count);
+ for (let i = 0; i < count; ++i) {
+ const filled = i % 2 === 0;
+ expect(Object.hasOwn(array, i)).toBe(filled);
+ expect(i in array).toBe(filled);
+ expect(array[i]).toBe(filled ? i : undefined);
+ }
+ expect(Object.keys(array).length).toBe(Math.ceil(count / 2));
+ }
+ });
+
+ test("filling in reverse and the last index first", () => {
+ warmUp();
+ const expected = Array.from({ length: 20 }, (_, i) => i);
+
+ const reversed = new Array(20);
+ for (let i = 19; i >= 0; --i) store(reversed, i, i);
+ expect(reversed).toEqual(expected);
+
+ const lastFirst = holeyArray(20);
+ store(lastFirst, 19, 19);
+ for (let i = 1; i < 19; ++i) store(lastFirst, i, i);
+ expect(lastFirst).toEqual(expected);
+
+ const lastAtEnd = holeyArray(20);
+ for (let i = 1; i < 20; ++i) store(lastAtEnd, i, i);
+ expect(lastAtEnd).toEqual(expected);
+
+ for (const array of [reversed, lastFirst, lastAtEnd]) {
+ expect(array[19]).toBe(19);
+ expect(array.indexOf(7)).toBe(7);
+ expect(array.indexOf(20)).toBe(-1);
+ expect(array.push(20)).toBe(21);
+ expect([...array]).toEqual([...expected, 20]);
+ expect(Object.keys(array).length).toBe(21);
+ }
+ });
+
+ test("arrays that cannot get new elements", () => {
+ warmUp();
+ const array = Object.preventExtensions(holeyArray(8));
+ store(array, 3, "x");
+ expect(Object.hasOwn(array, 3)).toBeFalse();
+ expect(array.length).toBe(8);
+ expect(() => strictStore(array, 3, "x")).toThrow(TypeError);
+ expect(Object.hasOwn(array, 3)).toBeFalse();
+ store(array, 0, "existing");
+ expect(array[0]).toBe("existing");
+
+ const sealed = Object.seal(holeyArray(8));
+ store(sealed, 3, "x");
+ expect(Object.hasOwn(sealed, 3)).toBeFalse();
+ expect(() => strictStore(sealed, 3, "x")).toThrow(TypeError);
+ });
+
+ test("arrays with other prototypes", () => {
+ warmUp();
+ class Subclass extends Array {
+ set 3(value) {
+ this.seen = value;
+ }
+ }
+ const subclass = new Subclass(8);
+ subclass[0] = 0;
+ store(subclass, 3, "x");
+ expect(subclass.seen).toBe("x");
+ expect(Object.hasOwn(subclass, 3)).toBeFalse();
+ store(subclass, 4, "y");
+ expect(subclass[4]).toBe("y");
+
+ const calls = [];
+ const withOwnPrototype = holeyArray(8);
+ Object.setPrototypeOf(withOwnPrototype, {
+ set 2(value) {
+ calls.push([this, value]);
+ },
+ });
+ store(withOwnPrototype, 2, "x");
+ strictStore(withOwnPrototype, 2, "y");
+ expect(calls).toEqual([
+ [withOwnPrototype, "x"],
+ [withOwnPrototype, "y"],
+ ]);
+ expect(Object.hasOwn(withOwnPrototype, 2)).toBeFalse();
+ store(withOwnPrototype, 3, "z");
+ expect(Object.hasOwn(withOwnPrototype, 3)).toBeTrue();
+ });
+
+ test("proxy targets and other objects", () => {
+ warmUp();
+ const target = holeyArray(8);
+ let sets = 0;
+ const proxy = new Proxy(target, {
+ set(target, key, value) {
+ ++sets;
+ target[key] = value;
+ return true;
+ },
+ });
+ store(target, 3, "x");
+ expect(target[3]).toBe("x");
+ expect(sets).toBe(0);
+ store(proxy, 4, "y");
+ expect(target[4]).toBe("y");
+ expect(sets).toBe(1);
+ expect(Object.keys(target)).toEqual(["0", "3", "4"]);
+
+ const arrayLike = { length: 8, 0: 0, 5: 5 };
+ store(arrayLike, 3, "x");
+ expect(arrayLike[3]).toBe("x");
+ expect(arrayLike.length).toBe(8);
+ expect(Object.keys(arrayLike)).toEqual(["0", "3", "5", "length"]);
+ });
+});