Truly independent web browser
LibJS: Inline constructs of derived classes with derived parents
Andreas Klingcb3b3e929fe6
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs b/Libraries/LibJS/JIT/Rust/src/builder/inlining.rsindex 726c3c914c7..9b62562864d 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs@@ -223,6 +223,13 @@ fn returns_no_object(callee: &Function<'_>) -> bool {/// frame and can return while `this` is still empty, and nothing checks the/// value such a frame returns.fn calls_super_once_before_returning(callee: &Function<'_>) -> bool {+ if callee+ .instructions+ .iter()+ .any(|instruction| instruction.instruction.opcode() == OpCode::Catch)+ {+ return false;+ }let mut jump_targets = Vec::new();for instruction in callee.instructions {instruction@@ -306,6 +313,24 @@ pub(super) enum InlineValue {Node(NodeId),}+/// What an inlined call does (see `GraphBuilder::inlinable_callee()`).+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum InlinedCallKind {+ Call,+ /// A construct of a base constructor.+ Construct,+ /// A construct of a derived constructor, whose super() is inlined too.+ DerivedConstruct,+}++/// A callee that `GraphBuilder::inline_call()` may inline (see+/// `GraphBuilder::inlinable_callee()`).+struct InlinableCallee<'a> {+ executable: &'a crate::snapshot::ExecutableSnapshot,+ function: Function<'a>,+ has_legacy_arguments: bool,+}+/// A call to inline.struct InlinedCallSite {/// The snapshot index of the callee's executable.@@ -389,7 +414,7 @@ impl InlinedCallSite {}}-impl GraphBuilder<'_> {+impl<'a> GraphBuilder<'a> {pub(super) fn boxed_object(&self, cell: CellId) -> u64 {(u64::from(value::OBJECT_TAG) << 48) | (cell.0 & self.runtime.heap_region_offset_mask)}@@ -1456,7 +1481,7 @@ impl GraphBuilder<'_> {return Ok(None);}if let Some(super_constructor) = construct.super_constructor- && !self.may_inline_super_constructor(super_constructor)+ && !self.may_inline_super_constructor(construct.executable, super_constructor){return Ok(None);}@@ -1474,36 +1499,65 @@ impl GraphBuilder<'_> {self.inline_call(call)}- /// Whether the super() of an inlined construct of a derived constructor- /// here can inline the construct of `target` (see- /// `try_inline_super_call()`), one inlined call deeper.- fn may_inline_super_constructor(&self, target: SuperConstructTarget) -> bool {- let Some(executable) = self.snapshot.executables.get(target.executable as usize) else {+ /// Whether the super() of an inlined construct of the derived+ /// constructor `constructor` here can inline the construct of `target`+ /// (see `try_inline_super_call()`), one inlined call deeper, and so on+ /// down the chain of super constructors if `target` is derived too. Each+ /// construct is checked like `inline_call()` checks it (see+ /// `inlinable_callee()`), and no super() in the chain may have exited+ /// because `inline_call()` refused its construct after all.+ fn may_inline_super_constructor(&self, constructor: u32, mut target: SuperConstructTarget) -> bool {+ let Some(constructor_executable) = self.snapshot.executables.get(constructor as usize) else {return false;};- if executable.function.is_none()- || !self.may_inline_calls_of(executable)- || self.callers.len() + 1 >= self.snapshot.options.inlining.max_depth as usize- {+ if self.super_call_exited(constructor) {return false;}- let Ok(decoded) = super::decoded_function(executable, &self.decoded[target.executable as usize]) else {- return false;- };- if decoded.instructions.len() > self.snapshot.options.inlining.max_construct_instructions as usize {- return false;+ // NB: The constructors inlined above `target` by then, from the derived constructor here down.+ let mut inlined_above = vec![constructor_executable.cell];+ loop {+ let kind = if target.derived {+ InlinedCallKind::DerivedConstruct+ } else {+ InlinedCallKind::Construct+ };+ let Some(InlinableCallee { executable, .. }) =+ self.inlinable_callee(target.executable, kind, false, &inlined_above)+ else {+ return false;+ };+ if !target.derived {+ return true;+ }+ if self.super_call_exited(target.executable) {+ return false;+ }+ let Some(next) = executable.super_constructor else {+ return false;+ };+ inlined_above.push(executable.cell);+ target = next;}- let Ok(function) = Function::new(- target.executable,- executable,- decoded,- executable.supports_legacy_arguments,- ) else {- return false;+ }++ /// Whether compiled code exited at a super() of the derived constructor+ /// of snapshot executable `index` because `inline_call()` refused the+ /// construct there (see `try_inline_super_call()`).+ fn super_call_exited(&self, index: u32) -> bool {+ let Some(executable) = self.snapshot.executables.get(index as usize) else {+ return true;};- let virtual_arguments =- self.virtualize_arguments.compiled_function && self.virtualize_arguments.inlined_callees;- can_inline(&function, virtual_arguments, false) && returns_no_object(&function)+ let Ok(decoded) = super::decoded_function(executable, &self.decoded[index as usize]) else {+ return true;+ };+ decoded.instructions.iter().any(|instruction| {+ matches!(+ instruction.instruction.opcode(),+ OpCode::SuperCall | OpCode::SuperCallWithForwardedArguments+ ) && executable+ .exit_sites+ .contains(&(instruction.pc, ExitKind::BadCallTarget))+ })}/// `GetSuperConstructor` in an inlined construct of a derived@@ -1525,7 +1579,7 @@ impl GraphBuilder<'_> {self.check_shapes(function,&[ShapeCheck {- shape: construct.function_shape,+ shape: target.function_shape,dictionary_generation: None,}],);@@ -1537,7 +1591,7 @@ impl GraphBuilder<'_> {Ok(true)}- /// The derived constructor of an inlined construct, and the base+ /// The derived constructor of an inlined construct, and the/// constructor its super() constructs with.fn derived_construct_function(&self,@@ -1625,13 +1679,32 @@ impl GraphBuilder<'_> {// 6. Let result be ? Construct(superCtor, argList, newTarget).// NB: OrdinaryCreateFromConstructor of the construct reads "prototype" of the new target, the derived// constructor.+ // NB: A derived super constructor's super() constructs with its own parent (see+ // `may_inline_super_constructor()`).+ let next_super_constructor = if target.derived {+ let next = self+ .snapshot+ .executables+ .get(target.executable as usize)+ .and_then(|executable| executable.super_constructor);+ if next.is_none() {+ return Err(CompileFailure::InvalidBytecode {+ pc: self.function.pc,+ reason: "derived super constructor without a super constructor",+ });+ }+ next+ } else {+ None+ };+ let new_target = self.function.inline.as_ref().and_then(|call| call.new_target);let call = InlinedCallSite {construct: Some(ConstructTarget {executable: target.executable,- super_constructor: None,+ super_constructor: next_super_constructor,..construct}),- new_target: Some(function),+ new_target: Some(new_target.unwrap_or(function)),forwarded,..InlinedCallSite::new(target.executable,@@ -1641,13 +1714,22 @@ impl GraphBuilder<'_> {*dst,)};- match self.inline_call(call)? {- Some(flow) => Ok(Some(flow)),- None => Err(CompileFailure::InvalidBytecode {- pc: self.function.pc,- reason: "super() of an inlined derived construct could not be inlined",- }),+ if let Some(flow) = self.inline_call(call)? {+ return Ok(Some(flow));}+ // NB: `may_inline_super_constructor()` checks ahead what `inline_call()` checks, but not the values at the+ // call site, like a virtual arguments object, nor what may be speculated here. A generic SuperCall+ // cannot run in the inlined frame, which is not the running frame: exit, which keeps the next+ // compilation from inlining the construct.+ let frame_state = self.eager_frame_state();+ let exit = self.set_control(+ Op::Exit {+ kind: ExitKind::BadCallTarget,+ },+ Vec::new(),+ );+ self.graph.nodes[exit.index()].frame_state = Some(frame_state);+ Ok(Some(Flow::Ended))}/// `BindThisFromSuperCall` in an inlined construct of a derived@@ -1787,13 +1869,25 @@ impl GraphBuilder<'_> {/// This lets recursive functions inline their own calls twice over, and lets functions that share one executable/// inline each other, like the constructors that `Class.create()` returns in Prototype-style code.fn may_inline_calls_of(&self, callee_executable: &crate::snapshot::ExecutableSnapshot) -> bool {+ self.may_inline_calls_of_below(callee_executable, &[])+ }++ /// Like `may_inline_calls_of()`, once the calls of the executables+ /// `inlined_above` (their cells) are inlined here, one in the other.+ fn may_inline_calls_of_below(+ &self,+ callee_executable: &crate::snapshot::ExecutableSnapshot,+ inlined_above: &[CellId],+ ) -> bool {const MAX_RECURSION_DEPTH: usize = 2;let recursion_depth = core::iter::once(&self.function).chain(&self.callers)- .filter(|function| function.executable.cell == callee_executable.cell)+ .map(|function| function.executable.cell)+ .chain(inlined_above.iter().copied())+ .filter(|cell| *cell == callee_executable.cell).count();recursion_depth <= MAX_RECURSION_DEPTH- && self.callers.len() < self.snapshot.options.inlining.max_depth as usize+ && self.callers.len() + inlined_above.len() < self.snapshot.options.inlining.max_depth as usize&& self.may_speculate(ExitKind::BadCallTarget)}@@ -1821,55 +1915,36 @@ impl GraphBuilder<'_> {<= self.snapshot.options.inlining.budget_instructions as usize}- /// Inlines the call `call` describes, if its callee qualifies.- fn inline_call(&mut self, call: InlinedCallSite) -> Result<Option<Flow>, CompileFailure> {- let InlinedCallSite {- index,- callee,- expected_callee,- this,- arguments,- passed_argument_count,- forwarded,- dst,- construct,- new_target,- closure,- check_closure,- callback,- } = call;- let derived_construct = construct.filter(|construct| construct.super_constructor.is_some());- // NB: The callee's frame cannot hold the virtual arguments object:- // the callee's generic instructions could not read it.- if std::iter::once(&this)- .chain(arguments.iter())- .any(|value| matches!(value, InlineValue::Operand(operand) if self.holds_virtual_arguments(*operand)))- {- return Ok(None);- }+ /// The snapshot executable `index`, if a call of the+ /// kind `kind` (a closure call if `closure`) may inline it here once the+ /// executables `inlined_above` (their cells) are inlined here, one in the+ /// other: the checks of `inline_call()` that do not depend on the values+ /// at the call site, which `may_inline_super_constructor()` makes ahead+ /// of the calls that inlined constructs inline for super().+ fn inlinable_callee(+ &self,+ index: u32,+ kind: InlinedCallKind,+ closure: bool,+ inlined_above: &[CellId],+ ) -> Option<InlinableCallee<'a>> {let snapshot = self.snapshot;- let Some(callee_executable) = snapshot.executables.get(index as usize) else {- return Ok(None);- };- let Some(function) = callee_executable.function else {- return Ok(None);- };- let limits = snapshot.options.inlining;- if !self.may_inline_calls_of(callee_executable) {- return Ok(None);+ let callee_executable = snapshot.executables.get(index as usize)?;+ callee_executable.function?;+ if !self.may_inline_calls_of_below(callee_executable, inlined_above) {+ return None;}- let Ok(decoded) = super::decoded_function(callee_executable, &self.decoded[index as usize]) else {- return Ok(None);- };+ let decoded = super::decoded_function(callee_executable, &self.decoded[index as usize]).ok()?;let instruction_count = decoded.instructions.len();+ let limits = snapshot.options.inlining;// NB: Builtins are always inlined (see the snapshot's inlining rules).let within_budget = callee_executable.builtin|| crate::bytecode::inlining_size(&decoded.instructions) <= limits.always_inlined_instructions as usize- || (construct.is_some() && instruction_count <= limits.max_construct_instructions as usize)+ || (kind != InlinedCallKind::Call && instruction_count <= limits.max_construct_instructions as usize)|| (instruction_count <= limits.max_instructions as usize&& self.inlined_instructions + instruction_count <= limits.budget_instructions as usize);if !within_budget {- return Ok(None);+ return None;}// NB: CheckClosure checks shared data, not legacy-property eligibility.// Keep non-strict closure calls conservative. Frames with a virtual@@ -1882,20 +1957,19 @@ impl GraphBuilder<'_> {.iter().any(|instruction| instruction.instruction.opcode() == OpCode::CreateArguments);// NB: A derived constructor that passes its arguments on to super() keeps them all, like legacy `arguments`.- let forwards_arguments_to_super = derived_construct.is_some()+ let derived_construct = kind == InlinedCallKind::DerivedConstruct;+ let forwards_arguments_to_super = derived_construct&& decoded.instructions.iter().any(|instruction| instruction.instruction.opcode() == OpCode::SuperCallWithForwardedArguments);let has_legacy_arguments = callee_executable.supports_legacy_arguments- || (closure.is_some() && callee_executable.is_non_strict_function())+ || (closure && callee_executable.is_non_strict_function())|| (virtual_arguments && creates_arguments)|| forwards_arguments_to_super;- let Ok(mut callee_function) = Function::new(index, callee_executable, decoded, has_legacy_arguments) else {- return Ok(None);- };- if !can_inline(&callee_function, virtual_arguments, derived_construct.is_some()) {- return Ok(None);+ let callee_function = Function::new(index, callee_executable, decoded, has_legacy_arguments).ok()?;+ if !can_inline(&callee_function, virtual_arguments, derived_construct) {+ return None;}// NB: Closures of a function share its code but may have other home objects, and the base of `super` property// access is guarded by a shape check.@@ -1903,16 +1977,66 @@ impl GraphBuilder<'_> {.instructions.iter().any(|instruction| instruction.instruction.opcode() == OpCode::ResolveSuperBase);- if resolves_super_base && (closure.is_some() || !self.may_speculate(ExitKind::BadShape)) {- return Ok(None);+ if resolves_super_base && (closure || !self.may_speculate(ExitKind::BadShape)) {+ return None;}- if derived_construct.is_some() {- if !calls_super_once_before_returning(&callee_function) {- return Ok(None);- }- } else if construct.is_some() && !returns_no_object(&callee_function) {+ let qualifies = match kind {+ InlinedCallKind::Call => true,+ InlinedCallKind::Construct => returns_no_object(&callee_function),+ InlinedCallKind::DerivedConstruct => calls_super_once_before_returning(&callee_function),+ };+ qualifies.then_some(InlinableCallee {+ executable: callee_executable,+ function: callee_function,+ has_legacy_arguments,+ })+ }++ /// Inlines the call `call` describes, if its callee qualifies.+ fn inline_call(&mut self, call: InlinedCallSite) -> Result<Option<Flow>, CompileFailure> {+ let InlinedCallSite {+ index,+ callee,+ expected_callee,+ this,+ arguments,+ passed_argument_count,+ forwarded,+ dst,+ construct,+ new_target,+ closure,+ check_closure,+ callback,+ } = call;+ let derived_construct = construct.filter(|construct| construct.super_constructor.is_some());+ // NB: The callee's frame cannot hold the virtual arguments object:+ // the callee's generic instructions could not read it.+ if std::iter::once(&this)+ .chain(arguments.iter())+ .any(|value| matches!(value, InlineValue::Operand(operand) if self.holds_virtual_arguments(*operand)))+ {return Ok(None);}+ let Some(InlinableCallee {+ executable: callee_executable,+ function: mut callee_function,+ has_legacy_arguments,+ }) = self.inlinable_callee(+ index,+ match (construct, derived_construct) {+ (None, _) => InlinedCallKind::Call,+ (Some(_), None) => InlinedCallKind::Construct,+ (Some(_), Some(_)) => InlinedCallKind::DerivedConstruct,+ },+ closure.is_some(),+ &[],+ )+ else {+ return Ok(None);+ };+ let function = callee_executable.function.expect("inlined callees have a function");+ let instruction_count = callee_function.instructions.len();// NB: Bind `this` like the interpreter's inline calls do.let receiver = if construct.is_some() {diff --git a/Libraries/LibJS/JIT/Rust/src/snapshot.rs b/Libraries/LibJS/JIT/Rust/src/snapshot.rsindex c10bc811df4..e84757fc34f 100644--- a/Libraries/LibJS/JIT/Rust/src/snapshot.rs+++ b/Libraries/LibJS/JIT/Rust/src/snapshot.rs@@ -140,6 +140,10 @@ pub struct ExecutableSnapshot {/// The global variables of the executable's realm that its `GetGlobal`/// and `SetGlobal` instructions access, if code may access them directly.pub globals: Option<GlobalsSnapshot>,+ /// For a derived constructor among the inlining candidates whose+ /// constructs JIT code can inline (see `ConstructTarget`): what its+ /// super() constructs with.+ pub super_constructor: Option<SuperConstructTarget>,}/// The global object and the global declarative environment of a realm, and@@ -465,10 +469,9 @@ pub struct CallFeedbackSnapshot {/// (with no function environment).////// Or a derived constructor without fields whose super() constructs with-/// `super_constructor`, its [[Prototype]] while it has `function_shape`.-/// Its construct runs its body, and super() creates `this` like the-/// construct of a base constructor does, with the derived constructor as-/// the new target.+/// `super_constructor`. Its construct runs its body, and super() constructs+/// with its parent and the same new target, down to a base constructor,+/// which creates `this` as above.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct ConstructTarget {pub executable: u32,@@ -483,13 +486,17 @@ pub struct ConstructTarget {pub super_constructor: Option<SuperConstructTarget>,}-/// The base constructor without fields that super() in a derived-/// constructor JIT code can inline constructs with: `function`, whose body-/// is the snapshot executable `executable`.+/// The constructor without fields that super() in a derived constructor+/// JIT code can inline constructs with: `function`, the [[Prototype]] of the+/// derived constructor while that has `function_shape`, whose body is the+/// snapshot executable `executable`. If `function` is `derived` itself, the+/// snapshot of its executable says what its super() constructs with.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct SuperConstructTarget {pub executable: u32,pub function: CellId,+ pub function_shape: CellId,+ pub derived: bool,}/// How a callee forwards calls to another function.diff --git a/Libraries/LibJS/Rust/src/jit/snapshot.rs b/Libraries/LibJS/Rust/src/jit/snapshot.rsindex e9d7e733973..f6b53738daa 100644--- a/Libraries/LibJS/Rust/src/jit/snapshot.rs+++ b/Libraries/LibJS/Rust/src/jit/snapshot.rs@@ -34,6 +34,7 @@ use crate::bytecode::feedback::{CallFeedback, CallFeedbackForwarding, call_feedbuse crate::bytecode::instruction::instruction_length_from_bytes;use crate::gc::class::Extends;use crate::gc::defer_gc::{DeferGc, Deferred};+use crate::gc::root::MarkedVec;use crate::interpreter::vm::Vm;use crate::layout::cell::{CellHeader, Gc};use crate::layout::environment::DeclarativeEnvironment;@@ -115,6 +116,9 @@ struct SnapshotBuilder<'vm> {/// For the constructors among the inlining candidates, by index: the shape of the `this` value their inlined/// constructs create, whose entries their megamorphic caches describe.construct_this_shapes: HashMap<u32, Gc<Shape>>,+ /// For the derived constructors among the inlining candidates, by index: what their super() constructs with in+ /// inlined constructs of them (see `ExecutableSnapshot::super_constructor`).+ super_constructors: HashMap<u32, SuperConstructTarget>,}/// The number of bytecode instructions of an executable, counted up to one past `limit`.@@ -813,47 +817,57 @@ impl SnapshotBuilder<'_> {/// Describes the single constructor of a construct site if JIT code can inline its construct: a base constructor/// without fields (whose construct only creates `this` before running its body), or a derived constructor without- /// fields whose [[Prototype]] is such a base constructor, with a function object of a shape that has its- /// "prototype" as a data property holding an object.+ /// fields whose chain of [[Prototype]]s up to a base constructor are such constructors, with a function object of a+ /// shape that has its "prototype" as a data property holding an object.fn construct_target(&mut self, target: Option<Gc<CellHeader>>, caller: &Entry) -> Option<ConstructTarget> {let function = ecmascript_function(target)?;- if !function.has_constructor()- || function.has_class_data()- || function.allocates_function_environment()- || function.contains_direct_call_to_eval()- || function.realm() != Some(caller.realm)- {- return None;- }- let super_constructor = match function.constructor_kind() {- ConstructorKind::Base => None,- ConstructorKind::Derived => {- // NB: The frame of the derived constructor holds its this value (see+ let inlinable = |constructor: Gc<EcmascriptFunctionObject>| {+ constructor.has_constructor()+ && !constructor.has_class_data()+ && !constructor.allocates_function_environment()+ && !constructor.contains_direct_call_to_eval()+ && constructor.realm() == Some(caller.realm)+ // NB: The frame of a derived constructor holds its this value (see// `function_with_frame_as_this_environment()`).- if function.shared_data().function_environment_has_this_binding() {- return None;- }- let parent = ecmascript_function(function.prototype().map(|parent| parent.upcast::<CellHeader>()))?;- if !parent.has_constructor()- || parent.constructor_kind() != ConstructorKind::Base- || parent.has_class_data()- || parent.allocates_function_environment()- || parent.contains_direct_call_to_eval()- || parent.realm() != Some(caller.realm)- {- return None;- }- Some(parent)- }+ && (constructor.constructor_kind() == ConstructorKind::Base+ || !constructor.shared_data().function_environment_has_this_binding())};+ // NB: The constructors super() constructs with, from the target's parent down to a base constructor. Each+ // level is one inlined call deeper.+ // NB: Making the shape of `this` below may collect garbage.+ let chain = MarkedVec::new(self.vm);+ chain.push(function);+ loop {+ let constructor = chain.get(chain.len() - 1).expect("the chain starts with the target");+ if !inlinable(constructor) {+ return None;+ }+ if constructor.constructor_kind() == ConstructorKind::Base {+ break;+ }+ if chain.len() > self.vm.jit.options.inline_depth as usize {+ return None;+ }+ chain.push(ecmascript_function(+ constructor.prototype().map(|parent| parent.upcast::<CellHeader>()),+ )?);+ }// NB: Class constructors cannot be called, only constructed, so their executable is no inline call executable,// but it runs in an inline frame for a construct all the same.let limit = MAX_INLINED_CONSTRUCT_INSTRUCTION_COUNT;- for constructor in core::iter::once(function).chain(super_constructor) {+ for level in 0..chain.len() {+ let constructor = chain.get(level).expect("the level is in the chain");if instruction_count(&*constructor.bytecode_executable()?, limit) > limit {return None;}}+ // NB: GetSuperConstructor in each derived constructor reads its [[Prototype]] from its shape.+ for level in 0..chain.len() - 1 {+ let constructor = chain.get(level).expect("the level is in the chain");+ if constructor.shape().is_dictionary() || !constructor.has_ordinary_get_prototype_of() {+ return None;+ }+ }let function_shape = function.shape();if function_shape.is_dictionary() {return None;@@ -874,30 +888,36 @@ impl SnapshotBuilder<'_> {empty_shape.create_prototype_transition(self.vm, Some(prototype))};let index = self.inlined_function_index(function, caller)?;- let (super_constructor, reserve) = match super_constructor {- None => {- self.construct_this_shapes.insert(index, this_shape);- (None, function.shared_data().current_construct_reserve())- }- Some(parent) => {- let entry = self.entries[index as usize];- let parent_index = self.inlined_function_index(parent, &entry)?;- (- Some(SuperConstructTarget {- executable: parent_index,- function: self.cell(parent),- }),- parent.shared_data().current_construct_reserve(),- )- }- };+ let mut indices = vec![index];+ for level in 1..chain.len() {+ let entry = self.entries[*indices.last().expect("the chain starts with the target") as usize];+ let parent = chain.get(level).expect("the level is in the chain");+ indices.push(self.inlined_function_index(parent, &entry)?);+ }+ let base = chain+ .get(chain.len() - 1)+ .expect("the chain ends with a base constructor");+ if chain.len() == 1 {+ self.construct_this_shapes.insert(index, this_shape);+ }+ let mut super_constructor = None;+ for level in (0..chain.len() - 1).rev() {+ let target = SuperConstructTarget {+ executable: indices[level + 1],+ function: self.cell(chain.get(level + 1).expect("the level is in the chain")),+ function_shape: self.cell(chain.get(level).expect("the level is in the chain").shape()),+ derived: level + 2 < chain.len(),+ };+ self.super_constructors.insert(indices[level], target);+ super_constructor = Some(target);+ }Some(ConstructTarget {executable: index,function_shape: self.cell(function_shape),prototype_offset: metadata.offset,prototype: self.cell(prototype),this_shape: self.cell(this_shape),- reserve,+ reserve: base.shared_data().current_construct_reserve(),super_constructor,})}@@ -1068,6 +1088,11 @@ impl SnapshotBuilder<'_> {.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 property_caches = executable.property_lookup_caches().iter()@@ -1166,6 +1191,7 @@ impl SnapshotBuilder<'_> {// NB: Builtins written in JavaScript never access global variables by name.globals: (!matches!(entry.function, Some(InlinedFunction::Builtin(_)))).then(|| self.globals(executable, realm)),+ super_constructor,// NB: Only the compiled function's own code creates bindings by name.identifiers: if entry.function.is_none() {executable@@ -1355,6 +1381,7 @@ pub fn capture_snapshot<'d>(bound_arguments: Vec::new(),lexical_environment_templates: Vec::new(),construct_this_shapes: HashMap::new(),+ super_constructors: HashMap::new(),};builder.closure_templates =closure_template_snapshots(closure_templates.into_inner(), |sample| builder.cell(sample), defer_gc);diff --git a/Tests/LibJS/JIT/ir/inlining-derived-construct-chains.js b/Tests/LibJS/JIT/ir/inlining-derived-construct-chains.jsnew file mode 100644index 00000000000..171e410ceb8--- /dev/null+++ b/Tests/LibJS/JIT/ir/inlining-derived-construct-chains.js@@ -0,0 +1,36 @@+// REQUIRES: inline-allocation+// A construct of a derived constructor whose parents are derived constructors without fields too inlines each level's+// construct at its super(), down to the base constructor, which creates `this`.++class A {+ constructor(x) {+ this.x = x;+ }+}+class B extends A {+ constructor(x) {+ super(x);+ this.y = 1;+ }+}+class C extends B {}+class D extends C {+ constructor(x) {+ super(x);+ }+}+function make(i) {+ return new D(i).x;+}+jit.prepare(make);+for (let i = 0; i < 10; ++i) make(i);+jit.compile(make);++// CHECK-FUNCTION: make+// CHECK-PASS: graph building+// CHECK-NOT: CallConstruct+// CHECK-NOT: SuperCall+// CHECK: AllocateObject+// CHECK-NOT: CallConstruct+// CHECK-NOT: SuperCall+// CHECK-NOT: BindThisFromSuperCalldiff --git a/Tests/LibJS/JIT/ir/inlining-derived-construct-parent-with-super-property.js b/Tests/LibJS/JIT/ir/inlining-derived-construct-parent-with-super-property.jsnew file mode 100644index 00000000000..fe15336dbbe--- /dev/null+++ b/Tests/LibJS/JIT/ir/inlining-derived-construct-parent-with-super-property.js@@ -0,0 +1,29 @@+// REQUIRES: inline-allocation+// The super() of an inlined derived construct inlines a parent constructor that accesses a super property, which+// the check made before the derived construct is inlined allows like the inlining of the super() does.++class A {+ constructor(x) {+ this.x = x;+ this.inherited = super.toString === Object.prototype.toString;+ }+}+class B extends A {+ constructor(x) {+ super(x);+ }+}+function make(i) {+ return new B(i).x;+}+jit.prepare(make);+for (let i = 0; i < 10; ++i) make(i);+jit.compile(make);++// CHECK-FUNCTION: make+// CHECK-PASS: graph building+// CHECK-NOT: CallConstruct+// CHECK-NOT: SuperCall+// CHECK: AllocateObject+// CHECK-NOT: CallConstruct+// CHECK-NOT: SuperCalldiff --git a/Tests/LibJS/JIT/ir/inlining-derived-construct-recursive-chains.js b/Tests/LibJS/JIT/ir/inlining-derived-construct-recursive-chains.jsnew file mode 100644index 00000000000..b4fa8b95c66--- /dev/null+++ b/Tests/LibJS/JIT/ir/inlining-derived-construct-recursive-chains.js@@ -0,0 +1,27 @@+// REQUIRES: inline-allocation+// The classes of a chain made from one class expression share their code, and only so many frames of the same code+// are inlined in one another. A construct of a chain longer than that is not inlined, and its caller still compiles.++const mixin = Base =>+ class extends Base {+ constructor(x) {+ super(x);+ }+ };+class A {+ constructor(x) {+ this.x = x;+ }+}+const B = mixin(mixin(mixin(mixin(A))));+function make(i) {+ return new B(i).x;+}+jit.prepare(make);+for (let i = 0; i < 10; ++i) make(i);+jit.compile(make);++// CHECK-FUNCTION: make+// CHECK-PASS: graph building+// CHECK: CallConstruct+// CHECK-NOT: AllocateObjectdiff --git a/Tests/LibJS/Runtime/classes/class-super-call-paths.js b/Tests/LibJS/Runtime/classes/class-super-call-paths.jsindex 51029178026..1f117526bb6 100644--- a/Tests/LibJS/Runtime/classes/class-super-call-paths.js+++ b/Tests/LibJS/Runtime/classes/class-super-call-paths.js@@ -965,3 +965,149 @@ describe("derived constructs in hot callers", () => {});});});++describe("inheritance chains in hot callers", () => {+ test("each level sees the new target and runs in order", () => {+ const log = [];+ class A {+ constructor(x) {+ this.x = x;+ this.aTarget = new.target;+ }+ }+ class B extends A {+ constructor(x) {+ super(x);+ this.bTarget = new.target;+ }+ }+ class C extends B {}+ class D extends C {+ constructor(x) {+ super(x + 1);+ this.d = this.x;+ }+ }+ function make(i) {+ return new D(i);+ }+ repeat(i => {+ const d = make(i);+ expect(d.x).toBe(i + 1);+ expect(d.d).toBe(i + 1);+ expect(d.aTarget).toBe(D);+ expect(d.bTarget).toBe(D);+ expect(Object.getPrototypeOf(d)).toBe(D.prototype);+ expect(Object.keys(d)).toEqual(["x", "aTarget", "bTarget", "d"]);+ });+ });++ test("return overrides and exceptions in the middle of a chain", () => {+ const override = { override: true };+ class A {+ constructor(mode) {+ if (mode === "throw") throw new Error("base");+ this.a = 1;+ }+ }+ class B extends A {+ constructor(mode) {+ super(mode);+ if (mode === "override") return override;+ if (mode === "number") return 1;+ }+ }+ class C extends B {+ constructor(mode) {+ super(mode);+ this.c = 1;+ }+ }+ function make(mode) {+ return new C(mode);+ }+ repeat(i => {+ expect(make("plain").c).toBe(1);+ if (i % 100 === 0) {+ const result = make("override");+ expect(result).toBe(override);+ expect(result.c).toBe(1);+ delete override.c;+ expect(() => make("number")).toThrow(TypeError);+ expect(() => make("throw")).toThrowWithMessage(Error, "base");+ }+ });+ });++ test("changing a prototype in the chain while hot", () => {+ class A {+ constructor() {+ this.from = "A";+ }+ }+ class Other {+ constructor() {+ this.from = "Other";+ }+ }+ class B extends A {+ constructor() {+ super();+ }+ }+ class C extends B {+ constructor() {+ super();+ }+ }+ function make() {+ return new C();+ }+ repeat(i => {+ if (i === ITERATIONS / 2) Object.setPrototypeOf(B, Other);+ expect(make().from).toBe(i < ITERATIONS / 2 ? "A" : "Other");+ });+ });++ test("Reflect.construct with another new target", () => {+ class A {+ constructor() {+ this.target = new.target;+ }+ }+ class B extends A {}+ class C extends B {}+ function make(i) {+ return i % 3 === 0 ? Reflect.construct(C, [], Array) : new C();+ }+ repeat(i => {+ const result = make(i);+ expect(result.target).toBe(i % 3 === 0 ? Array : C);+ expect(Object.getPrototypeOf(result)).toBe(i % 3 === 0 ? Array.prototype : C.prototype);+ });+ });++ test("a chain of classes from one class expression", () => {+ const mixin = Base =>+ class extends Base {+ constructor(x) {+ super(x);+ this.depth = (this.depth ?? 0) + 1;+ }+ };+ class A {+ constructor(x) {+ this.x = x;+ }+ }+ const B = mixin(mixin(mixin(mixin(A))));+ function make(i) {+ return new B(i);+ }+ repeat(i => {+ const b = make(i);+ expect(b.x).toBe(i);+ expect(b.depth).toBe(4);+ });+ });+});