Skip to content

Truly independent web browser

LibJS/JIT: Allocate the arrays of `new Array(...)` inline

Andreas Kling48c2e871fcd9
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/allocation.rs b/Libraries/LibJS/JIT/Rust/src/builder/allocation.rs
index 8504de0eecc..ab820bfccd6 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/allocation.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/allocation.rs
@@ -116,17 +116,22 @@ pub(super) enum ArrayElement {
}
impl GraphBuilder<'_> {
+ /// Whether compiled code allocates arrays of `count` elements.
+ pub(super) fn can_allocate_array(&self, count: usize) -> bool {
+ // NB: The runtime always allocates arrays; the codegen tests of slow
+ // path conventions leave its allocation out to run NewArray's.
+ count <= MAX_ARRAY_LITERAL_ELEMENTS && self.runtime.array_allocation.slow_path != 0
+ }
+
/// Builds `NewArray` or `NewPrimitiveArray` as an `AllocateArray` and
- /// the stores of its elements. Returns false, having built nothing, for
- /// arrays with too many elements.
+ /// the stores of its elements. Returns false, having built nothing that
+ /// matters, for arrays with too many elements or with holes.
pub(super) fn try_build_new_array(
&mut self,
dst: Operand,
elements: &[ArrayElement],
) -> Result<bool, CompileFailure> {
- // NB: The runtime always allocates arrays; the codegen tests of slow
- // path conventions leave its allocation out to run NewArray's.
- if elements.len() > MAX_ARRAY_LITERAL_ELEMENTS || self.runtime.array_allocation.slow_path == 0 {
+ if !self.can_allocate_array(elements.len()) {
return Ok(false);
}
let values = elements
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/intrinsics.rs b/Libraries/LibJS/JIT/Rust/src/builder/intrinsics.rs
index 58bc987653f..3cffb9d915c 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/intrinsics.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/intrinsics.rs
@@ -685,6 +685,94 @@ impl GraphBuilder<'_> {
Ok(())
}
+ /// Builds a call or construct of the `Array` constructor `callee`, which
+ /// the code checked, with at most one argument: an array of length
+ /// `length` (a nonnegative int32), or of none, through `ArrayCreate`.
+ /// Other lengths and realms take the instruction's cold slow path.
+ fn build_array_of_length(
+ &mut self,
+ dst: Operand,
+ callee: Operand,
+ length: Option<Operand>,
+ ) -> Result<Flow, CompileFailure> {
+ // 23.1.1.1 Array ( ...values ), https://tc39.es/ecma262/#sec-array
+ let mut slow_paths = self.start_slow_paths(Some(Repr::Tagged))?;
+ let length = match length {
+ Some(argument) => {
+ let length = self.read(argument)?;
+ // NB: Other numbers are lengths that throw, and other
+ // values elements.
+ let length =
+ self.branch_to_slow_path(&mut slow_paths, BranchCondition::NonNegativeInt32, vec![length], true);
+ self.emit(Op::UnboxInt32, vec![length], Some(Repr::Int32))
+ }
+ None => self.int32_constant(0),
+ };
+ let function = self.read(callee)?;
+ let array = self.emit(Op::ArrayCreate, vec![length, function], Some(Repr::Tagged));
+ let array = self.branch_if_empty(&mut slow_paths, array);
+ let array = self
+ .join_slow_paths(slow_paths, Some(array))
+ .expect("calls have a value");
+ self.write(dst, array)?;
+ Ok(Flow::Continue)
+ }
+
+ /// Builds `new Array(...)` of the `Array` constructor, if the site saw
+ /// only it. Since the constructor is its own NewTarget, it makes what
+ /// its call makes: with one argument, an array of that length (see
+ /// `build_array_of_length()`), and otherwise an array of the arguments,
+ /// which code of the constructor's realm allocates like an array
+ /// literal. Returns `None`, having built nothing, if the construct is no
+ /// such construct.
+ pub(super) fn try_build_array_construct(
+ &mut self,
+ instruction: &Instruction,
+ ) -> Result<Option<Flow>, CompileFailure> {
+ let Instruction::CallConstruct {
+ call_feedback,
+ dst,
+ callee,
+ arguments,
+ ..
+ } = instruction
+ else {
+ return Ok(None);
+ };
+ let Some((target, Intrinsic::ArrayConstructor)) = self
+ .call_feedback(*call_feedback)
+ .and_then(|feedback| feedback.monomorphic_intrinsic())
+ else {
+ return Ok(None);
+ };
+ if arguments.iter().any(|operand| self.holds_virtual_arguments(*operand)) {
+ return Ok(None);
+ }
+ if let [length] = arguments.as_slice() {
+ if self.checked_intrinsic_callee(*call_feedback, *callee)?.is_none() {
+ return Ok(None);
+ }
+ return self.build_array_of_length(*dst, *callee, Some(*length)).map(Some);
+ }
+ // 23.1.1.1 Array ( ...values ), https://tc39.es/ecma262/#sec-array
+ if target != self.runtime.array_constructor
+ || !self.can_allocate_array(arguments.len())
+ || self.checked_intrinsic_callee(*call_feedback, *callee)?.is_none()
+ {
+ return Ok(None);
+ }
+ let elements = arguments
+ .iter()
+ .copied()
+ .map(super::allocation::ArrayElement::Operand)
+ .collect::<Vec<_>>();
+ // NB: Arrays with holes are left to the generic construct, which reading the operands does not affect.
+ if !self.try_build_new_array(*dst, &elements)? {
+ return Ok(None);
+ }
+ Ok(Some(Flow::Continue))
+ }
+
/// Builds calls of the `String`, `Array`, `Object` and `Boolean`
/// constructors with at most one argument, if the site saw only that
/// constructor: `Boolean(x)` is the truthiness of `x`, `String(x)` is a
@@ -735,32 +823,10 @@ impl GraphBuilder<'_> {
}
return Ok(Some(Flow::Continue));
}
- // 23.1.1.1 Array ( ...values ), https://tc39.es/ecma262/#sec-array
if constructor == Intrinsic::ArrayConstructor {
- let mut slow_paths = self.start_slow_paths(Some(Repr::Tagged))?;
- let length = match arguments.first() {
- Some(argument) => {
- let length = self.read(*argument)?;
- // NB: Other numbers are lengths that throw, and other
- // values elements.
- let length = self.branch_to_slow_path(
- &mut slow_paths,
- BranchCondition::NonNegativeInt32,
- vec![length],
- true,
- );
- self.emit(Op::UnboxInt32, vec![length], Some(Repr::Int32))
- }
- None => self.int32_constant(0),
- };
- let function = self.read(*callee)?;
- let array = self.emit(Op::ArrayCreate, vec![length, function], Some(Repr::Tagged));
- let array = self.branch_if_empty(&mut slow_paths, array);
- let array = self
- .join_slow_paths(slow_paths, Some(array))
- .expect("calls have a value");
- self.write(*dst, array)?;
- return Ok(Some(Flow::Continue));
+ return self
+ .build_array_of_length(*dst, *callee, arguments.first().copied())
+ .map(Some);
}
let Some(argument) = arguments.first() else {
return Ok(None);
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs b/Libraries/LibJS/JIT/Rust/src/builder/mod.rs
index 81c48aaa659..104a0ac4407 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/mod.rs
@@ -1644,7 +1644,12 @@ impl<'a> GraphBuilder<'a> {
return Ok(None);
}
}
- Instruction::CallConstruct { .. } => return self.try_inline_construct(instruction),
+ Instruction::CallConstruct { .. } => {
+ if let Some(flow) = self.try_build_array_construct(instruction)? {
+ return Ok(Some(flow));
+ }
+ return self.try_inline_construct(instruction);
+ }
Instruction::Call { .. } => {
if let Some(flow) = self.try_build_builtin_call(instruction)? {
return Ok(Some(flow));
diff --git a/Libraries/LibJS/JIT/Rust/src/snapshot.rs b/Libraries/LibJS/JIT/Rust/src/snapshot.rs
index 2eaaf302008..61968d1a859 100644
--- a/Libraries/LibJS/JIT/Rust/src/snapshot.rs
+++ b/Libraries/LibJS/JIT/Rust/src/snapshot.rs
@@ -1094,6 +1094,8 @@ pub struct RuntimeInfo {
/// `CompiledCode::embedded_cells`.
pub array_prototype: CellId,
pub object_prototype: CellId,
+ /// `%Array%` of the realm of the compiled code.
+ pub array_constructor: CellId,
/// `ExecutionContext::no_yield_continuation`.
pub no_yield_continuation: u32,
/// `js_heap_region_base`: cell pointers are this plus the offset bits of a cell value.
diff --git a/Libraries/LibJS/Rust/src/jit/runtime_info.rs b/Libraries/LibJS/Rust/src/jit/runtime_info.rs
index 38e319bc30f..b780a2d0b45 100644
--- a/Libraries/LibJS/Rust/src/jit/runtime_info.rs
+++ b/Libraries/LibJS/Rust/src/jit/runtime_info.rs
@@ -521,6 +521,7 @@ pub fn runtime_info(vm: &Vm, realm: Gc<Realm>, allocation: AllocationInfos) -> R
realm: CellId(realm.as_ptr() as u64),
array_prototype: CellId(realm.array_prototype().as_ptr() as u64),
object_prototype: CellId(realm.object_prototype().as_ptr() as u64),
+ array_constructor: CellId(realm.intrinsics().array_constructor(vm).as_ptr() as u64),
no_yield_continuation: ExecutionContext::NO_YIELD_CONTINUATION,
heap_region_base: vm.head.heap_region_base.get() as u64,
heap_region_offset_mask: HEAP_REGION_OFFSET_MASK,
diff --git a/Tests/LibJS/Runtime/jit/array-constructs.js b/Tests/LibJS/Runtime/jit/array-constructs.js
new file mode 100644
index 00000000000..bf12b5f1875
--- /dev/null
+++ b/Tests/LibJS/Runtime/jit/array-constructs.js
@@ -0,0 +1,79 @@
+// JIT code allocates the arrays `new Array(...)` makes of no argument or of
+// several arguments itself, and those of a length through the runtime.
+// These tests run every function many times, so that with a low JIT
+// threshold they are compiled.
+
+const iterations = 100;
+
+describe("constructs of Array in JIT code", () => {
+ test("no arguments, a length, and several elements", () => {
+ function empty() {
+ return new Array();
+ }
+ function ofLength(n) {
+ return new Array(n);
+ }
+ function ofElements(a, b, c) {
+ return new Array(a, b, c);
+ }
+ for (let i = 0; i < iterations; ++i) {
+ const array = empty();
+ expect(Array.isArray(array)).toBeTrue();
+ expect(Object.getPrototypeOf(array)).toBe(Array.prototype);
+ expect(array.length).toBe(0);
+ array.push(i);
+ expect(array).toEqual([i]);
+ expect(empty()).not.toBe(empty());
+
+ const sized = ofLength(i % 5);
+ expect(sized.length).toBe(i % 5);
+ expect(0 in sized).toBeFalse();
+
+ const elements = ofElements(i, "x", null);
+ expect(elements).toEqual([i, "x", null]);
+ expect(Object.getPrototypeOf(elements)).toBe(Array.prototype);
+ }
+ });
+
+ test("single arguments that are no lengths", () => {
+ function ofOne(value) {
+ return new Array(value);
+ }
+ for (let i = 0; i < iterations; ++i) {
+ expect(ofOne(3).length).toBe(3);
+ expect(ofOne("3")).toEqual(["3"]);
+ expect(ofOne(null)).toEqual([null]);
+ }
+ expect(() => ofOne(-1)).toThrow(RangeError);
+ expect(() => ofOne(1.5)).toThrow(RangeError);
+ expect(ofOne(2 ** 31).length).toBe(2 ** 31);
+ });
+
+ test("constructors other than Array", () => {
+ class MyArray extends Array {}
+ function construct(C) {
+ return new C();
+ }
+ for (let i = 0; i < iterations; ++i) expect(Array.isArray(construct(Array))).toBeTrue();
+ const mine = construct(MyArray);
+ expect(mine).toBeInstanceOf(MyArray);
+ expect(construct(Object)).not.toBeInstanceOf(Array);
+ });
+
+ test("a replaced global Array", () => {
+ const OriginalArray = Array;
+ function make() {
+ return new Array();
+ }
+ for (let i = 0; i < iterations; ++i) expect(Array.isArray(make())).toBeTrue();
+ try {
+ globalThis.Array = function () {
+ this.replaced = true;
+ };
+ expect(make().replaced).toBeTrue();
+ } finally {
+ globalThis.Array = OriginalArray;
+ }
+ expect(Array.isArray(make())).toBeTrue();
+ });
+});