Truly independent web browser
LibJS: Define literal fields of inlined derived constructs in JIT code
Andreas Kling6c76b11f3f42
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs b/Libraries/LibJS/JIT/Rust/src/builder/inlining.rsindex e3635aeb7f2..50da7f7e1c1 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs@@ -1732,6 +1732,93 @@ impl<'a> GraphBuilder<'a> {Ok(Some(Flow::Ended))}+ /// `BindThisFromSuperCall` in an inlined construct of a derived+ /// constructor whose fields JIT code can define (see+ /// `ExecutableSnapshot::derived_instance_fields`), whose `this` is still+ /// empty there and whose super() created `this` in the graph: binds it+ /// and defines the fields after checking that `this` has the shape they+ /// start from. Returns false, having built nothing, otherwise.+ pub(super) fn try_build_bind_this_defining_fields(&mut self, result: Operand) -> Result<bool, CompileFailure> {+ if self+ .function+ .inline+ .as_ref()+ .and_then(|call| call.derived_construct)+ .is_none()+ || !self.may_speculate(ExitKind::BadShape)+ {+ return Ok(false);+ }+ let Some(fields) = self.function.executable.derived_instance_fields.clone() else {+ return Ok(false);+ };+ let this_register = Operand::from_raw(THIS_VALUE_REGISTER);+ let this_value = self.read(this_register)?;+ if self.graph.constant_value(this_value) != Some(value::EMPTY) {+ return Ok(false);+ }+ let object = self.read(result)?;+ let allocation = self.graph.unrefined(object);+ let Op::AllocateObject {+ shape: allocated_shape,+ property_count,+ reserve,+ } = self.graph.node(allocation).op+ else {+ return Ok(false);+ };+ let added_count = fields.fields.iter().map(|(offset, _, _)| offset + 1).max().unwrap_or(0);+ let reserve = reserve.max(added_count);+ if self.runtime.object_allocation.size_class_for(reserve).is_none() {+ return Ok(false);+ }+ self.graph.nodes[allocation.index()].op = Op::AllocateObject {+ shape: allocated_shape,+ property_count,+ reserve,+ };++ // NB: The shape check exits before `this` is bound, to the BindThisFromSuperCall in the interpreter.+ let object = self.check_shapes(+ object,+ &[ShapeCheck {+ shape: fields.shape,+ dictionary_generation: None,+ }],+ );+ // 13.3.7.1 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation+ // 9. Perform ? BindThisValue(thisER, result).+ // NB: The result of the inlined construct is its `this`, an object.+ self.write(this_register, object)?;+ // 10. Let funcObj be thisER.[[FunctionObject]].+ // 11. Assert: funcObj is an ECMAScript function object.+ // 12. Perform ? InitializeInstanceElements(result, funcObj).+ // NB: The fields have literal values, so this cannot throw, and since `this` has the shape the fields start+ // from (checked above), which allows extensions and has none of their names, each field adds its property+ // or sets the value of an earlier field of the same name.+ for (offset, value, added) in fields.fields {+ let value = self.constant(value);+ match added {+ Some(shape) => {+ self.embed(shape);+ let address = self.cell_address(object);+ self.emit(+ Op::AddNamed {+ offset,+ shape,+ property_count: offset + 1,+ },+ vec![object, value, address],+ None,+ );+ }+ None => self.store_named_holding(object, offset, value, true),+ }+ }+ // 13. Return result.+ Ok(true)+ }+/// `BindThisFromSuperCall` in an inlined construct of a derived/// constructor with fields or private methods, whose `this` is still/// empty there (see `calls_super_once_before_returning()`): its slowdiff --git a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs b/Libraries/LibJS/JIT/Rust/src/builder/mod.rsindex 77b34382a66..af9ead09daa 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/mod.rs@@ -1658,11 +1658,13 @@ impl<'a> GraphBuilder<'a> {}}Instruction::BindThisFromSuperCall { result } => {- if let Some(flow) = self.try_build_bind_this_initializing_instance_elements(instruction, result)? {- return Ok(Some(flow));- }- if !self.try_build_bind_this_from_super_call(result)? {- return Ok(None);+ if !self.try_build_bind_this_defining_fields(result)? {+ if let Some(flow) = self.try_build_bind_this_initializing_instance_elements(instruction, result)? {+ return Ok(Some(flow));+ }+ if !self.try_build_bind_this_from_super_call(result)? {+ return Ok(None);+ }}}Instruction::SuperCall { .. } | Instruction::SuperCallWithForwardedArguments { .. } => {diff --git a/Libraries/LibJS/JIT/Rust/src/snapshot.rs b/Libraries/LibJS/JIT/Rust/src/snapshot.rsindex 591dddb10c2..c954e308c5c 100644--- a/Libraries/LibJS/JIT/Rust/src/snapshot.rs+++ b/Libraries/LibJS/JIT/Rust/src/snapshot.rs@@ -153,6 +153,23 @@ pub struct ExecutableSnapshot {/// InitializeInstanceElements defines them. `this` is created with the/// shape it has after that (see `ConstructTarget::this_shape`).pub literal_instance_fields: Option<Vec<(u32, u64)>>,+ /// For a derived constructor with instance elements among the inlining+ /// candidates whose constructs JIT code can inline: its fields, if they+ /// can be added to `this` like literal fields of a base constructor,+ /// starting from the shape `this` always had there so far.+ pub derived_instance_fields: Option<DerivedInstanceFields>,+}++/// The fields InitializeInstanceElements defines on `this` of a derived+/// constructor, which only has fields with string or symbol names and+/// literal initial values: from `shape`, which must not have their names+/// and allows extensions, in order, the property offset of each field, its+/// value, and the shape `this` gets if the field adds the property (the+/// same one as an earlier field otherwise).+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct DerivedInstanceFields {+ pub shape: CellId,+ pub fields: Vec<(u32, u64, Option<CellId>)>,}/// The global object and the global declarative environment of a realm, anddiff --git a/Libraries/LibJS/Rust/src/interpreter/slow_paths/calls.rs b/Libraries/LibJS/Rust/src/interpreter/slow_paths/calls.rsindex 75f529f74ce..169f49edf75 100644--- a/Libraries/LibJS/Rust/src/interpreter/slow_paths/calls.rs+++ b/Libraries/LibJS/Rust/src/interpreter/slow_paths/calls.rs@@ -956,6 +956,11 @@ fn bind_this_from_super_call_result(vm: &Vm, pc: u32, result: Gc<Object>) -> Opt// 10. Let funcObj be thisER.[[FunctionObject]].// 11. Assert: funcObj is an ECMAScript function object.// 12. Perform ? InitializeInstanceElements(result, funcObj).+ // NB: JIT code initializes objects of the shape it always had here like this does (see+ // EcmascriptFunctionObject::instance_elements_shape()).+ if f.has_class_data() {+ f.record_instance_elements_shape(vm, result.shape());+ }if let Err(throw) = result.initialize_instance_elements(vm, f) {return Some(handle_asm_exception(vm, pc, throw.value()));}diff --git a/Libraries/LibJS/Rust/src/jit/snapshot.rs b/Libraries/LibJS/Rust/src/jit/snapshot.rsindex 568f54b67c4..4c1ed8e7a0a 100644--- a/Libraries/LibJS/Rust/src/jit/snapshot.rs+++ b/Libraries/LibJS/Rust/src/jit/snapshot.rs@@ -15,12 +15,12 @@ use libjs_jit::bytecode::{EnvironmentCoordinate, ExceptionHandler, FrameLayout,use libjs_jit::code::ExitKind;use libjs_jit::snapshot::{AccessorFunctionSnapshot, CallFeedbackSnapshot, CellId, ClosureTemplateSnapshot, CompileOptions, ConstructTarget,- DirectCallTarget, DirectGetterFields, EnvironmentTemplateSnapshot, ExecutableSnapshot, FeedbackSnapshot,- ForwardedCallSnapshot, Forwarding, FunctionFrameFields, GlobalCacheSnapshot, GlobalValueSnapshot, GlobalsSnapshot,- InlinedFunctionSnapshot, InliningLimits, Intrinsic, KeyedFeedbackSnapshot, LexicalEnvironmentTemplateSnapshot,- NativeCallTarget, ObjectShapeCacheSnapshot, OrdinaryHasInstanceSnapshot, PropertyCacheEntrySnapshot,- PropertyCacheEntryType, PropertyCacheKind, PropertyCacheSnapshot, ShapeSnapshot, Snapshot, StressOptions,- SuperBaseSnapshot, SuperConstructTarget, TypedArraySnapshot,+ DerivedInstanceFields, DirectCallTarget, DirectGetterFields, EnvironmentTemplateSnapshot, ExecutableSnapshot,+ FeedbackSnapshot, ForwardedCallSnapshot, Forwarding, FunctionFrameFields, GlobalCacheSnapshot, GlobalValueSnapshot,+ GlobalsSnapshot, InlinedFunctionSnapshot, InliningLimits, Intrinsic, KeyedFeedbackSnapshot,+ LexicalEnvironmentTemplateSnapshot, NativeCallTarget, ObjectShapeCacheSnapshot, OrdinaryHasInstanceSnapshot,+ PropertyCacheEntrySnapshot, PropertyCacheEntryType, PropertyCacheKind, PropertyCacheSnapshot, ShapeSnapshot,+ Snapshot, StressOptions, SuperBaseSnapshot, SuperConstructTarget, TypedArraySnapshot,};use super::allocation::{@@ -124,8 +124,15 @@ struct SnapshotBuilder<'vm> {/// For the base constructors with fields among the inlining candidates, by index: the values of their fields (see/// `ExecutableSnapshot::literal_instance_fields`).literal_instance_fields: HashMap<u32, Vec<(u32, u64)>>,+ /// For the derived constructors with fields among the inlining candidates, by index: how they add their fields+ /// (see `ExecutableSnapshot::derived_instance_fields`).+ derived_instance_fields: HashMap<u32, DerivedInstanceFields>,}+/// The property offset of a literal field, its value, and the shape its definition gives the object if it adds the+/// property, if asked for (see `SnapshotBuilder::literal_field_definitions()`).+type FieldDefinition = (u32, u64, Option<CellId>);+/// The values of literal fields, by property offset (see `ExecutableSnapshot::literal_instance_fields`).type LiteralFieldValues = Vec<(u32, u64)>;@@ -919,6 +926,12 @@ impl SnapshotBuilder<'_> {self.literal_instance_fields.insert(*indices.last().expect("the chain ends with a base constructor"), fields);}+ for (level, index) in indices.iter().enumerate().take(chain.len() - 1) {+ let constructor = chain.get(level).expect("the level is in the chain");+ if let Some(fields) = self.derived_instance_fields(constructor) {+ self.derived_instance_fields.insert(*index, fields);+ }+ }if chain.len() == 1 {self.construct_this_shapes.insert(index, this_shape);}@@ -948,10 +961,51 @@ impl SnapshotBuilder<'_> {/// creates it with `shape`, by property offset, if its instance elements are only fields with string or symbol/// names whose initial values are no cells (from literals) or absent, and the shape `this` has after that.fn literal_instance_fields(- &self,+ &mut self,constructor: Gc<EcmascriptFunctionObject>,shape: Gc<Shape>,) -> Option<(Gc<Shape>, LiteralFieldValues)> {+ let (shape, fields) = self.literal_field_definitions(constructor, shape, false)?;+ Some((+ shape,+ fields.into_iter().map(|(offset, value, _)| (offset, value)).collect(),+ ))+ }++ /// How InitializeInstanceElements of the derived constructor `constructor` defines its fields on objects of the+ /// shape it always initialized so far (see `ExecutableSnapshot::derived_instance_fields`), if they are literal+ /// fields (see literal_instance_fields()) whose names objects of that shape do not have yet, and it allows+ /// extensions.+ fn derived_instance_fields(&mut self, constructor: Gc<EcmascriptFunctionObject>) -> Option<DerivedInstanceFields> {+ if constructor.constructor_kind() != ConstructorKind::Derived || !constructor.has_class_data() {+ return None;+ }+ let shape = constructor.instance_elements_shape()?;+ if shape.is_dictionary() || shape.is_non_extensible() {+ return None;+ }+ let own_property_count = shape.property_count();+ let (_, fields) = self.literal_field_definitions(constructor, shape, true)?;+ // NB: Defining a property the object has already may fail or change its attributes.+ if fields.iter().any(|(offset, _, _)| *offset < own_property_count) {+ return None;+ }+ Some(DerivedInstanceFields {+ shape: self.cell(shape),+ fields,+ })+ }++ /// The fields InitializeInstanceElements of `constructor` defines on an ordinary object of `shape`, if its instance+ /// elements are only fields with string or symbol names whose initial values are no cells (from literals) or+ /// absent: the shape the object has after that, and in order, each field's property offset, its value, and with+ /// `with_shapes` the shape the object gets if the field adds the property.+ fn literal_field_definitions(+ &mut self,+ constructor: Gc<EcmascriptFunctionObject>,+ shape: Gc<Shape>,+ with_shapes: bool,+ ) -> Option<(Gc<Shape>, Vec<FieldDefinition>)> {if constructor.private_methods_count() != 0 {return None;}@@ -973,16 +1027,16 @@ impl SnapshotBuilder<'_> {};// 7.3.33 DefineField ( receiver, fieldRecord ), https://tc39.es/ecma262/#sec-definefield// 6.b. Perform ? CreateDataPropertyOrThrow(receiver, fieldName, initValue).- // NB: `this` is a new ordinary object, whose only properties are the fields defined before, so this adds the- // property or sets the value of an earlier field of the same name, like the interpreter does.- let offset = match shape.lookup(key) {- Some(metadata) => metadata.offset,+ // NB: For a property the object has from an earlier field of the same name, this sets the value like the+ // interpreter does, and otherwise it adds the property.+ let (offset, added) = match shape.lookup(key) {+ Some(metadata) => (metadata.offset, None),None => {shape = shape.create_put_transition(self.vm, key, DEFAULT_ATTRIBUTES);- shape.property_count() - 1+ (shape.property_count() - 1, with_shapes.then(|| self.cell(shape)))}};- values.push((offset, value.0));+ values.push((offset, value.0, added));}Some((shape, values))}@@ -1148,21 +1202,11 @@ impl SnapshotBuilder<'_> {bound_arguments: core::mem::take(&mut self.bound_arguments),};- let construct_this_shape = entry- .function- .and_then(|function| self.indices.get(&function))- .and_then(|index| self.construct_this_shapes.get(index))- .copied();- let super_constructor = entry- .function- .and_then(|function| self.indices.get(&function))- .and_then(|index| self.super_constructors.get(index))- .copied();- let literal_instance_fields = entry- .function- .and_then(|function| self.indices.get(&function))- .and_then(|index| self.literal_instance_fields.get(index))- .cloned();+ let index = entry.function.and_then(|function| self.indices.get(&function));+ let construct_this_shape = index.and_then(|index| self.construct_this_shapes.get(index)).copied();+ let super_constructor = index.and_then(|index| self.super_constructors.get(index)).copied();+ let literal_instance_fields = index.and_then(|index| self.literal_instance_fields.get(index)).cloned();+ let derived_instance_fields = index.and_then(|index| self.derived_instance_fields.get(index)).cloned();let has_instance_elements =matches!(entry.function, Some(InlinedFunction::Ecmascript(function)) if function.has_class_data());let property_caches = executable@@ -1266,6 +1310,7 @@ impl SnapshotBuilder<'_> {super_constructor,has_instance_elements,literal_instance_fields,+ derived_instance_fields,// NB: Only the compiled function's own code creates bindings by name.identifiers: if entry.function.is_none() {executable@@ -1457,6 +1502,7 @@ pub fn capture_snapshot<'d>(construct_this_shapes: HashMap::new(),super_constructors: HashMap::new(),literal_instance_fields: HashMap::new(),+ derived_instance_fields: HashMap::new(),};builder.closure_templates =closure_template_snapshots(closure_templates.into_inner(), |sample| builder.cell(sample), defer_gc);diff --git a/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rs b/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rsindex 62beb9813f5..4ae5799ba8f 100644--- a/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rs+++ b/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rs@@ -61,6 +61,10 @@ struct ClassData {private_methods: Vec<PrivateElement>, // [[PrivateMethods]]/// The [[ClassFieldInitializerName]] of an initializer of a field whose key is computed.class_field_initializer_name: ClassFieldInitializerName,+ /// The shape of the objects InitializeInstanceElements initialized for this derived constructor, while it was+ /// always the same one (see record_instance_elements_shape()).+ instance_elements_shape: Option<Gc<Shape>>,+ instance_elements_shape_varies: bool,}/// The parts of a class constructor, or of a field initializer, that the interpreter does not read.@@ -1096,6 +1100,33 @@ impl EcmascriptFunctionObject {.get_or_init(Box::default)}+ /// Remembers that InitializeInstanceElements for this derived constructor initializes an object of `shape`, which+ /// JIT code can rely on while it is always the same one (see instance_elements_shape()).+ pub fn record_instance_elements_shape(&self, vm: &Vm, shape: Gc<Shape>) {+ let Some(class_data) = self.class_data() else {+ return;+ };+ {+ let class_data = class_data.borrow();+ if class_data.instance_elements_shape_varies || class_data.instance_elements_shape == Some(shape) {+ return;+ }+ }+ let mut class_data = class_data.borrow_mut(vm);+ if class_data.instance_elements_shape.is_some() {+ class_data.instance_elements_shape = None;+ class_data.instance_elements_shape_varies = true;+ } else {+ class_data.instance_elements_shape = Some(shape);+ }+ }++ /// The shape of every object InitializeInstanceElements initialized for this derived constructor so far, if there+ /// was one and it was always the same.+ pub fn instance_elements_shape(&self) -> Option<Gc<Shape>> {+ self.class_data()?.borrow().instance_elements_shape+ }+pub fn has_class_data(&self) -> bool {self.class_data().is_some_and(|class_data| {let class_data = class_data.borrow();diff --git a/Tests/LibJS/JIT/ir/inlining-constructs-with-fields.js b/Tests/LibJS/JIT/ir/inlining-constructs-with-fields.jsindex e586295b033..7af216d96ff 100644--- a/Tests/LibJS/JIT/ir/inlining-constructs-with-fields.js+++ b/Tests/LibJS/JIT/ir/inlining-constructs-with-fields.js@@ -1,6 +1,7 @@// REQUIRES: inline-allocation// A construct of a base constructor whose fields have literal values creates `this` with the shape it has after the-// fields and stores their values. A derived constructor with fields initializes them through the slow path of+// fields and stores their values. A derived constructor with literal fields adds them to `this` once it checked the+// shape they start from. One with private methods initializes its instance elements through the slow path of// BindThisFromSuperCall, in the published frames of the inlined construct.class A {@@ -16,20 +17,32 @@ class B extends A {super(x);}}+class C extends A {+ #m() {}+ constructor(x) {+ super(x);+ }+}function makeBase(i) {return new A(i).x;}function makeDerived(i) {return new B(i).x;}+function makeDerivedWithPrivateMethod(i) {+ return new C(i).x;+}jit.prepare(makeBase);jit.prepare(makeDerived);+jit.prepare(makeDerivedWithPrivateMethod);for (let i = 0; i < 10; ++i) {makeBase(i);makeDerived(i);+ makeDerivedWithPrivateMethod(i);}jit.compile(makeBase);jit.compile(makeDerived);+jit.compile(makeDerivedWithPrivateMethod);// CHECK-FUNCTION: makeBase// CHECK-PASS: graph building@@ -45,5 +58,14 @@ jit.compile(makeDerived);// CHECK-NOT: SuperCall// CHECK: AllocateObject// CHECK: InitializeNamed+// CHECK: CheckShape+// CHECK: AddNamed+// CHECK-NOT: BindThisFromSuperCall+// CHECK-NOT: CallConstruct++// CHECK-FUNCTION: makeDerivedWithPrivateMethod+// CHECK-PASS: graph building+// CHECK-NOT: CallConstruct+// CHECK: AllocateObject// CHECK: CallSlowPath BindThisFromSuperCall// CHECK-NOT: CallConstructdiff --git a/Tests/LibJS/Runtime/classes/class-super-call-paths.js b/Tests/LibJS/Runtime/classes/class-super-call-paths.jsindex ecc33b9e484..d9194a218e7 100644--- a/Tests/LibJS/Runtime/classes/class-super-call-paths.js+++ b/Tests/LibJS/Runtime/classes/class-super-call-paths.js@@ -1686,3 +1686,129 @@ describe("constructs in hot callers that are not inlined", () => {});});});++describe("literal fields of derived constructs in hot callers", () => {+ test("fields across levels are defined in order", () => {+ class A {+ a = 1;+ constructor(x) {+ this.x = x;+ }+ }+ class B extends A {+ b = 2;+ c;+ constructor(x) {+ super(x);+ this.y = this.b + 1;+ }+ }+ class C extends B {+ d = "d";+ b = 4;+ }+ repeat(i => {+ const b = new B(i);+ expect(Object.keys(b)).toEqual(["a", "x", "b", "c", "y"]);+ expect(b.y).toBe(3);+ expect(b.c).toBeUndefined();+ const c = new C(i);+ expect(Object.keys(c)).toEqual(["a", "x", "b", "c", "y", "d"]);+ expect(c.b).toBe(4);+ expect(c.y).toBe(3);+ });+ });++ test("fields are defined, not set, with setters on the prototype chain", () => {+ let setterCalls = 0;+ class A {+ set f(value) {+ setterCalls++;+ }+ }+ class B extends A {+ f = 1;+ }+ repeat(() => {+ const object = new B();+ expect(Object.getOwnPropertyDescriptor(object, "f")).toEqual({+ value: 1,+ writable: true,+ enumerable: true,+ configurable: true,+ });+ });+ expect(setterCalls).toBe(0);+ });++ test("parents that add different properties change the shape fields start from", () => {+ class A {+ constructor(flag) {+ if (flag) this.p = 1;+ else this.q = 2;+ }+ }+ class B extends A {+ f = 3;+ }+ repeat(i => {+ const object = new B(i % 300 === 299);+ expect(object.f).toBe(3);+ expect(Object.keys(object)).toEqual([i % 300 === 299 ? "p" : "q", "f"]);+ });+ });++ test("a parent that adds a property of the same name as a field", () => {+ class A {+ constructor(flag) {+ if (flag) Object.defineProperty(this, "f", { value: 0, writable: false, configurable: false });+ }+ }+ class B extends A {+ f = 1;+ }+ repeat(i => {+ if (i % 200 === 199) expect(() => new B(true)).toThrow(TypeError);+ else expect(new B(false).f).toBe(1);+ });+ });++ test("frozen and non-extensible objects from a parent's return override", () => {+ let mode = "none";+ class A {+ constructor() {+ if (mode === "frozen") return Object.freeze({});+ if (mode === "sealed") return Object.preventExtensions({});+ }+ }+ class B extends A {+ f = 1;+ }+ repeat(i => {+ mode = i % 100 === 50 ? "frozen" : i % 100 === 51 ? "sealed" : "none";+ if (mode === "none") expect(new B().f).toBe(1);+ else expect(() => new B()).toThrow(TypeError);+ });+ });++ test("fields with symbol names and of a subclass of a subclass", () => {+ const symbol = Symbol("s");+ class A {}+ class B extends A {+ [symbol] = 1;+ n = null;+ }+ class C extends B {+ constructor() {+ super();+ this.after = this[symbol];+ }+ }+ repeat(() => {+ const object = new C();+ expect(object[symbol]).toBe(1);+ expect(object.n).toBeNull();+ expect(object.after).toBe(1);+ });+ });+});