Truly independent web browser
LibJS: Start plain object inline storage at the elements word
Andreas Klingadaf8d14d5aa
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/allocation.rs b/Libraries/LibJS/JIT/Rust/src/codegen/allocation.rsindex 4292237fa1d..8b5071a3c35 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/allocation.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/allocation.rs@@ -116,11 +116,11 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {// NB: The cell's fields up to the inline storage come from the// template, patched with the shape and the inline capacity.let template_bytes = 8 * info.template.len() as u64;- let fields_fit = u64::from(info.inline_storage_offset) <= template_bytes- && info.inline_storage_offset.is_multiple_of(8)+ let fields_fit = u64::from(info.plain_inline_storage_offset) <= template_bytes+ && info.plain_inline_storage_offset.is_multiple_of(8)&& info.named_properties_offset.is_multiple_of(8)- && info.shape_offset + 4 <= info.inline_storage_offset- && info.inline_capacity_offset < info.inline_storage_offset;+ && info.shape_offset + 4 <= info.plain_inline_storage_offset+ && info.inline_capacity_offset < info.plain_inline_storage_offset;let size_class = info.size_class_for(reserve).copied().filter(|_| fields_fit);let Some(size_class) = size_class else {self.masm.jump(entry);@@ -146,7 +146,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {.template.iter().flat_map(|word| word.to_le_bytes())- .take(info.inline_storage_offset as usize)+ .take(info.plain_inline_storage_offset as usize).collect::<Vec<u8>>();let shape_offset = info.shape_offset as usize;image[shape_offset..shape_offset + 4].copy_from_slice(&shape.compressed().to_le_bytes());@@ -161,6 +161,8 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {// If it is a constant, the allocation stores it, and none of// them runs; otherwise they all run.let initialized = self.initializations_without_gc(node);+ self.inline_initializations+ .extend(initialized.iter().map(|(_, initialization, _)| *initialization));let last_initialization = |index: u32| initialized.iter().rev().find(|(offset, _, _)| *offset == index);for index in 0..size_class.inline_capacity {let value = match last_initialization(index) {@@ -170,7 +172,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {Some((_, _, Some(bits))) => *bits,None => value::UNDEFINED,};- fields.push((info.inline_storage_offset + 8 * index, 8, value));+ fields.push((info.plain_inline_storage_offset + 8 * index, 8, value));}let mut constant_fields = Vec::new();for (offset, initialization, _) in &initialized {@@ -179,7 +181,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {};self.absorbed_initializations.push(*initialization);if last == initialization {- constant_fields.push((info.inline_storage_offset + 8 * offset, *bits));+ constant_fields.push((info.plain_inline_storage_offset + 8 * offset, *bits));}}self.deferred_allocations@@ -188,7 +190,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {.constant_fields = constant_fields;self.emit_constant_fields(cell, next, &mut fields)?;self.masm- .load_effective_address(next, &at(cell, info.inline_storage_offset));+ .load_effective_address(next, &at(cell, info.plain_inline_storage_offset));self.masm.store64(&at(cell, info.named_properties_offset), next);self.box_object(cell);self.masm.bind(resume);@@ -310,14 +312,12 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {}let storage = self.allocation_temp(node, 0);let object = self.input(node, 0);- // Objects allocated in a size class keep their properties inline.- let inline_storage = match self.graph.node(self.graph.node(node).inputs[0]).op {- Op::AllocateObject { reserve, .. } => self.runtime.object_allocation.size_class_for(reserve).is_some(),- _ => false,- };+ // NB: Objects allocated in a size class keep their properties inline, until their first indexed property. A+ // computed key of the literal can give them one, but only further down than right after the allocation.+ let inline_storage = self.inline_initializations.contains(&node);self.emit_unbox_cell(storage, object);let slot = if inline_storage {- let offset = u64::from(self.runtime.object_allocation.inline_storage_offset) + 8 * u64::from(offset);+ let offset = u64::from(self.runtime.object_allocation.plain_inline_storage_offset) + 8 * u64::from(offset);Address::new(storage, super::checked_i32(offset)?)} else {let storage_field = Address::new(storage, self.runtime.offsets.object_named_properties as i32);diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rs b/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rsindex c2f51f571be..3b8429820b1 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rs@@ -113,6 +113,7 @@ pub fn generate_call_stub<M: PortableMacroAssembler>(runtime: &RuntimeInfo) -> Rdeferred_allocations: Vec::new(),deferred_storage_growths: Vec::new(),absorbed_initializations: Vec::new(),+ inline_initializations: Default::default(),};codegen.emit_call_stub()?;let (code, _) = codegendiff --git a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rsindex fefeace6d6f..a5b1cc20c00 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs@@ -91,7 +91,7 @@ use crate::code::Repr;use crate::code::Site;use crate::code::SiteKind;use crate::code::ValueLocation;-use crate::fast_hash::HashMap;+use crate::fast_hash::{HashMap, HashSet};use crate::ir;use crate::ir::BlockId;use crate::ir::BranchCondition;@@ -298,6 +298,8 @@ struct Codegen<'a, M: PortableMacroAssembler> {/// `InitializeNamed` nodes whose constant the allocation of their object/// stored already.absorbed_initializations: Vec<NodeId>,+ /// `InitializeNamed` nodes right after the allocation of their object, which still has its properties inline.+ inline_initializations: HashSet<NodeId>,/// The slots of the compiled function's frame that hold its arguments/// object, which the code never created, when the node being emitted/// (in the compiled function or an inlined callee) leaves the code after@@ -443,6 +445,7 @@ pub fn generate<M: PortableMacroAssembler>(deferred_allocations: Vec::new(),deferred_storage_growths: Vec::new(),absorbed_initializations: Vec::new(),+ inline_initializations: HashSet::default(),leave_arguments: Vec::new(),leave_stubs: Vec::new(),leave_frame: None,diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/named_storage.rs b/Libraries/LibJS/JIT/Rust/src/codegen/named_storage.rsindex 426cdcfb5b2..533c3ad7c1d 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/named_storage.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/named_storage.rs@@ -167,9 +167,14 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {self.masm.load64(object, &self.growth_save_address(0, return_address_bytes));self.masm.load64(storage, &at(object, offsets.object_named_properties));- self.masm- .load_effective_address(scratch, &at(object, objects.inline_storage_offset));- self.masm.branch64(Condition::NotEqual, storage, scratch, heap_storage);+ // NB: Inline storage starts at one of two offsets, within the object. Heap storage is outside of it.+ self.masm.sub64(scratch, storage, object);+ self.masm.branch64_imm(+ Condition::Above,+ scratch,+ i64::from(objects.inline_storage_offset),+ heap_storage,+ );self.masm.load8(old_capacity, &at(object, objects.inline_capacity_offset));self.masm.jump(have_capacity);@@ -248,6 +253,14 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {self.masm.store64(&values(cell, old_capacity), scratch);self.masm.jump(copy);self.masm.bind(copied);+ // NB: The inline storage of a plain object overlaps the indexed elements word, which is free again now.+ let no_overlap = self.masm.new_label();+ self.masm+ .load_effective_address(scratch, &at(object, objects.plain_inline_storage_offset));+ self.masm.branch64(Condition::NotEqual, storage, scratch, no_overlap);+ self.masm+ .store_imm64(&at(object, self.runtime.layout.object_indexed_elements), 0);+ self.masm.bind(no_overlap);self.masm.load_effective_address(storage, &at(cell, info.storage_values_offset));self.masm.store64(&at(object, offsets.object_named_properties), storage);diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/probes/property.rs b/Libraries/LibJS/JIT/Rust/src/codegen/probes/property.rsindex d60444e973c..c4c500df900 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/probes/property.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/probes/property.rs@@ -550,11 +550,14 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {let check_capacity = self.masm.new_label();self.masm.load64(storage, &Address::new(object, offsets.object_named_properties as i32));- self.masm.load_effective_address(+ // NB: Inline storage starts at one of two offsets, within the object. Heap storage is outside of it.+ self.masm.sub64(scratch, storage, object);+ self.masm.branch64_imm(+ Condition::Above,scratch,- &Address::new(object, self.runtime.object_allocation.inline_storage_offset as i32),+ i64::from(self.runtime.object_allocation.inline_storage_offset),+ heap_storage,);- self.masm.branch64(Condition::NotEqual, storage, scratch, heap_storage);self.masm.load8(scratch,&Address::new(object, self.runtime.object_allocation.inline_capacity_offset as i32),diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs b/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rsindex 614d29cb3ac..b11ba253325 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs@@ -290,6 +290,7 @@ fn marker_runtime() -> RuntimeInfo {runtime.offsets.object_shape = 48;runtime.offsets.object_named_properties = 56;runtime.object_allocation.inline_storage_offset = 64;+ runtime.object_allocation.plain_inline_storage_offset = 64;runtime.object_allocation.inline_capacity_offset = 40;runtime.offsets.shape_dictionary_generation = 84;runtime.object_allocation.template = vec![PLAIN_OBJECT_CLASS];diff --git a/Libraries/LibJS/JIT/Rust/src/snapshot.rs b/Libraries/LibJS/JIT/Rust/src/snapshot.rsindex dbb1ede5713..9c9ac406b9d 100644--- a/Libraries/LibJS/JIT/Rust/src/snapshot.rs+++ b/Libraries/LibJS/JIT/Rust/src/snapshot.rs@@ -1285,9 +1285,9 @@ pub struct DynamicCallLayout {/// 6. Copy `template` (`8 * template.len()` bytes, the start of every cell) to/// `cell`. Then store `inline_capacity` (a u8) at/// `cell + inline_capacity_offset`, the shape at `cell + shape_offset`,-/// `cell + inline_storage_offset` (the address) at+/// `cell + plain_inline_storage_offset` (the address) at/// `cell + named_properties_offset`, and at-/// `cell + inline_storage_offset + 8 * index` the value of each named+/// `cell + plain_inline_storage_offset + 8 * index` the value of each named/// property (in shape order; NaN-boxed `undefined` for the ones not/// initialized yet) followed by NaN-boxed `undefined` up to/// `inline_capacity` values.@@ -1322,7 +1322,10 @@ pub struct ObjectAllocationInfo {pub template: Vec<u64>,pub shape_offset: u32,pub named_properties_offset: u32,+ /// Where the inline named storage of the objects of other classes starts.pub inline_storage_offset: u32,+ /// Where the inline named storage of plain objects starts, which is below `inline_storage_offset`.+ pub plain_inline_storage_offset: u32,/// `Object::inline_named_capacity` (u8).pub inline_capacity_offset: u32,/// `Object* libjs_jit_allocate_object(VM*, Shape*, u32 reserve)`.diff --git a/Libraries/LibJS/Rust/src/jit/allocation.rs b/Libraries/LibJS/Rust/src/jit/allocation.rsindex a989ea820c4..8e883c2accb 100644--- a/Libraries/LibJS/Rust/src/jit/allocation.rs+++ b/Libraries/LibJS/Rust/src/jit/allocation.rs@@ -113,6 +113,7 @@ pub fn allocation_infos<'d>(vm: &Vm, realm: Gc<Realm>, defer_gc: &'d DeferGc<'_>shape_offset: offset(core::mem::offset_of!(Object, shape)),named_properties_offset: offset(core::mem::offset_of!(Object, named_properties)),inline_storage_offset: offset(core::mem::offset_of!(Object, inline_named_storage)),+ plain_inline_storage_offset: offset(core::mem::offset_of!(Object, indexed_elements)),inline_capacity_offset: offset(core::mem::offset_of!(Object, inline_named_capacity)),slow_path: libjs_jit_allocate_object as *const () as u64,..ObjectAllocationInfo::default()diff --git a/Libraries/LibJS/Rust/src/layout/object.rs b/Libraries/LibJS/Rust/src/layout/object.rsindex 77e7187153c..27d7509f2db 100644--- a/Libraries/LibJS/Rust/src/layout/object.rs+++ b/Libraries/LibJS/Rust/src/layout/object.rs@@ -70,8 +70,11 @@ pub struct Object {/// ecmascript_function_flags for an ECMAScript function object, which have the highest bit set, or array_flags for/// an array. Zero for other objects.pub class_bits: Cell<u8>,- /// Points at `inline_named_storage` until the object needs more room.+ /// Points at the inline storage until the object needs more room.pub named_properties: Cell<*mut Value>,+ /// The packed or holey elements. A plain object has its inline storage start here instead, as long as+ /// `named_properties` points at this word, and moves it out of the way for its first indexed property. Nothing may+ /// read this word without knowing that the object has packed, holey or dictionary indexed storage.pub indexed_elements: Cell<*mut Value>,pub inline_named_storage: [Cell<Value>; 0],}diff --git a/Libraries/LibJS/Rust/src/runtime/abstract_operations.rs b/Libraries/LibJS/Rust/src/runtime/abstract_operations.rsindex b9e111f3ab2..c7ed0bbd9f1 100644--- a/Libraries/LibJS/Rust/src/runtime/abstract_operations.rs+++ b/Libraries/LibJS/Rust/src/runtime/abstract_operations.rs@@ -1687,7 +1687,7 @@ pub fn create_unmapped_arguments_object(vm: &Vm, arguments: &[Cell<Value>]) -> G// 2. Let obj be OrdinaryObjectCreate(%Object.prototype%, « [[ParameterMap]] »).// 3. Set obj.[[ParameterMap]] to undefined.- let object = Object::create_with_premade_shape(vm, realm.unmapped_arguments_object_shape());+ let object = Object::create_with_premade_shape_for_indexed_elements(vm, realm.unmapped_arguments_object_shape());// 4. Perform ! DefinePropertyOrThrow(obj, "length", PropertyDescriptor { [[Value]]: 𝔽(len), [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }).object.initialize_direct(diff --git a/Libraries/LibJS/Rust/src/runtime/object.rs b/Libraries/LibJS/Rust/src/runtime/object.rsindex f8e9507ae76..bc204a3a1e9 100644--- a/Libraries/LibJS/Rust/src/runtime/object.rs+++ b/Libraries/LibJS/Rust/src/runtime/object.rs@@ -484,9 +484,9 @@ const PLAIN_OBJECT_SIZE_CLASS_CELL_SIZES: [u32; PLAIN_OBJECT_INLINE_CAPACITIES.llet mut cell_sizes = [0; PLAIN_OBJECT_INLINE_CAPACITIES.len()];let mut index = 0;while index < cell_sizes.len() {- // NB: The inline named storage ends the object.- cell_sizes[index] =- (size_of::<Object>() + PLAIN_OBJECT_INLINE_CAPACITIES[index] as usize * size_of::<Value>()) as u32;+ // NB: The inline named storage starts at the indexed elements word, which it shares.+ cell_sizes[index] = (core::mem::offset_of!(Object, indexed_elements)+ + PLAIN_OBJECT_INLINE_CAPACITIES[index] as usize * size_of::<Value>()) as u32;index += 1;}cell_sizes@@ -646,10 +646,20 @@ impl Object {// 10.1.12 OrdinaryObjectCreate ( proto [ , additionalInternalSlotsList ] ), https://tc39.es/ecma262/#sec-ordinaryobjectcreatepub fn create(vm: &Vm, realm: Gc<Realm>, prototype: Option<Gc<Object>>) -> Gc<Object> {let Some(prototype) = prototype else {- return Self::create_in_size_class(vm, realm.empty_object_shape(), 0);+ let object = Self::new_with_shape(+ Self::CLASS,+ realm.empty_object_shape(),+ MayInterfereWithIndexedPropertyAccess::No,+ );+ return Self::allocate_plain_object(vm, object, 0);};if prototype == realm.object_prototype() {- return Self::create_in_size_class(vm, realm.new_object_shape(), 0);+ let object = Self::new_with_shape(+ Self::CLASS,+ realm.new_object_shape(),+ MayInterfereWithIndexedPropertyAccess::No,+ );+ return Self::allocate_plain_object(vm, object, 0);}let object = Self::new_with_prototype(vm, Self::CLASS, prototype, MayInterfereWithIndexedPropertyAccess::No);Self::allocate_plain_object(vm, object, 0)@@ -664,7 +674,13 @@ impl Object {}pub fn create_with_premade_shape(vm: &Vm, shape: Gc<Shape>) -> Gc<Object> {- Self::create_in_size_class(vm, shape, shape.property_count())+ let property_count = shape.property_count();+ // OPTIMIZATION: Objects with up to two properties, the most common ones, are in the first size class.+ if property_count <= u32::from(EMPTY_PLAIN_OBJECT_INLINE_CAPACITY) {+ let object = Self::new_with_shape(Self::CLASS, shape, MayInterfereWithIndexedPropertyAccess::No);+ return Self::allocate_plain_object(vm, object, 0);+ }+ Self::create_in_size_class(vm, shape, property_count)}/// OrdinaryObjectCreate(prototype) for the `this` of a construction of the function with `shared_data`, with@@ -689,6 +705,27 @@ impl Object {Self::create_in_size_class(vm, shape, shape.property_count().max(reserve))}+ /// A plain object of the shape that gets indexed elements right away.+ /// OPTIMIZATION: Its inline storage starts after the word that holds the elements, so that the first element does+ /// not have to move the properties out of the cell.+ pub fn create_with_premade_shape_for_indexed_elements(vm: &Vm, shape: Gc<Shape>) -> Gc<Object> {+ let property_count = shape.property_count();+ let size_class = plain_object_size_class(property_count + 1);+ let object = Self::new_with_shape(Self::CLASS, shape, MayInterfereWithIndexedPropertyAccess::No);+ object+ .inline_named_capacity+ .set(PLAIN_OBJECT_INLINE_CAPACITIES[size_class] - 1);+ let size_class_allocator = plain_object_size_classes(vm.heap())[size_class];+ let cell = vm+ .heap()+ .allocate_with_size_class(size_class_allocator, |_| object, Value::UNDEFINED);+ cell.named_properties.set(cell.inline_named_storage_pointer());+ if property_count > 0 {+ cell.ensure_named_storage_capacity(property_count);+ }+ cell+ }+/// A plain object of the shape, in the size class for that many properties.fn create_in_size_class(vm: &Vm, shape: Gc<Shape>, property_count: u32) -> Gc<Object> {let object = Self::new_with_shape(Self::CLASS, shape, MayInterfereWithIndexedPropertyAccess::No);@@ -700,11 +737,22 @@ impl Object {object.inline_named_capacity.set(PLAIN_OBJECT_INLINE_CAPACITIES[size_class]);+ // OPTIMIZATION: Most plain objects never get indexed properties, so their inline storage starts at the word+ // that would hold the indexed elements.+ object+ .indexed_elements+ .set(core::ptr::without_provenance_mut(Value::UNDEFINED.to_raw() as usize));let size_class_allocator = plain_object_size_classes(vm.heap())[size_class];- set_up_named_storage(- vm.heap()- .allocate_with_size_class(size_class_allocator, |_| object, Value::UNDEFINED),- )+ let cell = vm+ .heap()+ .allocate_with_size_class(size_class_allocator, |_| object, Value::UNDEFINED);+ debug_assert!(cell.named_properties.get().is_null());+ cell.named_properties.set(cell.indexed_elements.as_ptr().cast());+ let property_count = cell.shape().property_count();+ if property_count > 0 {+ cell.ensure_named_storage_capacity(property_count);+ }+ cell}pub(crate) fn as_gc(&self) -> Gc<Object> {@@ -3682,6 +3730,12 @@ impl Object {pub(crate) fn named_storage_is_inline(&self) -> bool {core::ptr::eq(self.named_properties.get(), self.inline_named_storage_pointer())+ || self.named_storage_overlaps_indexed_elements()+ }++ /// Whether the inline named storage of this plain object starts at the indexed elements word.+ fn named_storage_overlaps_indexed_elements(&self) -> bool {+ core::ptr::eq(self.named_properties.get(), self.indexed_elements.as_ptr().cast())}fn named_storage_external_memory_size(&self) -> usize {@@ -3747,7 +3801,13 @@ impl Object {if needed <= old_capacity {return;}- let new_capacity = needed.max(old_capacity.saturating_mul(2));+ self.move_named_storage_out_of_line(old_capacity, needed.max(old_capacity.saturating_mul(2)));+ }++ /// NB: The capacity of the storage never shrinks, which JIT code that added properties to an object it allocated+ /// relies on.+ fn move_named_storage_out_of_line(&self, old_capacity: u32, new_capacity: u32) {+ let overlapped_indexed_elements = self.named_storage_overlaps_indexed_elements();// NB: Callers may have given the object a shape with more properties than its storage has room for already, so// nothing may visit it before the new storage is in place, and cached property additions read their cache@@ -3762,6 +3822,23 @@ impl Object {object_flag::HAS_MALLOC_NAMED_STORAGE,new_storage,);+ if overlapped_indexed_elements {+ self.indexed_elements.set(core::ptr::null_mut());+ }+ }++ /// Frees up the indexed elements word, ahead of anything that reads or writes it.+ #[inline(always)]+ fn make_room_for_indexed_storage(&self) {+ if self.named_storage_overlaps_indexed_elements() {+ self.move_overlapping_named_storage_out_of_line();+ }+ }++ #[cold]+ fn move_overlapping_named_storage_out_of_line(&self) {+ let capacity = self.named_storage_capacity();+ self.move_named_storage_out_of_line(capacity, capacity);}// Indexed property storage@@ -3800,6 +3877,7 @@ impl Object {.borrow_mut().insert(core::ptr::from_ref(self).addr(), dictionary);} else {+ self.make_room_for_indexed_storage();self.indexed_elements.set(dictionary.cast());}}@@ -3813,14 +3891,16 @@ impl Object {}fn indexed_elements_capacity(&self) -> u32 {+ if !matches!(+ self.indexed_storage_kind(),+ IndexedStorageKind::Packed | IndexedStorageKind::Holey+ ) {+ return 0;+ }let elements = self.indexed_elements.get();if elements.is_null() {return 0;}- assert!(matches!(- self.indexed_storage_kind(),- IndexedStorageKind::Packed | IndexedStorageKind::Holey- ));// SAFETY: Packed and holey indexed storage is storage value_storage::allocate() returned.unsafe { value_storage::capacity(elements) }}@@ -3862,6 +3942,7 @@ impl Object {fn adopt_indexed_elements(&self, elements: *mut Value) {assert!(!self.is_ecmascript_function_object());+ self.make_room_for_indexed_storage();debug_assert!(self.indexed_elements.get().is_null() && !self.has_flag(object_flag::HAS_MALLOC_INDEXED_STORAGE));self.replace_storage(&self.indexed_elements,@@ -3872,6 +3953,9 @@ impl Object {fn free_indexed_elements(&self) {assert!(!self.is_ecmascript_function_object());+ if self.indexed_storage_kind() == IndexedStorageKind::None {+ return;+ }if self.indexed_storage_kind() == IndexedStorageKind::Dictionary {self.free_indexed_elements_dictionary();} else {@@ -3904,6 +3988,7 @@ impl Object {fn ensure_indexed_elements(&self, needed_capacity: u32) {assert!(!self.is_ecmascript_function_object());+ self.make_room_for_indexed_storage();if !self.indexed_elements.get().is_null() && self.indexed_elements_capacity() >= needed_capacity {return;}@@ -4213,6 +4298,7 @@ impl Object {if new_size == 0 {return true;}+ self.make_room_for_indexed_storage();self.indexed_storage_kind.set(IndexedStorageKind::Holey);self.indexed_array_like_size.set(new_size);return true;diff --git a/Tests/LibJS/Runtime/object-indexed-and-inline-named-properties.js b/Tests/LibJS/Runtime/object-indexed-and-inline-named-properties.jsnew file mode 100644index 00000000000..81f4a93589b--- /dev/null+++ b/Tests/LibJS/Runtime/object-indexed-and-inline-named-properties.js@@ -0,0 +1,223 @@+// Plain objects keep their first named property where indexed storage would go until they get an indexed property.++function expectProperties(object, a, b) {+ expect(object.a).toBe(a);+ expect(object.b).toBe(b);+}++test("named properties survive the first indexed property", () => {+ const object = { a: 1, b: 2 };+ object[0] = "zero";+ expectProperties(object, 1, 2);+ expect(object[0]).toBe("zero");+ expect(Object.keys(object)).toEqual(["0", "a", "b"]);+});++test("a full inline storage still takes more named properties afterwards", () => {+ const object = { a: 1, b: 2 };+ object[5] = "five";+ for (let i = 0; i < 40; ++i) object[`p${i}`] = i;+ expectProperties(object, 1, 2);+ expect(object[5]).toBe("five");+ for (let i = 0; i < 40; ++i) expect(object[`p${i}`]).toBe(i);+});++test("indexed properties after named storage outgrew the cell", () => {+ const object = {};+ for (let i = 0; i < 40; ++i) object[`p${i}`] = i;+ expect(object[0]).toBeUndefined();+ object[0] = "zero";+ object[1] = "one";+ expect(object[0]).toBe("zero");+ expect(object[1]).toBe("one");+ for (let i = 0; i < 40; ++i) expect(object[`p${i}`]).toBe(i);+});++test("reading indexed properties of an object without them", () => {+ const object = { a: 1.5, b: "string" };+ for (let i = 0; i < 3; ++i) expect(object[i]).toBeUndefined();+ expect(0 in object).toBeFalse();+ expect(Object.keys(object)).toEqual(["a", "b"]);+ expect(Object.getOwnPropertyDescriptor(object, "0")).toBeUndefined();+ expect(delete object[0]).toBeTrue();+ expectProperties(object, 1.5, "string");+});++test("array methods on plain objects", () => {+ const pushed = { a: 1, b: 2, length: 0 };+ Array.prototype.push.call(pushed, "x", "y");+ expect(pushed.length).toBe(2);+ expect(pushed[1]).toBe("y");+ expect(pushed.a).toBe(1);++ const sliced = Array.prototype.slice.call({ a: 1, 0: "x", 1: "y", length: 2 });+ expect(sliced).toEqual(["x", "y"]);+});++test("sparse and non-default indexed properties", () => {+ const sparse = { a: 1, b: 2 };+ sparse[1000000] = "far";+ expectProperties(sparse, 1, 2);+ expect(sparse[1000000]).toBe("far");++ const accessor = { a: 1, b: 2 };+ Object.defineProperty(accessor, 0, { get: () => "got", enumerable: false });+ expectProperties(accessor, 1, 2);+ expect(accessor[0]).toBe("got");+ accessor[1] = "one";+ expect(accessor[1]).toBe("one");++ const frozen = { a: 1, b: 2, 0: "zero" };+ Object.freeze(frozen);+ expectProperties(frozen, 1, 2);+ expect(frozen[0]).toBe("zero");+});++test("deleting the elements and adding them back", () => {+ const object = { a: 1, b: 2 };+ object[0] = "zero";+ delete object[0];+ expect(object[0]).toBeUndefined();+ expectProperties(object, 1, 2);+ object[0] = "again";+ expect(object[0]).toBe("again");+ expectProperties(object, 1, 2);+});++test("prototype and dictionary objects", () => {+ const prototype = { a: 1 };+ const child = Object.create(prototype);+ prototype[3] = "three";+ expect(child[3]).toBe("three");+ expect(child.a).toBe(1);++ const dictionary = {};+ for (let i = 0; i < 200; ++i) dictionary[`key${i}`] = i;+ for (let i = 0; i < 190; ++i) delete dictionary[`key${i}`];+ dictionary[0] = "zero";+ expect(dictionary[0]).toBe("zero");+ for (let i = 190; i < 200; ++i) expect(dictionary[`key${i}`]).toBe(i);+});++// The rest runs often enough for compiled code to allocate the objects and add their properties.+const ITERATIONS = 20000;++test("object literals with computed keys in between", () => {+ function literal(key, value) {+ return { a: value, [key]: "computed", b: value + 1, c: value + 2 };+ }+ for (let i = 0; i < ITERATIONS; ++i) {+ const object = literal(i % 16 === 0 ? 0 : "other", i);+ if (object.a !== i || object.b !== i + 1 || object.c !== i + 2) expect().fail();+ }+ const object = literal(0, 7);+ expect(object[0]).toBe("computed");+ expect(object.c).toBe(9);+});++test("constructors that add named properties after indexed ones", () => {+ function Constructed(indexed, value) {+ if (indexed) this[0] = "zero";+ this.a = value;+ this.b = value + 1;+ this.c = value + 2;+ }+ for (let i = 0; i < ITERATIONS; ++i) {+ const object = new Constructed(i % 16 === 0, i);+ if (object.a !== i || object.b !== i + 1 || object.c !== i + 2) expect().fail();+ if (i % 16 === 0 && object[0] !== "zero") expect().fail();+ }+});++test("named property additions that grow the storage", () => {+ function grow(object, value) {+ object.a = value;+ object.b = value;+ object.c = value;+ object.d = value;+ object.e = value;+ return object;+ }+ for (let i = 0; i < ITERATIONS; ++i) {+ const object = grow({}, i);+ if (i % 16 === 0) object[0] = i;+ if (object.a !== i || object.e !== i) expect().fail();+ if (i % 16 === 0 && object[0] !== i) expect().fail();+ }+});++test("indexed accesses in loops on objects of varying kinds", () => {+ function sum(object, count) {+ let result = 0;+ for (let i = 0; i < count; ++i) result += object[0] === undefined ? 1 : object[0];+ return result;+ }+ const packed = [2];+ const plain = { a: 1.5, b: 2.5 };+ const callable = function () {};+ for (let i = 0; i < 2000; ++i) sum(packed, 20);+ expect(sum(plain, 20)).toBe(20);+ expect(sum(callable, 20)).toBe(20);+ for (let i = 0; i < 2000; ++i) {+ sum(packed, 20);+ sum(plain, 20);+ sum(callable, 20);+ }+ expect(sum(packed, 20)).toBe(40);+ expect(plain.a).toBe(1.5);++ function store(object, count) {+ for (let i = 0; i < count; ++i) object[i % 2] = i;+ }+ for (let i = 0; i < 2000; ++i) store([0, 0], 20);+ const stored = { a: 1, b: 2 };+ store(stored, 20);+ expect(stored[1]).toBe(19);+ expectProperties(stored, 1, 2);+});++test("objects survive a garbage collection with either storage", () => {+ const objects = [];+ for (let i = 0; i < 1000; ++i) {+ const object = { a: { value: i }, b: `string${i}` };+ if (i % 2 === 0) object[0] = { value: i };+ objects.push(object);+ }+ gc();+ for (let i = 0; i < 1000; ++i) {+ expect(objects[i].a.value).toBe(i);+ expect(objects[i].b).toBe(`string${i}`);+ if (i % 2 === 0) expect(objects[i][0].value).toBe(i);+ }+});++test("strict arguments keep their properties and elements as they grow", () => {+ "use strict";++ function make() {+ return arguments;+ }++ const args = make(1, 2, 3);+ expect(args.length).toBe(3);+ expect(args[0]).toBe(1);+ expect(args[2]).toBe(3);+ expect(typeof args[Symbol.iterator]).toBe("function");+ expect([...args]).toEqual([1, 2, 3]);++ for (let i = 0; i < 40; ++i) args["named" + i] = i;+ args[10] = "sparse";+ expect(args.length).toBe(3);+ expect(args[2]).toBe(3);+ expect(args[10]).toBe("sparse");+ expect(args.named39).toBe(39);+ expect(typeof args[Symbol.iterator]).toBe("function");++ const empty = make();+ expect(empty.length).toBe(0);+ empty[0] = "first";+ empty.extra = "named";+ expect(empty[0]).toBe("first");+ expect(empty.extra).toBe("named");+ expect(empty.length).toBe(0);+});