Skip to content

Truly independent web browser

LibJS: Cache the shape of new objects by their constructor

Andreas Kling5dccdb3193f2
diff --git a/Libraries/LibJS/Rust/src/interpreter/slow_paths/calls.rs b/Libraries/LibJS/Rust/src/interpreter/slow_paths/calls.rs
index 97ea2d1c5c9..75f529f74ce 100644
--- a/Libraries/LibJS/Rust/src/interpreter/slow_paths/calls.rs
+++ b/Libraries/LibJS/Rust/src/interpreter/slow_paths/calls.rs
@@ -26,7 +26,7 @@ use crate::layout::feedback::CallFeedbackForwarding;
use crate::layout::value::Value;
use crate::runtime::abstract_operations::{
self, CallerMode, create_mapped_arguments_object, create_unmapped_arguments_object, function_object_as_object,
- function_with_frame_as_this_environment, get_prototype_from_constructor, get_this_environment, perform_eval,
+ function_with_frame_as_this_environment, get_this_environment, perform_eval,
};
use crate::runtime::array::Array;
use crate::runtime::bound_function::BoundFunction;
@@ -43,7 +43,6 @@ use crate::runtime::error::ErrorKind;
use crate::runtime::error_types::ErrorType;
use crate::runtime::function_environment::FunctionEnvironment;
use crate::runtime::function_object::FunctionObject;
-use crate::runtime::intrinsics::Intrinsics;
use crate::runtime::native_javascript_backed_function::NativeJavaScriptBackedFunction;
use crate::runtime::object::{Object, StackFrameInfo};
use crate::runtime::property_attributes::DEFAULT_ATTRIBUTES;
@@ -613,17 +612,11 @@ pub fn call_construct(
// local keeps from happening (see `bytecode::flushing`).
&& let Some(executable) = function.bytecode_executable()
{
- let prototype = asm_try!(
+ // NB: With room for the properties the constructor is known to add.
+ let this_object = asm_try!(
vm,
pc,
- get_prototype_from_constructor(vm, function.as_function_object_gc(), Intrinsics::object_prototype)
- );
- // NB: OrdinaryObjectCreate(prototype), with room for the properties the constructor is known to add.
- let this_object = Object::create_for_construct(
- vm,
- vm.current_realm().expect("a construction runs in a realm"),
- prototype,
- function.shared_data(),
+ Object::create_from_constructor_for_construct(vm, function.as_function_object_gc(), function.shared_data())
);
let Some(context) = vm.push_inline_frame(
function,
@@ -786,17 +779,11 @@ fn super_call_with_arguments(
if function.constructor_kind() == ConstructorKind::Base {
// 10.2.2 [[Construct]], step 3.a: Let thisArgument be ? OrdinaryCreateFromConstructor(newTarget,
// "%Object.prototype%").
- let prototype = asm_try!(
- vm,
- pc,
- get_prototype_from_constructor(vm, new_target, Intrinsics::object_prototype)
- );
// NB: With room for the properties the constructor is known to add.
- this_object = Some(Object::create_for_construct(
+ this_object = Some(asm_try!(
vm,
- vm.current_realm().expect("a construction runs in a realm"),
- prototype,
- function.shared_data(),
+ pc,
+ Object::create_from_constructor_for_construct(vm, new_target, function.shared_data())
));
}
let Some(context) = vm.push_inline_frame_without_this(
diff --git a/Libraries/LibJS/Rust/src/interpreter/vm.rs b/Libraries/LibJS/Rust/src/interpreter/vm.rs
index e7b6eb7ddc0..3d0ab9c78c0 100644
--- a/Libraries/LibJS/Rust/src/interpreter/vm.rs
+++ b/Libraries/LibJS/Rust/src/interpreter/vm.rs
@@ -86,7 +86,7 @@ use crate::runtime::primitive_string::PrimitiveString;
use crate::runtime::promise::{Promise, PromiseState, RejectionOperation};
use crate::runtime::property_key::PropertyKey;
use crate::runtime::reference::{BaseType, Reference};
-use crate::runtime::shape::PrototypeTransitionCache;
+use crate::runtime::shape::{ConstructShapeCache, PrototypeTransitionCache};
use crate::runtime::shared_function_instance_data::SharedFunctionInstanceData;
use crate::runtime::source_text_module::SourceTextModule;
use crate::runtime::symbol::{self, GlobalSymbolRegistry, Symbol, enumerate_well_known_symbols};
@@ -575,6 +575,7 @@ pub struct Vm {
static_property_lookup_caches: StaticPropertyLookupCaches,
keyed_property_lookup_cache: KeyedPropertyLookupCache,
prototype_transition_cache: Box<PrototypeTransitionCache>,
+ construct_shape_cache: Box<ConstructShapeCache>,
/// Like the keyed property lookup cache, how string-keyed PutByValue instructions whose own caches gave up put
/// properties: the writable own data properties they change and the properties they add, by shape and name (see
/// put_by_value_with_keyed_store_cache()).
@@ -739,6 +740,7 @@ impl Vm {
static_property_lookup_caches: StaticPropertyLookupCaches::new(),
keyed_property_lookup_cache: KeyedPropertyLookupCache::new(),
prototype_transition_cache: Box::new(PrototypeTransitionCache::new()),
+ construct_shape_cache: Box::new(ConstructShapeCache::new()),
keyed_property_store_cache: KeyedPropertyLookupCache::new(),
keyed_property_store_scratch_cache: PropertyLookupCache::new(),
host_ensure_can_add_private_element: Cell::new(default_host_ensure_can_add_private_element),
@@ -1573,6 +1575,7 @@ impl Vm {
self.static_property_lookup_caches.remove_dead_entries(sweep);
self.keyed_property_lookup_cache.remove_dead_entries(sweep);
self.prototype_transition_cache.remove_dead_entries(sweep);
+ self.construct_shape_cache.remove_dead_entries(sweep);
self.keyed_property_store_cache.remove_dead_entries(sweep);
self.jit.dependents.remove_dead_entries(sweep);
}
@@ -1610,6 +1613,10 @@ impl Vm {
&self.prototype_transition_cache
}
+ pub fn construct_shape_cache(&self) -> &ConstructShapeCache {
+ &self.construct_shape_cache
+ }
+
pub fn keyed_property_store_cache(&self) -> &KeyedPropertyLookupCache {
&self.keyed_property_store_cache
}
diff --git a/Libraries/LibJS/Rust/src/jit/calls.rs b/Libraries/LibJS/Rust/src/jit/calls.rs
index 4b14cc2c8da..dd13add9a69 100644
--- a/Libraries/LibJS/Rust/src/jit/calls.rs
+++ b/Libraries/LibJS/Rust/src/jit/calls.rs
@@ -37,8 +37,8 @@ use crate::layout::function_object::{EcmascriptFunctionObject, FunctionObject, N
use crate::layout::object::{IndexedStorageKind, Object};
use crate::layout::value::Value;
use crate::runtime::abstract_operations::{
- call_function_object, create_unmapped_arguments_object, function_object_as_object, get_prototype_from_constructor,
- length_of_array_like, throw_if_too_many_arguments,
+ call_function_object, create_unmapped_arguments_object, function_object_as_object, length_of_array_like,
+ throw_if_too_many_arguments,
};
use crate::runtime::array::Array;
use crate::runtime::bound_function::BoundFunction;
@@ -47,7 +47,6 @@ use crate::runtime::ecmascript_function_object::{as_ecmascript_function_object,
use crate::runtime::error::ErrorKind;
use crate::runtime::error_types::ErrorType;
use crate::runtime::function_prototype::FunctionPrototype;
-use crate::runtime::intrinsics::Intrinsics;
use crate::runtime::iterator::get_iterator_values;
use crate::runtime::math_object;
use crate::runtime::native_javascript_backed_function::NativeJavaScriptBackedFunction;
@@ -205,15 +204,8 @@ fn construct_ecmascript_function_from_jit(
if kind == ConstructorKind::Base {
// a. Let thisArgument be ? OrdinaryCreateFromConstructor(newTarget, "%Object.prototype%").
// NB: With room for the properties the constructor is known to add.
- match get_prototype_from_constructor(vm, new_target, Intrinsics::object_prototype) {
- Ok(prototype) => {
- this_argument = Some(Object::create_for_construct(
- vm,
- vm.current_realm().expect("a construction runs in a realm"),
- prototype,
- function.shared_data(),
- ));
- }
+ match Object::create_from_constructor_for_construct(vm, new_target, function.shared_data()) {
+ Ok(object) => this_argument = Some(object),
Err(throw) => return handle_asm_exception(vm, site.pc, throw.value()),
}
}
diff --git a/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rs b/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rs
index acbe9fd26d9..62beb9813f5 100644
--- a/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rs
+++ b/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rs
@@ -28,9 +28,7 @@ use crate::layout::function_object::{RawNativeFunction, ecmascript_function_flag
use crate::layout::member::NullableMember;
use crate::layout::object::{IndexedStorageKind, Object};
use crate::layout::value::Value;
-use crate::runtime::abstract_operations::{
- create_unmapped_arguments_object, get_prototype_from_constructor, new_call_environment,
-};
+use crate::runtime::abstract_operations::{create_unmapped_arguments_object, new_call_environment};
use crate::runtime::async_function_driver_wrapper::AsyncFunctionDriverWrapper;
use crate::runtime::async_generator::AsyncGenerator;
use crate::runtime::class_field_definition::{ClassElementName, ClassFieldDefinition};
@@ -41,7 +39,6 @@ use crate::runtime::function_environment::FunctionEnvironment;
use crate::runtime::function_object::{FUNCTION_OBJECT_METHODS, FunctionObject};
use crate::runtime::function_prototype::FunctionPrototype;
use crate::runtime::generator_object::{GeneratingFunction, GeneratorObject};
-use crate::runtime::intrinsics::Intrinsics;
use crate::runtime::object::{
MayInterfereWithIndexedPropertyAccess, ObjectMethods, PrivateElement, StackFrameInfo, allocate_object,
};
@@ -720,13 +717,11 @@ impl EcmascriptFunctionObject {
if kind == ConstructorKind::Base {
// a. Let thisArgument be ? OrdinaryCreateFromConstructor(newTarget, "%Object.prototype%").
// NB: With room for the properties the constructor is known to add.
- let prototype = get_prototype_from_constructor(vm, new_target, Intrinsics::object_prototype)?;
- this_argument = Some(Object::create_for_construct(
+ this_argument = Some(Object::create_from_constructor_for_construct(
vm,
- vm.current_realm().expect("a construction runs in a realm"),
- prototype,
+ new_target,
function.shared_data(),
- ));
+ )?);
}
// 4. Let calleeContext be PrepareForOrdinaryCall(F, newTarget).
diff --git a/Libraries/LibJS/Rust/src/runtime/object.rs b/Libraries/LibJS/Rust/src/runtime/object.rs
index 3bd9e35c2ad..f3fb439f2e4 100644
--- a/Libraries/LibJS/Rust/src/runtime/object.rs
+++ b/Libraries/LibJS/Rust/src/runtime/object.rs
@@ -31,13 +31,14 @@ pub use crate::layout::object::{INDEXED_ELEMENTS_HEADER_SIZE, IndexedStorageKind
use crate::layout::value::Value;
use crate::layout_forward::RawNativeFunctionPointer;
use crate::runtime::abstract_operations::{
- call, call_function_object, function_object_as_object, validate_and_apply_property_descriptor,
+ call, call_function_object, function_object_as_object, get_prototype_from_constructor,
+ validate_and_apply_property_descriptor,
};
use crate::runtime::accessor::Accessor;
use crate::runtime::array::{ARRAY_OBJECT_METHODS, Array};
use crate::runtime::class_field_definition::{ClassElementName, ClassFieldDefinition, ClassFieldInitializer};
use crate::runtime::completion::{Must, ThrowCompletionOr};
-use crate::runtime::ecmascript_function_object::ECMASCRIPT_FUNCTION_OBJECT_METHODS;
+use crate::runtime::ecmascript_function_object::{ECMASCRIPT_FUNCTION_OBJECT_METHODS, as_ecmascript_function_object};
use crate::runtime::error::{ErrorKind, error_data_of_error};
use crate::runtime::error_data::ErrorData;
use crate::runtime::error_types::ErrorType;
@@ -692,6 +693,40 @@ impl Object {
Self::create_in_size_class(vm, shape, reserve)
}
+ /// OrdinaryCreateFromConstructor(constructor, "%Object.prototype%") for the `this` of a construction of the
+ /// function with `shared_data` and `constructor` as the new target, in the current realm (see
+ /// create_for_construct()).
+ pub fn create_from_constructor_for_construct(
+ vm: &Vm,
+ constructor: Gc<FunctionObject>,
+ shared_data: Gc<SharedFunctionInstanceData>,
+ ) -> ThrowCompletionOr<Gc<Object>> {
+ let realm = vm.current_realm().expect("a construction runs in a realm");
+ let constructor_object = function_object_as_object(constructor);
+ // OPTIMIZATION: The shape a construct with the constructor gave its object before, while the constructor's
+ // "prototype" still holds its prototype. Reading the own data property has no side effects.
+ let cache = vm.construct_shape_cache();
+ if let Some(shape) = cache.get(constructor_object, realm) {
+ let reserve = shared_data.construct_reserve(shape);
+ return Ok(Self::create_in_size_class(vm, shape, reserve));
+ }
+ let prototype = get_prototype_from_constructor(
+ vm,
+ constructor,
+ crate::runtime::intrinsics::Intrinsics::object_prototype,
+ )?;
+ let object = Self::create_for_construct(vm, realm, prototype, shared_data);
+ if as_ecmascript_function_object(constructor).is_some()
+ && let Some(metadata) = constructor_object.shape().lookup(&vm.names.prototype)
+ && let value = constructor_object.get_direct(metadata.offset)
+ && value.is_object()
+ && value.as_object() == prototype
+ {
+ cache.set(constructor_object, metadata.offset, object.shape());
+ }
+ Ok(object)
+ }
+
/// Like create_with_premade_shape(), in the size class for at least `reserve` properties, for properties that will
/// be added right away.
pub fn create_with_premade_shape_and_reserve(vm: &Vm, shape: Gc<Shape>, reserve: u32) -> Gc<Object> {
diff --git a/Libraries/LibJS/Rust/src/runtime/shape.rs b/Libraries/LibJS/Rust/src/runtime/shape.rs
index b2567a4e761..c63463a5c42 100644
--- a/Libraries/LibJS/Rust/src/runtime/shape.rs
+++ b/Libraries/LibJS/Rust/src/runtime/shape.rs
@@ -336,6 +336,85 @@ fn prototype_address(prototype: Option<Gc<Object>>) -> usize {
prototype.map_or(0, |prototype| prototype.as_ptr().addr())
}
+/// The shape OrdinaryCreateFromConstructor() gave a new object for `constructor`: the empty object shape of a realm
+/// with the prototype that the "prototype" data property of the constructor held, at `prototype_offset` in objects of
+/// `constructor_shape`.
+#[derive(Clone, Copy, Default)]
+struct ConstructShape {
+ constructor: Option<Gc<Object>>,
+ constructor_shape: Option<Gc<Shape>>,
+ prototype_offset: u32,
+ this_shape: Option<Gc<Shape>>,
+}
+
+const CONSTRUCT_SHAPE_CACHE_INDEX_BITS: u32 = 6;
+
+/// The shapes of the objects that constructs of ECMAScript functions created most recently, by the constructor (the
+/// new target), so that a construct does not have to look up "prototype" and the prototype transition every time. An
+/// entry holds while the constructor keeps its shape, which is no dictionary shape, and its "prototype" slot still
+/// holds the prototype of the shape.
+///
+/// The cache does not keep its cells alive: the VM's sweep callback forgets entries whose cells died.
+pub struct ConstructShapeCache {
+ entries: [Cell<ConstructShape>; 1 << CONSTRUCT_SHAPE_CACHE_INDEX_BITS],
+}
+
+impl ConstructShapeCache {
+ pub fn new() -> Self {
+ Self {
+ entries: core::array::from_fn(|_| Cell::new(ConstructShape::default())),
+ }
+ }
+
+ fn entry(&self, constructor: Gc<Object>) -> &Cell<ConstructShape> {
+ let hash = (constructor.as_ptr().addr() as u32).wrapping_mul(0x9e37_79b9);
+ &self.entries[(hash >> (32 - CONSTRUCT_SHAPE_CACHE_INDEX_BITS)) as usize]
+ }
+
+ /// The shape of an object a construct with `constructor` as the new target creates in `realm`, if it is known.
+ pub fn get(&self, constructor: Gc<Object>, realm: Gc<Realm>) -> Option<Gc<Shape>> {
+ let entry = self.entry(constructor).get();
+ if entry.constructor != Some(constructor) || entry.constructor_shape != Some(constructor.shape()) {
+ return None;
+ }
+ let this_shape = entry.this_shape?;
+ if this_shape.realm() != realm {
+ return None;
+ }
+ let prototype = constructor.get_direct(entry.prototype_offset);
+ (prototype.is_object() && this_shape.prototype() == Some(prototype.as_object())).then_some(this_shape)
+ }
+
+ /// Remembers that a construct with `constructor` as the new target created an object of `this_shape`, whose
+ /// prototype the constructor holds in its own "prototype" data property at `prototype_offset`.
+ pub fn set(&self, constructor: Gc<Object>, prototype_offset: u32, this_shape: Gc<Shape>) {
+ let constructor_shape = constructor.shape();
+ if constructor_shape.is_dictionary() {
+ return;
+ }
+ self.entry(constructor).set(ConstructShape {
+ constructor: Some(constructor),
+ constructor_shape: Some(constructor_shape),
+ prototype_offset,
+ this_shape: Some(this_shape),
+ });
+ }
+
+ pub fn remove_dead_entries(&self, sweep: &Sweep<'_>) {
+ for entry in &self.entries {
+ let construct_shape = entry.get();
+ if construct_shape.constructor.is_some_and(|cell| sweep.is_dead(cell))
+ || construct_shape
+ .constructor_shape
+ .is_some_and(|cell| sweep.is_dead(cell))
+ || construct_shape.this_shape.is_some_and(|cell| sweep.is_dead(cell))
+ {
+ entry.set(ConstructShape::default());
+ }
+ }
+ }
+}
+
/// A prototype transition the VM's cache of them remembers: from shape `from` to prototype `prototype` (see
/// prototype_address()) leads to `target`.
#[derive(Clone, Copy, Default)]
@@ -396,6 +475,12 @@ impl PrototypeTransitionCache {
}
}
+impl Default for ConstructShapeCache {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
impl Default for PrototypeTransitionCache {
fn default() -> Self {
Self::new()
diff --git a/Tests/LibJS/Runtime/classes/class-super-call-paths.js b/Tests/LibJS/Runtime/classes/class-super-call-paths.js
index 80686f36aa8..e9dd0493fb4 100644
--- a/Tests/LibJS/Runtime/classes/class-super-call-paths.js
+++ b/Tests/LibJS/Runtime/classes/class-super-call-paths.js
@@ -561,3 +561,36 @@ describe("super() with arguments as operands", () => {
expect(await b.asynchronous()).toBe(2);
});
});
+
+describe("prototypes of new objects", () => {
+ test("a changed prototype property of the new target is used", () => {
+ function Plain() {
+ this.a = 1;
+ }
+ class A {
+ constructor() {
+ this.a = 1;
+ }
+ }
+ class B extends A {
+ constructor() {
+ super();
+ }
+ }
+ function Target() {}
+ repeat(i => {
+ const prototype = { i };
+ Plain.prototype = prototype;
+ Target.prototype = prototype;
+ expect(Object.getPrototypeOf(new Plain())).toBe(prototype);
+ expect(Object.getPrototypeOf(Reflect.construct(A, [], Target))).toBe(prototype);
+ expect(Object.getPrototypeOf(Reflect.construct(B, [], Target))).toBe(prototype);
+ if (i % 100 === 0) {
+ Plain.prototype = 1;
+ expect(Object.getPrototypeOf(new Plain())).toBe(Object.prototype);
+ Target.prototype = null;
+ expect(Object.getPrototypeOf(Reflect.construct(B, [], Target))).toBe(Object.prototype);
+ }
+ });
+ });
+});