Skip to content

Truly independent web browser

LibJS: Create objects for f.arguments only when code reads them

Andreas Klingdd735e6e82c6
diff --git a/Libraries/LibJS/JIT/ARCHITECTURE.md b/Libraries/LibJS/JIT/ARCHITECTURE.md
index bf346e8913d..656c0ebe51f 100644
--- a/Libraries/LibJS/JIT/ARCHITECTURE.md
+++ b/Libraries/LibJS/JIT/ARCHITECTURE.md
@@ -164,6 +164,7 @@ Exits: E = eager, L = lazy. Every node that can exit has a frame state. "Call" m
| CheckTypedArrayStorage | Exits unless the storage offset of a typed array (input 0) is valid. Typed arrays whose length the snapshot knows to be fixed use it as a constant past this check, so accesses with a constant index rely on it alone. The value is the offset, refined. | E | | | cse |
| CheckNotHole | Exits at holes (the empty value). The value is input 0, refined. | E | | | cse |
| AssumeValid | Exits if the code was invalidated; a patchable no-op (section 5). | E | Any | | |
+| AssumeLegacyArgumentsUnread | After an instruction whose calls may run code reading the legacy `arguments` of inlined frames; escape analysis makes it an `AssumeValid` or removes it (section 4, "Legacy arguments"). | E | Any | | |
| **Object memory** | | | | | |
| LoadNamed | A named property at an offset; exits for accessors. | E | Named | | cse |
| StoreNamed | Stores an existing named property; exits for accessors. | E | Named | Named | |
@@ -200,7 +201,7 @@ Exits: E = eager, L = lazy. Every node that can exit has a frame state. "Call" m
| AllocateObject, AllocateArray | A new plain object or packed array; nothing can see it before it is stored. | | | | allocates |
| AllocateFunction, AllocateEnvironment | A new closure or lexical environment from its template. | | | | allocates |
| InitializeNamed, InitializeElement | Initializing stores into an object or array nothing else has seen. | | | Named / Elements | |
-| VirtualObject | An object escape analysis removed, as frame states need it; in no block, no code. | | | | |
+| VirtualObject | An object escape analysis removed, as frame states need it; in no block, no code. Names the `AllocateObject` it stands for, which is the same object at every site of the code. | | | | |
| **Frames and environments** | | | | | |
| InitializeFrame, EnsureFrameInitialized | The `Enter` bytecode: publishes the frame, empties the registers and locals, copies the constants (the second only if the frame is not initialized yet). | | | Frame | |
| PublishFrame | Makes the frame the running execution context, which direct calls leave to their callee's code. | | | Frame | |
@@ -275,6 +276,24 @@ runtime functions only see the running frame and its callers, so nothing may run
collect garbage or exit lazily before that. Eager exits publish the frame in the translator, and
the prologue's resumption in the interpreter publishes it inline.
+**Legacy arguments.** Code that a call in an inlined function runs may read the function's
+arguments through its legacy `f.arguments`, which may be objects the code never allocated. They
+stay virtual: the frames of inlined calls that the runtime publishes or materializes while compiled
+code keeps running get a marker in such an argument slot (an empty value with the low half of the
+JIT frame's frame pointer), where the frame state's `legacy_arguments` include it. Reading
+`f.arguments` (or the debugger) replaces the marker with the object, created from the values of the
+site the JIT frame is suspended at: in stack slots for a call site, and in the JIT frame's register
+dump for a publication (the frame stores the site's index where
+`CompiledCode::site_index_frame_offset` says). The runtime remembers the
+object for the frame (by the allocation its `VirtualObject` names), and every later
+materialization for that frame uses it, as it is. It then invalidates and discards the code and
+records `ExitKind::LegacyArgumentsRead` at the call. The builder ends every instruction whose
+calls run code in a frame chain with legacy arguments with an `AssumeLegacyArgumentsUnread`, which
+escape analysis keeps as an `AssumeValid` where the call has such objects, so the frame exits
+right after the call and the interpreter continues with the objects that code read and maybe
+changed. Recompiles keep the objects allocated at calls where code read them before. Calls
+without such a node after them keep the objects among legacy arguments allocated too.
+
### 4.1 Generators and async functions
@@ -379,7 +398,7 @@ unreachable. Each one keeps the graph valid (`passes/verify.rs`), and IR tests i
| Bounds check elimination | Bounds checks against constant counts go away where the index is known to be in range: induction variables of loops whose back edge compares the grown counter with a constant bound, merges of values from outside a loop, and int32 arithmetic on them that cannot overflow. The counter an on-stack replacement entry brings is checked against the bound once where it enters, unless such a check exited there before. With the same ranges, `((x << k) + c) >> k` becomes `x + (c >> k)` where nothing overflows and `c` is a multiple of 2^k. Int32 additions, subtractions and multiplications become `Int32WrappingBinary` where the ranges of their operands keep the result an int32 (and not -0), with operands also bounded by the masks and shifts of any int32, and by the dominating bounds checks and in-bounds branches of indices. |
| Exit unboxing | Frame states take the unboxed value of an int32, float64 or bool boxing that only frame states use, so that exits box it instead of the fast path. |
| Dead code elimination | Removes nodes without uses and without effects; frame states count as uses. Branches whose edges lead to the same place doing the same thing become jumps. |
-| Escape analysis | Allocations that do not escape become their properties' SSA values; frame states refer to `VirtualObject`s. |
+| Escape analysis | Allocations that do not escape become their properties' SSA values; frame states refer to `VirtualObject`s. `AssumeLegacyArgumentsUnread` nodes after calls whose frame states have virtual objects among legacy arguments become `AssumeValid` nodes; the others go away. |
| Dead code elimination | Again, for what escape analysis left unused. |
| Branch fusion | A branch on a single-use comparison (int32, float64 or tagged) compares itself, after a block that only branches on a phi of booleans hands the branch to its predecessors. |
| Refinement removal | Every use of a refined value becomes a use of the value itself; `Refine` nodes go away and checks lose their values; value numbering then merges what differed only in refinements (section 3.2). |
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs b/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs
index 4d2809c7c42..47290601374 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/inlining.rs
@@ -355,6 +355,54 @@ impl GraphBuilder<'_> {
values
}
+ /// Ends the instruction at `instruction_index` just built (with the
+ /// instructions it built as well), whose nodes are those from
+ /// `first_node` on, with an `AssumeLegacyArgumentsUnread` if code that
+ /// some of its nodes run may read the legacy `arguments` of the frames of
+ /// the inlined calls it is in. Its frame state resumes at the next
+ /// instruction.
+ pub(super) fn guard_legacy_arguments(&mut self, instruction_index: usize, first_node: usize) {
+ let Some(parent) = self.parent_frame_state() else {
+ return;
+ };
+ let has_legacy_arguments = self.function.has_legacy_arguments()
+ || self
+ .graph
+ .frame_state_chain(parent)
+ .iter()
+ .any(|id| !self.graph.frame_state(*id).legacy_arguments.is_empty());
+ if !has_legacy_arguments {
+ return;
+ }
+ let function_index = self.function.index;
+ let graph = &self.graph;
+ let nodes = (first_node..graph.nodes.len())
+ .map(|index| NodeId(index as u32))
+ .filter(|node| {
+ let data = graph.node(*node);
+ // NB: Nodes of the calls the instruction inlined run in frames
+ // of their own, after which those calls guard themselves.
+ data.op.properties().runs_code
+ && data.frame_state.is_some_and(|frame_state| {
+ let innermost = graph.frame_state(frame_state);
+ innermost.executable == function_index && innermost.parent == Some(parent)
+ })
+ })
+ .collect::<Vec<_>>();
+ if nodes.is_empty() {
+ return;
+ }
+ let last = instruction_index + self.function.skipped_instructions;
+ let frame_state = FrameState {
+ pc: self.function.instructions[last].next_pc(),
+ ..self.new_frame_state(self.function.liveness.live_out(last), ResumeMode::ResumeAt)
+ };
+ let frame_state = self.graph.add_frame_state(frame_state);
+ let guard = self.emit(Op::AssumeLegacyArgumentsUnread, Vec::new(), None);
+ self.graph.nodes[guard.index()].frame_state = Some(frame_state);
+ self.graph.legacy_arguments_guards.push((guard, nodes));
+ }
+
fn legacy_argument_slots(&self) -> core::ops::Range<u32> {
let function = &self.function;
let Some(call) = function.inline.as_ref().filter(|_| function.has_legacy_arguments()) else {
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs b/Libraries/LibJS/JIT/Rust/src/builder/mod.rs
index f866bde7f2e..bca9402b860 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/mod.rs
@@ -934,9 +934,11 @@ impl<'a> GraphBuilder<'a> {
self.function.skipped_instructions -= 1;
continue;
}
+ let first_node = self.graph.nodes.len();
if let Flow::Ended = self.build_instruction()? {
return Ok(());
}
+ self.guard_legacy_arguments(instruction_index, first_node);
}
// NB: The block falls through into the next one.
let next_pc = self.function.instructions[self.function.instruction_index].next_pc();
diff --git a/Libraries/LibJS/JIT/Rust/src/code.rs b/Libraries/LibJS/JIT/Rust/src/code.rs
index 7ff7c50b319..30c64f58a81 100644
--- a/Libraries/LibJS/JIT/Rust/src/code.rs
+++ b/Libraries/LibJS/JIT/Rust/src/code.rs
@@ -46,6 +46,17 @@ pub struct CompiledCode {
/// What invalidates the code: the bytes to write at each offset of it
/// (see `Op::AssumeValid`).
pub invalidation_patches: Vec<(u32, Vec<u8>)>,
+ /// The offset from the frame pointer of the 32-bit word where the code
+ /// keeps the index of a site the runtime reads the values of: that of
+ /// an exit or leave, while a slow path in an inlined callee runs in
+ /// frames the runtime published, that of their publication, and while a
+ /// call in an inlined callee runs in frames the runtime materialized for
+ /// it, that of the call.
+ pub site_index_frame_offset: i32,
+ /// The offset from the frame pointer of the register dump (see
+ /// `ValueLocation::Register`) that exits, leaves and publications fill,
+ /// which holds the values of a publication while its slow path runs.
+ pub register_dump_frame_offset: i32,
/// The debug dumps `CompileOptions` asked for, as text to print.
pub dump: Option<String>,
/// With `CompileOptions::coverage`, what the code contains (see
@@ -120,6 +131,13 @@ pub enum ExitKind {
/// Something the code depended on stopped holding while it ran other
/// code (see `Dependency`), so the code was invalidated.
Invalidated,
+ /// Code that a call in an inlined function ran read the legacy
+ /// `arguments` of the function's frame, among which were objects the
+ /// code never allocated: the runtime created them, and the code exited
+ /// after the call (see `Op::AssumeLegacyArgumentsUnread`). Recorded at
+ /// the call, in the executable of the function. Recompiles allocate the
+ /// objects among the function's arguments at that call.
+ LegacyArgumentsRead,
}
/// Something compiled code assumes keeps holding, without checking it where
@@ -251,6 +269,11 @@ pub struct FrameState {
pub in_frame: Vec<u32>,
/// See `ir::FrameState::passed_argument_count`.
pub passed_argument_count: Option<u32>,
+ /// The argument slots that the legacy `arguments` of the frame's
+ /// function shows (see `ir::FrameState::legacy_arguments`). Objects the
+ /// code never allocated among them are only created when code reads them
+ /// (see `ir::Op::AssumeLegacyArgumentsUnread`).
+ pub legacy_arguments: core::ops::Range<u32>,
}
/// Where an exit finds a value.
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
index 9be61ffd261..ff3187bf584 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
@@ -210,6 +210,10 @@ pub struct GeneratedCode {
/// What invalidates the code: the bytes to write at each offset (see
/// `Op::AssumeValid`).
pub invalidation_patches: Vec<(u32, Vec<u8>)>,
+ /// See `CompiledCode::site_index_frame_offset`.
+ pub site_index_frame_offset: i32,
+ /// See `CompiledCode::register_dump_frame_offset`.
+ pub register_dump_frame_offset: i32,
}
/// What a run of generated code is for, so `dump-asm` can label it.
@@ -458,6 +462,8 @@ pub fn generate<M: PortableMacroAssembler>(
)
})
.collect();
+ let site_index_frame_offset = codegen.local_frame_pointer_offset(codegen.locals.exit_index);
+ let register_dump_frame_offset = codegen.local_frame_pointer_offset(codegen.locals.dump);
let (code, data_offset) = codegen
.masm
.finish_with_data_offset()
@@ -471,6 +477,8 @@ pub fn generate<M: PortableMacroAssembler>(
annotations,
osr_entries,
invalidation_patches,
+ site_index_frame_offset,
+ register_dump_frame_offset,
})
}
@@ -817,6 +825,12 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
descriptor
}
+ /// The offset of the local at `offset` from the frame pointer.
+ fn local_frame_pointer_offset(&self, offset: u32) -> i32 {
+ let frame_pointer = i64::from(self.frame.caller_stack_offset) - 16;
+ i32::try_from(i64::from(offset) - frame_pointer).expect("JIT frames are smaller than 2 GiB")
+ }
+
/// The `saved` registers of a slow path call, with the frame pointer
/// offsets of their words in the saves area.
fn save_slot_offsets(&self, saved: &[Gpr]) -> Vec<(Gpr, i32)> {
@@ -1268,6 +1282,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
Op::Constant(_) | Op::Phi | Op::VirtualObject { .. } | Op::Refine { .. } => {
unreachable!("constants, phis, virtual objects and refinements have no code")
}
+ Op::AssumeLegacyArgumentsUnread => unreachable!("escape analysis resolves legacy arguments guards"),
Op::LoadSlot { slot } => {
let address = self.slot_address(*slot)?;
self.masm.load64(self.output(node_id), &address);
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/sites.rs b/Libraries/LibJS/JIT/Rust/src/codegen/sites.rs
index 85c21c41e9c..66667bd35a3 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/sites.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/sites.rs
@@ -85,6 +85,7 @@ pub(crate) fn site(
values,
in_frame,
passed_argument_count: frame_state.passed_argument_count,
+ legacy_arguments: frame_state.legacy_arguments.clone(),
}
})
.collect();
diff --git a/Libraries/LibJS/JIT/Rust/src/ir/dump.rs b/Libraries/LibJS/JIT/Rust/src/ir/dump.rs
index 9e5252e89e5..cc01a66f768 100644
--- a/Libraries/LibJS/JIT/Rust/src/ir/dump.rs
+++ b/Libraries/LibJS/JIT/Rust/src/ir/dump.rs
@@ -239,6 +239,7 @@ fn op_text(layout: &FrameLayout, op: &Op, inputs: &str) -> String {
Op::CheckShape { shapes } => with_inputs(&format!("CheckShape [{}]", shapes_text(shapes.iter()))),
Op::CheckPrototypeChainValid { validity } => format!("CheckPrototypeChainValid {:#x}", validity.0),
Op::AssumeValid => "AssumeValid".to_string(),
+ Op::AssumeLegacyArgumentsUnread => "AssumeLegacyArgumentsUnread".to_string(),
Op::HasInPrototypeChain => with_inputs("HasInPrototypeChain"),
Op::LoadGlobalBinding { environment, index } => format!("LoadGlobalBinding {:#x}[{index}]", environment.0),
Op::StoreGlobalBinding { environment, index } => {
diff --git a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs b/Libraries/LibJS/JIT/Rust/src/ir/mod.rs
index 1302bb0965f..24bc6c4c0ab 100644
--- a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/ir/mod.rs
@@ -814,6 +814,16 @@ pub enum Op {
/// one where it relies on its dependencies after other code ran, which
/// is the only way they can stop holding.
AssumeValid,
+ /// An `AssumeValid` after an instruction whose calls run code that may
+ /// read the legacy `arguments` of the frames of inlined calls the
+ /// instruction is in. Where those arguments are objects the code never
+ /// allocated, the runtime creates them for that code and invalidates the
+ /// code, so that the frame exits here and continues with the very objects
+ /// that code read. Escape analysis makes it an `AssumeValid` after calls
+ /// whose frame states have such objects, and removes the others (see
+ /// `Graph::legacy_arguments_guards`). Until then it is no `AssumeValid`,
+ /// so that check elimination does not rely on it.
+ AssumeLegacyArgumentsUnread,
/// Loads binding `index` of the global declarative environment
/// `environment`. Exits with `ExitKind::BadShape` if it is still
/// uninitialized.
@@ -1418,7 +1428,7 @@ impl Op {
},
// NB: Reading everything keeps loops whose code may invalidate
// the code from hoisting it.
- Op::AssumeValid => P {
+ Op::AssumeValid | Op::AssumeLegacyArgumentsUnread => P {
reads: Locations::ALL,
..P::PURE
},
@@ -1672,6 +1682,7 @@ impl Op {
Op::CheckShape { .. } => "CheckShape",
Op::CheckPrototypeChainValid { .. } => "CheckPrototypeChainValid",
Op::AssumeValid => "AssumeValid",
+ Op::AssumeLegacyArgumentsUnread => "AssumeLegacyArgumentsUnread",
Op::HasInPrototypeChain => "HasInPrototypeChain",
Op::LoadGlobalBinding { .. } => "LoadGlobalBinding",
Op::StoreGlobalBinding { .. } => "StoreGlobalBinding",
@@ -1795,7 +1806,7 @@ impl Op {
Op::CheckArray => Some(ExitKind::BadType),
Op::CheckNonNegativeInt32 => Some(ExitKind::Overflow),
Op::CheckNumber | Op::CheckIdentityComparable | Op::HasInPrototypeChain => Some(ExitKind::BadType),
- Op::AssumeValid => Some(ExitKind::Invalidated),
+ Op::AssumeValid | Op::AssumeLegacyArgumentsUnread => Some(ExitKind::Invalidated),
Op::Int32Binary { op } if op.int32_can_overflow() => Some(ExitKind::Overflow),
Op::CheckValue { kind, .. } => Some(*kind),
Op::LoadArgument { .. } | Op::SliceArguments => Some(ExitKind::ArgumentsIndex),
@@ -2046,6 +2057,9 @@ pub struct Graph {
/// The argument slots of the compiled function that its legacy
/// `arguments` shows. Empty for functions without legacy `arguments`.
pub legacy_arguments: core::ops::Range<u32>,
+ /// The `AssumeLegacyArgumentsUnread` nodes, each with the nodes of its
+ /// instruction that run code.
+ pub legacy_arguments_guards: Vec<(NodeId, Vec<NodeId>)>,
}
impl Graph {
@@ -2128,7 +2142,10 @@ impl Graph {
)
}
- pub fn legacy_argument_values_read_by(&self, node: NodeId) -> Vec<NodeId> {
+ /// The values that code `node` runs may read through the legacy
+ /// `arguments` of the frames of its frame state chain for which
+ /// `frames` holds.
+ pub fn legacy_argument_values_read_by(&self, node: NodeId, frames: impl Fn(&FrameState) -> bool) -> Vec<NodeId> {
let data = self.node(node);
let Some(frame_state) = data.frame_state.filter(|_| data.op.properties().runs_code) else {
return Vec::new();
@@ -2136,6 +2153,9 @@ impl Graph {
let mut values = Vec::new();
for id in self.frame_state_chain(frame_state) {
let frame_state = self.frame_state(id);
+ if !frames(frame_state) {
+ continue;
+ }
for (slot, value) in &frame_state.values {
if frame_state.legacy_arguments.contains(slot) {
values.push(*value);
@@ -2145,6 +2165,16 @@ impl Graph {
values
}
+ /// Whether code that `node` runs may read objects the code never
+ /// allocated through the legacy `arguments` of the frames of its frame
+ /// state chain, which the runtime then creates from the values of the
+ /// node's site (see `Op::AssumeLegacyArgumentsUnread`).
+ pub fn defers_legacy_argument_objects(&self, node: NodeId) -> bool {
+ self.legacy_argument_values_read_by(node, |_| true)
+ .into_iter()
+ .any(|value| matches!(self.node(value).op, Op::VirtualObject { .. }))
+ }
+
/// The values of every frame of a frame state chain, innermost frame first.
///
/// They are followed by the properties of the virtual objects among them
diff --git a/Libraries/LibJS/JIT/Rust/src/lib.rs b/Libraries/LibJS/JIT/Rust/src/lib.rs
index 5bc26b66ec4..baa2a733562 100644
--- a/Libraries/LibJS/JIT/Rust/src/lib.rs
+++ b/Libraries/LibJS/JIT/Rust/src/lib.rs
@@ -136,6 +136,8 @@ pub fn compile_for<M: asm::PortableMacroAssembler>(
embedded_cells: graph.embedded_cells,
dependencies: graph.dependencies,
invalidation_patches: generated.invalidation_patches,
+ site_index_frame_offset: generated.site_index_frame_offset,
+ register_dump_frame_offset: generated.register_dump_frame_offset,
dump,
})
}
diff --git a/Libraries/LibJS/JIT/Rust/src/passes/check_elimination.rs b/Libraries/LibJS/JIT/Rust/src/passes/check_elimination.rs
index ef4ff63b312..1e34488b9d7 100644
--- a/Libraries/LibJS/JIT/Rust/src/passes/check_elimination.rs
+++ b/Libraries/LibJS/JIT/Rust/src/passes/check_elimination.rs
@@ -397,7 +397,7 @@ fn visit_node(
facts.expose(*input);
}
}
- for value in graph.legacy_argument_values_read_by(node_id) {
+ for value in graph.legacy_argument_values_read_by(node_id, |_| true) {
facts.expose(decisions.value(graph, value));
}
// NB: A check known to pass is replaced by what refined its input
diff --git a/Libraries/LibJS/JIT/Rust/src/passes/escape_analysis.rs b/Libraries/LibJS/JIT/Rust/src/passes/escape_analysis.rs
index 982265447a8..7e7ba0b5087 100644
--- a/Libraries/LibJS/JIT/Rust/src/passes/escape_analysis.rs
+++ b/Libraries/LibJS/JIT/Rust/src/passes/escape_analysis.rs
@@ -10,17 +10,21 @@
//! besides accesses of its named properties: when it is stored into the
//! frame or into an object that escapes, passed to anything but property
//! accesses and checks (an operand of a slow path or a call included),
-//! passed to an inlined call whose legacy `arguments` code it runs can read,
-//! or merged in a phi. An object that does not escape is never allocated: its
-//! properties become SSA values, initialized to `undefined`. Stores update
-//! them, loads become the value stored last, checks of the object (whose
-//! shape is known) go away, and where paths merge, phis merge the values.
+//! passed to an inlined call whose legacy `arguments` code it runs can read
+//! where no `AssumeLegacyArgumentsUnread` follows, or where code read them
+//! before (`ExitKind::LegacyArgumentsRead`), or merged in a phi. An object
+//! that does not escape is never allocated: its properties become SSA
+//! values, initialized to `undefined`. Stores update them, loads become the
+//! value stored last, checks of the object (whose shape is known) go away,
+//! and where paths merge, phis merge the values.
//!
//! Frame states only reach the frame when compiled code leaves: at exits,
//! and when slow paths and calls do not continue in compiled code (see
//! `SiteKind::Leave`). Frame states that need the object refer to an
//! `Op::VirtualObject` with the values its properties have there, and the
-//! runtime creates it then.
+//! runtime creates it then. So does code that reads it through legacy
+//! `arguments`, after which compiled code leaves at the next
+//! `AssumeLegacyArgumentsUnread` (see that).
//!
//! Values stored into an object that does not escape do not escape by being
//! stored there, so nested objects (an options bag holding a location
@@ -33,11 +37,13 @@ use super::edit;
use super::edit::Constants;
use super::edit::Replacements;
use crate::bitset::BitSet;
+use crate::code::ExitKind;
use crate::code::Repr;
use crate::fast_hash::HashMap;
use crate::fast_hash::HashSet;
use crate::ir::Block;
use crate::ir::BlockId;
+use crate::ir::FrameState;
use crate::ir::FrameStateId;
use crate::ir::Graph;
use crate::ir::Node;
@@ -113,8 +119,27 @@ fn analyze(graph: &Graph, placed: &[NodeId], escaping: &[NodeId]) -> Analysis {
}
}
+ // NB: Code that calls run may read the legacy `arguments` of the frames
+ // of inlined calls. The runtime creates the objects among them that
+ // the code never allocated then, after nodes that guard against that
+ // (see `Op::AssumeLegacyArgumentsUnread`), except where code read
+ // them before: there, and after other nodes, they stay allocated.
+ let guarded = graph
+ .legacy_arguments_guards
+ .iter()
+ .flat_map(|(_, nodes)| nodes.iter().copied())
+ .collect::<HashSet<_>>();
+ let read_before = graph
+ .exit_sites
+ .iter()
+ .filter(|(_, _, kind)| *kind == ExitKind::LegacyArgumentsRead)
+ .map(|(executable, pc, _)| (*executable, *pc))
+ .collect::<HashSet<_>>();
for node in placed {
- for value in graph.legacy_argument_values_read_by(*node) {
+ let allocated_in = |frame_state: &FrameState| {
+ !guarded.contains(node) || read_before.contains(&(frame_state.executable, frame_state.pc))
+ };
+ for value in graph.legacy_argument_values_read_by(*node, allocated_in) {
if let Some(root) = roots.get(&value) {
escaped.insert(root.index());
}
@@ -291,17 +316,41 @@ pub fn run(graph: &mut Graph) {
// properties.
if !analysis.has_nested_objects {
replace_objects(graph, &analysis).expect("objects not stored into others merge in no phi of properties");
- return;
+ break;
}
let mut copy = graph.clone();
match replace_objects(&mut copy, &analysis) {
Ok(()) => {
*graph = copy;
- return;
+ break;
}
Err(objects) => escaping.extend(objects),
}
}
+ resolve_legacy_arguments_guards(graph);
+}
+
+/// Makes the `AssumeLegacyArgumentsUnread` nodes after nodes whose code may
+/// read objects the code never allocated through legacy `arguments` (see
+/// `Graph::defers_legacy_argument_objects()`) `AssumeValid` nodes, and
+/// removes the others.
+fn resolve_legacy_arguments_guards(graph: &mut Graph) {
+ let mut placed = BitSet::new(graph.nodes.len());
+ for node in placed_nodes(graph) {
+ placed.insert(node.index());
+ }
+ let mut removed = BitSet::new(graph.nodes.len());
+ for (guard, nodes) in std::mem::take(&mut graph.legacy_arguments_guards) {
+ let needed = nodes
+ .iter()
+ .any(|node| placed.contains(node.index()) && graph.defers_legacy_argument_objects(*node));
+ if needed {
+ graph.nodes[guard.index()].op = Op::AssumeValid;
+ } else {
+ removed.insert(guard.index());
+ }
+ }
+ edit::remove_nodes(graph, &removed);
}
/// Replaces the objects of `analysis` that do not escape. Fails with the
diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs
index 2b6f932631a..c8c093302ab 100644
--- a/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs
+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs
@@ -465,6 +465,7 @@ fn exits_find_constants_registers_and_spilled_values() {
],
in_frame: Vec::new(),
passed_argument_count: None,
+ legacy_arguments: 0..0,
}],
objects: Vec::new(),
inlined_frame_bytes: 0,
diff --git a/Libraries/LibJS/Rust/src/debugger.rs b/Libraries/LibJS/Rust/src/debugger.rs
index eaa9b013ce0..54176e0d38a 100644
--- a/Libraries/LibJS/Rust/src/debugger.rs
+++ b/Libraries/LibJS/Rust/src/debugger.rs
@@ -268,6 +268,8 @@ impl Debugger {
.expect("a paused frame runs an executable"),
);
+ // NB: The copy must hold the objects that a frame of an inlined call has markers for.
+ crate::jit::translate::resolve_deferred_arguments(vm, execution_context);
let context = execution_context.copy();
let local_environment = new_declarative_environment(
vm,
@@ -402,6 +404,7 @@ impl Debugger {
pub fn bindings_for_frame<'vm>(&self, vm: &'vm Vm, context: &ExecutionContext) -> MarkedVec<'vm, FrameBinding> {
let executable = Executable::from_head(context.executable.get().expect("a frame runs an executable"));
let binding_locations = self.binding_locations_for_frame(context);
+ crate::jit::translate::resolve_deferred_arguments(vm, context);
let bindings = MarkedVec::with_capacity(vm, binding_locations.len());
for (name, location) in binding_locations {
let value = match location.storage {
diff --git a/Libraries/LibJS/Rust/src/jit/code.rs b/Libraries/LibJS/Rust/src/jit/code.rs
index 495830e4f27..0597a4bcfd4 100644
--- a/Libraries/LibJS/Rust/src/jit/code.rs
+++ b/Libraries/LibJS/Rust/src/jit/code.rs
@@ -21,6 +21,7 @@ use crate::interpreter::vm::Vm;
use crate::layout::cell::{CellHeader, Gc};
use crate::layout::execution_context::ExecutionContext;
use crate::layout::function_object::EcmascriptFunctionObject;
+use crate::layout::object::Object;
use crate::runtime::native_javascript_backed_function::NativeJavaScriptBackedFunction;
/// The status word of what JIT code returns, `libjs_jit::code::JitStatus`.
@@ -141,6 +142,25 @@ pub struct JitCode {
/// are no-ops until then.
invalidation_patches: Vec<(u32, Vec<u8>)>,
invalidated: Cell<bool>,
+ /// See `libjs_jit::code::CompiledCode::site_index_frame_offset`.
+ site_index_frame_offset: i32,
+ /// See `libjs_jit::code::CompiledCode::register_dump_frame_offset`.
+ register_dump_frame_offset: i32,
+ /// The objects the code never allocated that the runtime created for frames running the code while they were
+ /// suspended in a call, because code the call ran read them through the legacy `arguments` of a frame of an
+ /// inlined call (see `translate::resolve_deferred_arguments()`). Those frames continue in the interpreter with
+ /// these objects, which only they use. Exits and leaves forget a frame's objects; a frame an exception unwinds
+ /// past its compiled code leaves its objects here until the code detaches. Invalidated code is entered no more,
+ /// so no other frame that runs it can come to have the address of one of them.
+ materialized_objects: RefCell<Vec<MaterializedObject>>,
+}
+
+/// An object created for a frame running JIT code, standing for the object its code never allocated at `allocation`
+/// (see `libjs_jit::code::VirtualObjectDescriptor`).
+struct MaterializedObject {
+ frame: *const ExecutionContext,
+ allocation: u32,
+ object: Gc<Object>,
}
impl JitCode {
@@ -177,9 +197,63 @@ impl JitCode {
id: 0,
invalidation_patches: Vec::new(),
invalidated: Cell::new(false),
+ site_index_frame_offset: 0,
+ register_dump_frame_offset: 0,
+ materialized_objects: RefCell::new(Vec::new()),
}
}
+ /// Gives the code where its frames keep the index of a site and the register dump the runtime reads.
+ pub fn with_frame_offsets(mut self, site_index_frame_offset: i32, register_dump_frame_offset: i32) -> Self {
+ self.site_index_frame_offset = site_index_frame_offset;
+ self.register_dump_frame_offset = register_dump_frame_offset;
+ self
+ }
+
+ pub fn register_dump_frame_offset(&self) -> i32 {
+ self.register_dump_frame_offset
+ }
+
+ /// The index of the site whose values the runtime reads from the JIT frame at `frame_pointer` (see
+ /// `libjs_jit::code::CompiledCode::site_index_frame_offset`).
+ pub fn site_index_of_frame(&self, frame_pointer: u64) -> u32 {
+ let address = frame_pointer.wrapping_add_signed(i64::from(self.site_index_frame_offset)) as *const u32;
+ // SAFETY: The JIT frame is on the stack, suspended in a slow path or call that stored the index there.
+ unsafe { address.read() }
+ }
+
+ /// Stores `index` as the index of the site whose values the runtime reads from the JIT frame at `frame_pointer`.
+ pub fn set_site_index_of_frame(&self, frame_pointer: u64, index: u32) {
+ let address = frame_pointer.wrapping_add_signed(i64::from(self.site_index_frame_offset)) as *mut u32;
+ // SAFETY: The JIT frame is on the stack, suspended in a call, and the code reads the word only where it
+ // stored it.
+ unsafe { address.write(index) }
+ }
+
+ /// The object created for `frame` that stands for the object its code never allocated at `allocation`, if any.
+ pub fn materialized_object(&self, frame: *const ExecutionContext, allocation: u32) -> Option<Gc<Object>> {
+ self.materialized_objects
+ .borrow()
+ .iter()
+ .find(|materialized| materialized.frame == frame && materialized.allocation == allocation)
+ .map(|materialized| materialized.object)
+ }
+
+ pub fn remember_materialized_object(&self, frame: *const ExecutionContext, allocation: u32, object: Gc<Object>) {
+ self.materialized_objects.borrow_mut().push(MaterializedObject {
+ frame,
+ allocation,
+ object,
+ });
+ }
+
+ /// Forgets the objects created for `frame`, which no longer runs the code.
+ pub fn forget_materialized_objects(&self, frame: *const ExecutionContext) {
+ self.materialized_objects
+ .borrow_mut()
+ .retain(|materialized| materialized.frame != frame);
+ }
+
/// Gives the code its id among all code the VM installed, and the bytes that invalidate it.
pub fn with_invalidation(mut self, id: u64, invalidation_patches: Vec<(u32, Vec<u8>)>) -> Self {
self.id = id;
@@ -279,6 +353,9 @@ unsafe impl Trace for JitCode {
for cell in &self.embedded_cells {
visitor.visit(*cell);
}
+ for materialized in self.materialized_objects.borrow().iter() {
+ visitor.visit(materialized.object);
+ }
for executable in &self.snapshot_executables {
visitor.visit(executable.executable);
if let Some(function) = executable.function {
diff --git a/Libraries/LibJS/Rust/src/jit/disabled.rs b/Libraries/LibJS/Rust/src/jit/disabled.rs
index 5131f291307..3a373d91054 100644
--- a/Libraries/LibJS/Rust/src/jit/disabled.rs
+++ b/Libraries/LibJS/Rust/src/jit/disabled.rs
@@ -202,6 +202,8 @@ pub mod translate {
) -> Vec<Value> {
unreachable!("no frame runs JIT code");
}
+
+ pub fn resolve_deferred_arguments(_vm: &Vm, _frame: &ExecutionContext) {}
}
pub mod snapshot {
diff --git a/Libraries/LibJS/Rust/src/jit/tier_up.rs b/Libraries/LibJS/Rust/src/jit/tier_up.rs
index d00306af0ad..b70c8a17073 100644
--- a/Libraries/LibJS/Rust/src/jit/tier_up.rs
+++ b/Libraries/LibJS/Rust/src/jit/tier_up.rs
@@ -303,6 +303,7 @@ fn install(
snapshot,
)
.with_invalidation(id, compiled.invalidation_patches)
+ .with_frame_offsets(compiled.site_index_frame_offset, compiled.register_dump_frame_offset)
.with_osr_outer_loop_back_edges(compiled.osr_outer_loop_back_edges)
.with_uncaught_handlers(compiled.uncaught_handlers);
vm.jit.dependents.register(vm, executable, id, &compiled.dependencies);
diff --git a/Libraries/LibJS/Rust/src/jit/translate.rs b/Libraries/LibJS/Rust/src/jit/translate.rs
index 87f1473dfe4..9d3c46da378 100644
--- a/Libraries/LibJS/Rust/src/jit/translate.rs
+++ b/Libraries/LibJS/Rust/src/jit/translate.rs
@@ -79,6 +79,14 @@ impl RegisterDump {
);
}
+ /// The register dump of the JIT frame at `frame_pointer` of `code`, which holds the values of a publication while
+ /// its slow path runs (see `libjs_jit::code::CompiledCode::register_dump_frame_offset`).
+ fn in_jit_frame(code: &JitCode, frame_pointer: u64) -> RegisterDump {
+ let address = frame_pointer.wrapping_add_signed(i64::from(code.register_dump_frame_offset())) as *const Self;
+ // SAFETY: The JIT frame is on the stack, suspended in the slow path the publication was for.
+ unsafe { address.read() }
+ }
+
/// A dump for reading the values of a call site from the stack slots of the JIT frame at `frame_pointer`, which is
/// all a call site's values are in while the call runs.
fn of_stack_slots(frame_pointer: u64) -> RegisterDump {
@@ -122,22 +130,41 @@ fn read_location(location: ValueLocation, dump: &RegisterDump) -> Value {
}
}
-/// The values of a site, creating the objects the code never allocated once each, so that every slot referring to one
-/// holds the same object. Its users defer collections until the frames hold the values.
+/// The values of a site of `code` for the compiled function's frame `root`, creating the objects the code never
+/// allocated once each, so that every slot referring to one holds the same object: the one created for the frame
+/// before, if any (see `JitCode::materialized_object()`). Its users defer collections until the frames hold the values.
struct SiteValues<'a> {
vm: &'a Vm,
+ code: &'a JitCode,
+ root: *const ExecutionContext,
site: &'a Site,
dump: &'a RegisterDump,
created: HashMap<u32, Gc<Object>>,
+ /// Whether the objects created are remembered for the frame, for a frame that continues in compiled code until it
+ /// leaves it, where the objects must be the same.
+ remember: bool,
+ /// For frames of inlined calls written while compiled code keeps running: the frame pointer of the JIT frame, for
+ /// the markers that argument slots of objects the code never allocated get (see `argument_value()`).
+ deferred_arguments: Option<u64>,
}
impl<'a> SiteValues<'a> {
- fn new(vm: &'a Vm, site: &'a Site, dump: &'a RegisterDump) -> Self {
+ fn new(
+ vm: &'a Vm,
+ code: &'a JitCode,
+ root: NonNull<ExecutionContext>,
+ site: &'a Site,
+ dump: &'a RegisterDump,
+ ) -> Self {
Self {
vm,
+ code,
+ root: root.as_ptr(),
site,
dump,
created: HashMap::new(),
+ remember: false,
+ deferred_arguments: None,
}
}
@@ -149,11 +176,20 @@ impl<'a> SiteValues<'a> {
return Value::from_object(*object);
}
let description = &self.site.objects[index as usize];
+ // NB: An object created for the frame before is the one the frame has, with whatever happened to it since.
+ if let Some(object) = self.code.materialized_object(self.root, description.allocation) {
+ self.created.insert(index, object);
+ return Value::from_object(object);
+ }
// SAFETY: The code embeds the shape, which keeps it alive.
let shape = unsafe { Gc::from_non_null(NonNull::new(description.shape.0 as *mut _).expect("a shape")) };
let object = Object::create_with_premade_shape(self.vm, shape);
// NB: The object exists before its properties, which may refer to it.
self.created.insert(index, object);
+ if self.remember {
+ self.code
+ .remember_materialized_object(self.root, description.allocation, object);
+ }
let property_count = shape.property_count();
for index in 0..property_count {
let value = match description.properties.get(index as usize) {
@@ -165,6 +201,20 @@ impl<'a> SiteValues<'a> {
Value::from_object(object)
}
+ /// The value of the argument slot `slot` at `location` of the frame of `frame_state`, a frame of an inlined call
+ /// written while compiled code keeps running: a marker for an object the code never allocated that the legacy
+ /// `arguments` of the frame's function shows, which code reading them creates (see `resolve_deferred_arguments()`),
+ /// so that nothing creates it while nothing reads it. Compiled code leaves after the calls where they may be read
+ /// (see `libjs_jit::ir::Op::AssumeLegacyArgumentsUnread`).
+ fn argument_value(&mut self, slot: u32, location: ValueLocation, frame_state: &FrameState) -> Value {
+ match (self.deferred_arguments, location) {
+ (Some(frame_pointer), ValueLocation::VirtualObject(_)) if frame_state.legacy_arguments.contains(&slot) => {
+ deferred_argument_marker(frame_pointer)
+ }
+ _ => self.value(location),
+ }
+ }
+
/// The function the frame of `frame_state`, a frame of an inlined call, runs: the closure that was called for
/// frames of inlined closures, and otherwise the function the code was compiled for.
fn function(&mut self, code: &JitCode, frame_state: &FrameState) -> InlinedFunction {
@@ -185,6 +235,47 @@ impl<'a> SiteValues<'a> {
}
}
+/// The bits of a marker in the argument slot of a frame of an inlined call for an object the code never allocated
+/// (see `SiteValues::argument_value()`), with the low half of the JIT frame's frame pointer in the low bits: the empty
+/// value with a payload no other empty value has. The garbage collector skips it, and nothing else reads the slot
+/// before a leave writes the object there, but code reading the legacy `arguments` of the frame's function.
+const DEFERRED_ARGUMENT_MARKER: u64 = Value::EMPTY.0 | (1 << 47);
+
+fn deferred_argument_marker(frame_pointer: u64) -> Value {
+ Value(DEFERRED_ARGUMENT_MARKER | (frame_pointer & u64::from(u32::MAX)))
+}
+
+/// The low half of the frame pointer of the JIT frame that `value` is a marker of an object of (see
+/// `DEFERRED_ARGUMENT_MARKER`), if it is one.
+fn deferred_argument_frame_pointer(value: Value) -> Option<u32> {
+ (value.0 & !u64::from(u32::MAX) == DEFERRED_ARGUMENT_MARKER).then_some(value.0 as u32)
+}
+
+/// The slot of the first argument of frames of `executable`.
+fn arguments_base_of(executable: &Executable) -> u32 {
+ executable.registers_and_locals_count()
+ + u32::try_from(executable.constants().len()).expect("the constant count fits in u32")
+}
+
+/// Where `frame_state`, of a frame of `executable`, has the argument `argument`, if it lists it.
+fn argument_location(frame_state: &FrameState, executable: &Executable, argument: u32) -> Option<ValueLocation> {
+ let slot = arguments_base_of(executable) + argument;
+ frame_state
+ .values
+ .iter()
+ .find(|(listed, _)| *listed == slot)
+ .map(|(_, location)| *location)
+}
+
+/// Whether `code` is the code `compiled_executable` has installed. What discarded code learns counts for no later
+/// code.
+fn is_installed_code(vm: &Vm, compiled_executable: &Executable, code: &JitCode) -> bool {
+ compiled_executable.jit_compile_state() == CompileState::Installed
+ && compiled_executable
+ .jit_code(vm)
+ .is_some_and(|installed| core::ptr::eq(installed, code))
+}
+
/// How the frame of a frame state at a call is linked to the frame of its callee.
#[derive(Clone, Copy)]
struct CallLinkage {
@@ -391,6 +482,8 @@ fn write_frame_state(
// NB: Every slot holding the arguments object the code never created holds the same object, which is created from
// the frame's arguments once they are written: frames of inlined calls get theirs from the frame state too.
let mut arguments_object_slots = Vec::new();
+ let arguments_base = arguments_base_of(&executable_of(frame));
+ let mut has_deferred_arguments = false;
for (slot, location) in &frame_state.values {
// NB: The function object of a frame of an inlined closure is in no slot.
if *slot == CALLEE_SLOT || Some(*slot) == kept {
@@ -400,9 +493,17 @@ fn write_frame_state(
arguments_object_slots.push((*slot, *mapped));
continue;
}
- slots[*slot as usize].set(values.value(*location));
+ let value = if *slot >= arguments_base {
+ values.argument_value(*slot, *location, frame_state)
+ } else {
+ values.value(*location)
+ };
+ has_deferred_arguments |= deferred_argument_frame_pointer(value).is_some();
+ slots[*slot as usize].set(value);
}
- if let Some((_, mapped)) = arguments_object_slots.first() {
+ // NB: A frame with markers among its arguments does not run in the interpreter before a leave writes it again, and
+ // nothing else reads its arguments object.
+ if let Some((_, mapped)) = arguments_object_slots.first().filter(|_| !has_deferred_arguments) {
let arguments_object = create_arguments_object(vm, frame, *mapped);
for (slot, _) in &arguments_object_slots {
slots[*slot as usize].set(arguments_object);
@@ -504,7 +605,7 @@ pub(super) fn exit(vm: &Vm, root: NonNull<ExecutionContext>, code: &JitCode, ind
// NB: Nothing may collect the objects created here before the frames hold them.
let _defer_gc = DeferGc::new(vm);
- let mut values = SiteValues::new(vm, site, dump);
+ let mut values = SiteValues::new(vm, code, root, site, dump);
let innermost = push_site_frames(
vm,
code,
@@ -513,6 +614,7 @@ pub(super) fn exit(vm: &Vm, root: NonNull<ExecutionContext>, code: &JitCode, ind
CompiledFunctionFrame::Write,
Destination::Keep,
);
+ code.forget_materialized_objects(root.as_ptr());
let frame_state = &site.frames[0];
let frame_ref = frame_of(innermost);
let executable = executable_of(frame_ref);
@@ -569,12 +671,7 @@ pub(super) fn exit(vm: &Vm, root: NonNull<ExecutionContext>, code: &JitCode, ind
// NB: Sites in inlined callees are their executables', but the compiled code learns from them too.
executable.add_jit_exit_site((frame_state.pc, kind)) >= snapshot_executable.known_exit_sites
};
- // NB: What code that was discarded already learns counts for no later code.
- let is_installed_code = compiled_executable.jit_compile_state() == CompileState::Installed
- && compiled_executable
- .jit_code(vm)
- .is_some_and(|installed| core::ptr::eq(installed, code));
- if learned && is_installed_code {
+ if learned && is_installed_code(vm, &compiled_executable, code) {
compiled_executable.note_learned_jit_exit_site();
}
@@ -595,6 +692,7 @@ pub(super) fn leave(vm: &Vm, root: NonNull<ExecutionContext>, code: &JitCode, in
assert_eq!(site.kind, SiteKind::Leave);
// NB: The pushed frames are right above the compiled function's, outermost first.
let Some(frames) = frames_above(vm, root) else {
+ code.forget_materialized_objects(root.as_ptr());
return;
};
let frame_states = &site.frames;
@@ -602,7 +700,7 @@ pub(super) fn leave(vm: &Vm, root: NonNull<ExecutionContext>, code: &JitCode, in
// NB: Nothing may collect the objects created here before the frames hold them.
let _defer_gc = DeferGc::new(vm);
- let mut values = SiteValues::new(vm, site, dump);
+ let mut values = SiteValues::new(vm, code, root, site, dump);
let mut write = |frame: &ExecutionContext, frame_state: &FrameState| {
let expected = code.snapshot_executable(frame_state.executable).executable;
assert!(executable_of(frame) == expected);
@@ -614,6 +712,7 @@ pub(super) fn leave(vm: &Vm, root: NonNull<ExecutionContext>, code: &JitCode, in
let frame = frames[frames.len() - 1 - index];
write(frame_of(frame), &frame_states[frame_states.len() - 2 - index]);
}
+ code.forget_materialized_objects(root.as_ptr());
}
/// Header translation for a slow path or call in an inlined callee, which takes its operands as values (see
@@ -628,7 +727,9 @@ pub(super) fn publish(vm: &Vm, root: NonNull<ExecutionContext>, code: &JitCode,
assert!(frame_states.len() >= 2);
// NB: Nothing may collect the objects created here before the frames hold them.
let _defer_gc = DeferGc::new(vm);
- let mut values = SiteValues::new(vm, site, dump);
+ let mut values = SiteValues::new(vm, code, root, site, dump);
+ // NB: The values of the site stay in the register dump of the JIT frame while the slow path runs.
+ values.deferred_arguments = Some(dump.gprs[RegisterDump::FRAME_POINTER]);
// NB: The compiled function's frame is at the call of the outermost inlined call, which stack walks show.
let root_frame_state = frame_states.last().expect("a frame state");
frame_of(root).program_counter.set(root_frame_state.pc);
@@ -638,8 +739,7 @@ pub(super) fn publish(vm: &Vm, root: NonNull<ExecutionContext>, code: &JitCode,
let frame = push_frame(vm, function, linkage, FrameSlots::Uninitialized);
let frame_ref = frame_of(frame);
let executable = executable_of(frame_ref);
- let arguments_base = executable.registers_and_locals_count()
- + u32::try_from(executable.constants().len()).expect("the constant count fits in u32");
+ let arguments_base = arguments_base_of(&executable);
let slots = frame_ref.slots();
for (slot, location) in &frame_state.values {
if *slot == register::THIS_VALUE {
@@ -649,7 +749,7 @@ pub(super) fn publish(vm: &Vm, root: NonNull<ExecutionContext>, code: &JitCode,
frame_ref.this_value.set(this_value);
}
} else if *slot != CALLEE_SLOT && *slot >= arguments_base {
- slots[*slot as usize].set(values.value(*location));
+ slots[*slot as usize].set(values.argument_value(*slot, *location, frame_state));
}
}
frame_ref.program_counter.set(frame_state.pc);
@@ -695,7 +795,11 @@ pub(super) fn materialize_call_site_frames(
// NB: Nothing may collect the objects created here before the frames hold them.
let _defer_gc = DeferGc::new(vm);
let dump = RegisterDump::of_stack_slots(frame_pointer);
- let mut values = SiteValues::new(vm, site, &dump);
+ let mut values = SiteValues::new(vm, code, root, site, &dump);
+ // NB: Compiled code keeps running once the call returns, and the call may read the frames' legacy arguments, which
+ // find their values through the site (see `resolve_deferred_arguments()`).
+ values.deferred_arguments = Some(frame_pointer);
+ code.set_site_index_of_frame(frame_pointer, index);
let innermost = push_site_frames(
vm,
code,
@@ -793,7 +897,8 @@ pub fn call_site_frames(vm: &Vm, frame: &ExecutionContext, index: u32, frame_poi
/// View translation: the passed arguments of the frame of an inlined call that a call at the call site `index` of the
/// code running `frame` is in, the one with the frame state at `frame_state` of the site, while it runs without it,
-/// with the JIT frame at `frame_pointer`.
+/// with the JIT frame at `frame_pointer`, for code reading the legacy `arguments` of the frame's function. Objects
+/// among them that the code never allocated are created for the frame (see `note_legacy_arguments_read()`).
pub fn call_site_frame_arguments(
vm: &Vm,
frame: &ExecutionContext,
@@ -811,18 +916,108 @@ pub fn call_site_frame_arguments(
let passed_argument_count = call_linkage(&caller_executable, caller_frame_state).passed_argument_count;
let frame_state = &site.frames[frame_state];
let executable = code.snapshot_executable(frame_state.executable).executable;
- let arguments_base = executable.registers_and_locals_count()
- + u32::try_from(executable.constants().len()).expect("the constant count fits in u32");
// NB: The caller keeps collections deferred while it holds the objects created here.
let dump = RegisterDump::of_stack_slots(frame_pointer);
- let mut values = SiteValues::new(vm, site, &dump);
- (0..passed_argument_count)
+ let mut values = SiteValues::new(vm, code, NonNull::from(frame), site, &dump);
+ values.remember = true;
+ let mut reads_objects = false;
+ let arguments = (0..passed_argument_count)
.map(|argument| {
- frame_state
- .values
- .iter()
- .find(|(slot, _)| *slot == arguments_base + argument)
- .map_or(Value::UNDEFINED, |(_, location)| values.value(*location))
+ let location = argument_location(frame_state, &executable, argument);
+ reads_objects |= matches!(location, Some(ValueLocation::VirtualObject(_)));
+ location.map_or(Value::UNDEFINED, |location| values.value(location))
})
- .collect()
+ .collect();
+ if reads_objects {
+ note_legacy_arguments_read(vm, frame, code, frame_state);
+ }
+ arguments
+}
+
+/// Replaces the markers among the arguments of `frame` for objects the code never allocated (see
+/// `SiteValues::argument_value()`) with the objects, for code reading the legacy `arguments` of the frame's function or
+/// the debugger: a frame of an inlined call written while compiled code keeps running has them. The objects are
+/// created for the compiled function's frame from the values of the site its JIT frame is suspended at (see
+/// `note_legacy_arguments_read()`). Copies of the frame then hold the objects too.
+pub fn resolve_deferred_arguments(vm: &Vm, frame: &ExecutionContext) {
+ for (argument, slot) in (0..).zip(frame.arguments()) {
+ if let Some(low_half) = deferred_argument_frame_pointer(slot.get()) {
+ slot.set(deferred_argument(
+ vm,
+ frame,
+ argument,
+ frame_pointer_from_low_half(low_half),
+ ));
+ }
+ }
+}
+
+/// The object a marker in the argument slot `argument` of `frame` stands for, created for the frame of the compiled
+/// function whose JIT frame is at `frame_pointer`.
+fn deferred_argument(vm: &Vm, frame: &ExecutionContext, argument: u32, frame_pointer: u64) -> Value {
+ // NB: The frames of inlined calls are right above the compiled function's frame, the first below them that JIT
+ // code runs.
+ let mut depth = 0;
+ let mut root = frame.caller_frame.get();
+ loop {
+ // SAFETY: A frame's callers outlive it.
+ let caller = unsafe { root.as_ref() }.expect("the frames of inlined calls are above the compiled function's");
+ if caller.runs_jit_code.get() {
+ break;
+ }
+ depth += 1;
+ root = caller.caller_frame.get();
+ }
+ let root = NonNull::new(root).expect("the compiled function's frame is not null");
+ let code = executable_of(frame_of(root))
+ .jit_code(vm)
+ .expect("a frame suspended in JIT code has it attached");
+ let site = code.site(code.site_index_of_frame(frame_pointer));
+ let frame_state = &site.frames[site.frames.len() - 2 - depth];
+ let executable = executable_of(frame);
+ assert!(code.snapshot_executable(frame_state.executable).executable == executable);
+ let location =
+ argument_location(frame_state, &executable, argument).expect("the frame state lists arguments with markers");
+ assert!(matches!(location, ValueLocation::VirtualObject(_)));
+ // NB: The objects created here are remembered for the frame, which keeps them alive.
+ let _defer_gc = DeferGc::new(vm);
+ // NB: The values of a publication are in the JIT frame's register dump while its slow path runs; those of a call
+ // site, in stack slots.
+ let dump = match site.kind {
+ SiteKind::Publish => RegisterDump::in_jit_frame(code, frame_pointer),
+ _ => RegisterDump::of_stack_slots(frame_pointer),
+ };
+ let mut values = SiteValues::new(vm, code, root, site, &dump);
+ values.remember = true;
+ let object = values.value(location);
+ note_legacy_arguments_read(vm, frame_of(root), code, frame_state);
+ object
+}
+
+/// Makes `code`, which runs `root`, leave compiled code after the call `root` is suspended in, whose code read objects
+/// the code never allocated through the legacy `arguments` of the function of the frame of `frame_state`: the code is
+/// invalidated, so that the frame exits after the call (see `libjs_jit::ir::Op::AssumeLegacyArgumentsUnread`) with the
+/// objects created for it, and discarded. Its recompiles allocate the objects at that call (see
+/// `ExitKind::LegacyArgumentsRead`).
+fn note_legacy_arguments_read(vm: &Vm, root: &ExecutionContext, code: &JitCode, frame_state: &FrameState) {
+ let snapshot_executable = code.snapshot_executable(frame_state.executable);
+ let executable = snapshot_executable.executable;
+ let site = (frame_state.pc, libjs_jit::code::ExitKind::LegacyArgumentsRead);
+ let learned = executable.add_jit_exit_site(site) >= snapshot_executable.known_exit_sites;
+ let compiled_executable = executable_of(root);
+ if learned && is_installed_code(vm, &compiled_executable, code) {
+ compiled_executable.note_learned_jit_exit_site();
+ }
+ if vm.jit.options.log_exits && !code.is_invalidated() {
+ eprintln!(
+ "JIT invalidate: {}, legacy arguments of {} read at pc {}",
+ super::describe_executable(&compiled_executable),
+ super::describe_executable(&executable),
+ frame_state.pc
+ );
+ }
+ code.invalidate();
+ if is_installed_code(vm, &compiled_executable, code) {
+ compiled_executable.discard_jit_code(vm);
+ }
}
diff --git a/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rs b/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rs
index 2939af9fa43..eea514fcb75 100644
--- a/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rs
+++ b/Libraries/LibJS/Rust/src/runtime/ecmascript_function_object.rs
@@ -1011,6 +1011,9 @@ impl EcmascriptFunctionObject {
.collect(),
None => {
let context = frame.execution_context;
+ // NB: The frame of an inlined call that JIT code published or materialized for a call it made has
+ // markers for the objects among its arguments that the code never allocated.
+ crate::jit::translate::resolve_deferred_arguments(vm, context);
context.arguments()[..context.passed_argument_count.get() as usize]
.iter()
.map(|argument| Cell::new(argument.get()))
diff --git a/Tests/LibJS/JIT/ir/legacy-arguments-eligibility.js b/Tests/LibJS/JIT/ir/legacy-arguments-eligibility.js
index 9d488571c15..626e2df613b 100644
--- a/Tests/LibJS/JIT/ir/legacy-arguments-eligibility.js
+++ b/Tests/LibJS/JIT/ir/legacy-arguments-eligibility.js
@@ -1,21 +1,24 @@
-// Only functions with legacy arguments properties expose their inlined arguments to calls.
+// Calls in inlined functions with legacy arguments properties may run code that reads the function's arguments through
+// them. Objects among them that the code never allocated stay unallocated: the runtime creates them for code that reads
+// them, and the code exits after the call (AssumeValid). Where code read them before, recompiles allocate them there.
-function opaque() {
+function opaque(read) {
// A debugger statement keeps this function from being inlined.
debugger;
+ if (read) return ordinary.arguments[0].x;
}
const arrow = object => {
- opaque();
+ opaque(false);
return object.x;
};
const holder = {
method(object) {
- opaque();
+ opaque(false);
return object.x;
},
};
-function ordinary(object) {
- opaque();
+function ordinary(object, read) {
+ opaque(read);
return object.x;
}
function throughArrow(x) {
@@ -25,31 +28,60 @@ function throughMethod(x) {
return holder.method({ x });
}
function throughOrdinary(x) {
- return ordinary({ x });
+ return ordinary({ x }, false);
}
-for (const fn of [opaque, arrow, holder.method, ordinary, throughArrow, throughMethod, throughOrdinary])
+function throughOrdinaryAfterRead(x, read) {
+ return ordinary({ x }, read);
+}
+for (const fn of [
+ opaque,
+ arrow,
+ holder.method,
+ ordinary,
+ throughArrow,
+ throughMethod,
+ throughOrdinary,
+ throughOrdinaryAfterRead,
+])
jit.prepare(fn);
for (let i = 0; i < 10; ++i) {
throughArrow(i);
throughMethod(i);
throughOrdinary(i);
+ throughOrdinaryAfterRead(i, false);
}
jit.compile(throughArrow);
jit.compile(throughMethod);
jit.compile(throughOrdinary);
+jit.compile(throughOrdinaryAfterRead);
+throughOrdinaryAfterRead(1, true);
+jit.compile(throughOrdinaryAfterRead);
// CHECK-FUNCTION: throughArrow
// CHECK-PASS: graph building
// CHECK: AllocateObject
+// CHECK-NOT: AssumeLegacyArgumentsUnread
// CHECK-PASS: escape analysis
// CHECK-NOT: AllocateObject
// CHECK-FUNCTION: throughMethod
// CHECK-PASS: graph building
// CHECK: AllocateObject
+// CHECK-NOT: AssumeLegacyArgumentsUnread
// CHECK-PASS: escape analysis
// CHECK-NOT: AllocateObject
// CHECK-FUNCTION: throughOrdinary
+// CHECK-PASS: graph building
+// CHECK: AllocateObject
+// CHECK: CallDirect
+// CHECK-NEXT: AssumeLegacyArgumentsUnread
+// CHECK-PASS: escape analysis
+// CHECK-NOT: AllocateObject
+// CHECK: CallDirect
+// CHECK-NEXT: AssumeValid
+
+// CHECK-FUNCTION: throughOrdinaryAfterRead
// CHECK-PASS: escape analysis
// CHECK: AllocateObject
+// CHECK: CallDirect