Truly independent web browser
LibJS/JIT: Read the tables of installed code where they are
Andreas Kling133a8c35a92f
diff --git a/Libraries/LibJS/JIT/Rust/src/artifact.rs b/Libraries/LibJS/JIT/Rust/src/artifact.rsindex b8fc9f621e7..a2bea6db9df 100644--- a/Libraries/LibJS/JIT/Rust/src/artifact.rs+++ b/Libraries/LibJS/JIT/Rust/src/artifact.rs@@ -626,6 +626,15 @@ impl<'a, W: Word> Artifact<'a, W> {pcs.zip(self.section(Section::OsrOffsets).iter().map(W::word))}+ /// The offset within the code of the on-stack replacement entry point at `pc`, if there is one.+ pub fn osr_entry(self, pc: u32) -> Option<u32> {+ let index = self+ .section(Section::OsrPcs)+ .binary_search_by(|word| word.word().cmp(&pc))+ .ok()?;+ Some(self.section(Section::OsrOffsets)[index].word())+ }+/// The loop back edges from where a frame running in the interpreter reaches one of the `osr_entries()` without/// leaving the loop it is in.pub fn osr_loop_back_edges(self) -> Run<'a, W> {diff --git a/Libraries/LibJS/JIT/Rust/src/code.rs b/Libraries/LibJS/JIT/Rust/src/code.rsindex 1b6cf880771..a62fae64e53 100644--- a/Libraries/LibJS/JIT/Rust/src/code.rs+++ b/Libraries/LibJS/JIT/Rust/src/code.rs@@ -9,7 +9,6 @@use crate::artifact::Artifact;use crate::artifact::Layout;-use crate::artifact::SiteView;use crate::snapshot::CellId;/// Compiled machine code for one executable, not yet installed.@@ -48,11 +47,6 @@ impl CompiledCode {pub fn artifact(&self) -> Artifact<'_> {Artifact::new(&self.words, &self.layout)}-- /// The sites of the code, by index, as values that own their parts.- pub fn sites(&self) -> Vec<Site> {- self.artifact().sites().map(Site::from_view).collect()- }}/// The status word of `JitResult { u64 value; u64 status; }`, returned by@@ -201,52 +195,6 @@ pub enum Dependency {StableShape(CellId),}-/// A point of compiled code where the runtime may translate its state into-/// interpreter frames (see `SiteKind`): the frame states there, and where-/// their values are.-#[derive(Debug, Clone, PartialEq, Eq)]-pub struct Site {- pub kind: SiteKind,- /// The frames there, innermost first: the frames of the inlined calls- /// the site is in, and the compiled function's frame.- pub frames: Box<[FrameState]>,- /// The objects the compiled code never allocated, which the frames'- /// values refer to (as `ValueLocation::VirtualObject`).- pub objects: Box<[VirtualObjectDescriptor]>,- /// For a `SiteKind::Call`: the room for the frames of the inlined calls- /// that the call leaves below its callee's frame (see `Op::CallDirect`).- pub inlined_frame_bytes: u32,-}--impl Site {- fn from_view(site: SiteView<'_>) -> Self {- Self {- kind: site.kind(),- frames: site- .frames()- .map(|frame| FrameState {- executable: frame.executable(),- pc: frame.pc(),- mode: frame.mode(),- values: frame.values().collect(),- in_frame: frame.in_frame().iter().collect(),- passed_argument_count: frame.passed_argument_count(),- legacy_arguments: frame.legacy_arguments(),- })- .collect(),- objects: site- .objects()- .map(|object| VirtualObjectDescriptor {- kind: object.kind(),- allocation: object.allocation(),- properties: object.properties().collect(),- })- .collect(),- inlined_frame_bytes: site.inlined_frame_bytes(),- }- }-}-/// What a site of compiled code is. The runtime translates the state of/// compiled code at any of them into interpreter frames the same way.#[derive(Debug, Clone, Copy, PartialEq, Eq)]@@ -274,21 +222,8 @@ pub enum SiteKind {Call,}-/// An object the compiled code never allocated, which an exit creates as-/// `kind` says. Each one is created once per exit, before any is given its-/// properties, so objects may refer to each other.-#[derive(Debug, Clone, PartialEq, Eq)]-pub struct VirtualObjectDescriptor {- pub kind: VirtualObjectDescriptorKind,- /// The node index of the allocation the object stands for, which is the- /// same at every site of the code: the runtime may have created the- /// object at another site of the same frame already, and then uses that.- pub allocation: u32,- /// The values `kind` describes.- pub properties: Box<[ValueLocation]>,-}--/// What kind of object a `VirtualObjectDescriptor` describes.+/// What kind of object the runtime creates for one that compiled code never allocated (see+/// `artifact::ObjectView`).#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum VirtualObjectDescriptorKind {/// A plain object of `shape`, with the values of its properties in@@ -320,35 +255,11 @@ pub enum ResumeMode {ResumeAfter { dst: u32 },}-/// The slot of `FrameState::values` that holds the function object of a frame+/// The slot among the values of a frame (see `artifact::FrameView::values()`) that holds the function object of a frame/// of an inlined closure, whose frames run the closure that was called/// rather than the function object of the snapshot. It is in no frame slot.pub const CALLEE_SLOT: u32 = u32::MAX - 1;-/// The interpreter state of one frame at an exit.-#[derive(Debug, Clone, PartialEq, Eq)]-pub struct FrameState {- /// Index into `Snapshot::executables`.- pub executable: u32,- pub pc: u32,- pub mode: ResumeMode,- /// The value of each frame slot that differs from what the frame already- /// holds, in slot order.- pub values: Box<[(u32, ValueLocation)]>,- /// The live slots whose value the frame already holds (see- /// `ir::FrameState::in_frame`), in slot order. Exits clear the registers- /// and locals listed in neither, except a `ResumeAfter` destination,- /// which exits never write either.- pub in_frame: Box<[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.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum ValueLocation {@@ -366,7 +277,7 @@ pub enum ValueLocation {/// the runtime creates it from the frame's arguments like/// `CreateArguments` does, mapped or unmapped, once per exit.ArgumentsObject { mapped: bool },- /// The object at this index of `Site::objects`.+ /// The object at this index among those of the site (see `artifact::SiteView::object()`).VirtualObject(u32),}diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs b/Libraries/LibJS/JIT/Rust/src/codegen/tests.rsindex 2b54c66bce7..758824397e2 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs@@ -9,6 +9,7 @@//! offsets, and Rust functions standing in for the slow paths and helpers.use super::*;+use crate::artifact::Layout;use crate::bytecode::FrameLayout;use crate::bytecode::Instruction;use crate::bytecode::NUM_OPCODES;@@ -17,7 +18,6 @@ use crate::bytecode::Operand;use crate::bytecode::test_support::*;use crate::code::CompiledCode;use crate::code::ExitKind;-use crate::code::Site;use crate::code::ValueLocation;use crate::compile_for;use crate::snapshot::FunctionFrameFields;@@ -134,7 +134,9 @@ struct TestState {cells: Vec<u64>,/// Every frame of every exit taken.exit_frames: Vec<Vec<ExitFrame>>,- exits: Vec<Site>,+ /// The tables of the code, which have `layout`.+ tables: Vec<u32>,+ layout: Layout,exits_taken: Vec<u32>,/// Make the slow path of the instruction at this pc return this control word.fail: Option<(u32, i64)>,@@ -445,14 +447,17 @@ extern "C" fn to_boolean(value: u64) -> u64 {/// like the runtime does. Leaves neither count as exits nor move the pc.#[jit_abi]extern "C" fn jit_exit(vm: *mut u64, frame: *mut u64, exit_index: u32, dump: *const u64) {- if test_state(vm).borrow().exits[exit_index as usize].kind == SiteKind::Publish {+ let kind = {+ let state = test_state(vm).borrow();+ Artifact::new(&state.tables, &state.layout).site(exit_index).kind()+ };+ if kind == SiteKind::Publish {publish_frames(vm, exit_index);return;}// NB: Unlike the runtime, the fake pushes no frames for slow paths of// fast paths in inlined callees.- let is_leave = matches!(test_state(vm).borrow().exits[exit_index as usize].kind, SiteKind::Leave);- if is_leave {+ if kind == SiteKind::Leave {write_frame_states(vm, frame, exit_index, dump, Leaving::Yes);return;}@@ -464,23 +469,27 @@ extern "C" fn jit_exit(vm: *mut u64, frame: *mut u64, exit_index: u32, dump: *co/// calls of a publish site on the fake interpreter stack, linked to their/// callers, uninitialized, with their pc.fn publish_frames(vm: *mut u64, exit_index: u32) {- let (site, layouts, cells) = {+ let (tables, tables_layout, layouts, cells) = {let state = test_state(vm).borrow();(- state.exits[exit_index as usize].clone(),+ state.tables.clone(),+ state.layout,state.layouts.clone(),state.cells.clone(),)};- for frame_state in site.frames.iter().rev().skip(1) {- let layout = layouts[frame_state.executable as usize];+ let site = Artifact::new(&tables, &tables_layout).site(exit_index);+ // NB: The last frame is the compiled function's.+ for index in (0..site.frame_count() - 1).rev() {+ let frame_state = site.frame(index);+ let layout = layouts[frame_state.executable() as usize];// SAFETY: The fake VM and interpreter stack of the running test are alive.unsafe {let frame = *vm.add(3) as *mut u64;*frame.add(FRAME_CALLER_WORD) = *vm;- *frame.cast::<u32>() = frame_state.pc;+ *frame.cast::<u32>() = frame_state.pc();*frame.add(3) &= !0xff;- *frame.add(FRAME_EXECUTABLE_WORD) = cells[frame_state.executable as usize];+ *frame.add(FRAME_EXECUTABLE_WORD) = cells[frame_state.executable() as usize];*vm = frame as u64;*vm.add(3) =frame.add(FRAME_HEADER_WORDS + (layout.arguments_base() + layout.number_of_arguments) as usize) as u64;@@ -495,31 +504,31 @@ enum Leaving {}fn write_frame_states(vm: *mut u64, frame: *mut u64, exit_index: u32, dump: *const u64, leaving: Leaving) {- let descriptor = test_state(vm).borrow().exits[exit_index as usize].clone();- assert_eq!(descriptor.kind == SiteKind::Leave, leaving == Leaving::Yes);+ let (tables, tables_layout) = {+ let state = test_state(vm).borrow();+ (state.tables.clone(), state.layout)+ };+ let site = Artifact::new(&tables, &tables_layout).site(exit_index);+ assert_eq!(site.kind() == SiteKind::Leave, leaving == Leaving::Yes);let frame_pointer_index = <crate::asm::MacroAssembler as PortableMacroAssembler>::FRAME_POINTER.0 as usize;let gpr_dump_count = register_dump_counts::<crate::asm::MacroAssembler>().0 as usize;// SAFETY: The dump and the JIT frame it points into are alive during the call.let frames = unsafe {let frame_pointer = *dump.add(frame_pointer_index);- descriptor- .frames- .iter()+ site.frames().map(|frame_state| {// NB: Like the runtime, create one arguments object per frame.if frame_state- .values- .iter()+ .values().any(|(_, location)| matches!(location, ValueLocation::ArgumentsObject { .. })){test_state(vm).borrow_mut().arguments_created += 1;}let values = frame_state- .values- .iter()+ .values().map(|(slot, location)| {// NB: Like the runtime, box unboxed values.- let value = match *location {+ let value = match location {ValueLocation::Register(register, repr) => {// NB: Like the runtime, read float64 values from the FPRs, which the dump// holds after the GPRs.@@ -539,10 +548,10 @@ fn write_frame_states(vm: *mut u64, frame: *mut u64, exit_index: u32, dump: *conValueLocation::ArgumentsObject { mapped } => fake_arguments_object(mapped),ValueLocation::VirtualObject(_) => unreachable!("tests make no virtual objects"),};- (*slot, value)+ (slot, value)}).collect::<Vec<_>>();- (frame_state.executable, frame_state.pc, frame_state.mode, values)+ (frame_state.executable(), frame_state.pc(), frame_state.mode(), values)}).collect::<Vec<_>>()};@@ -573,7 +582,7 @@ fn write_frame_states(vm: *mut u64, frame: *mut u64, exit_index: u32, dump: *contest_state(vm).borrow_mut().exit_frames.push(frames);return;}- if descriptor.frames.len() < 2 {+ if site.frame_count() < 2 {return;}// NB: Like the runtime, write the frames compiled code pushed, which are@@ -938,7 +947,8 @@ impl Machine {.iter().map(|executable| executable.cell.0).collect();- state.exits = compiled.sites();+ state.tables.clone_from(&compiled.words);+ state.layout = compiled.layout;state.exits_taken.clear();}let code = crate::asm::executable_code::ExecutableCode::new(&compiled.code);@@ -1621,11 +1631,10 @@ mod execution {]});let (_, compiled) = compile_program(&program, test_layout(), &[5]);- assert!(compiled.sites().iter().any(|site| {- site.frames[0]- .values- .iter()- .any(|(slot, location)| *slot == l(0).raw() && *location == ValueLocation::Frame(a(0).raw()))+ assert!(compiled.artifact().sites().any(|site| {+ site.frame(0)+ .values()+ .any(|(slot, location)| slot == l(0).raw() && location == ValueLocation::Frame(a(0).raw()))}));let (result, machine) = run_with(&program, test_layout(), &[value::int32(5)], &[5], |_| {});assert_eq!(result.status, RESUME);@@ -2389,7 +2398,7 @@ fn aarch64_code_disassembles() {assert!(text.contains("blr"), "{text}");assert!(text.contains("ret"), "{text}");// NB: The slow paths of JumpLessThan and NewArray leave through sites.- let kinds = compiled.sites().iter().map(|site| site.kind).collect::<Vec<_>>();+ let kinds = compiled.artifact().sites().map(|site| site.kind()).collect::<Vec<_>>();assert_eq!(kinds,[SiteKind::Exit(ExitKind::NoFeedback), SiteKind::Leave, SiteKind::Leave]@@ -2666,7 +2675,7 @@ mod property_access {let taken = machine.state.borrow().exits_taken.clone();taken.iter()- .map(|index| match compiled.sites()[*index as usize].kind {+ .map(|index| match compiled.artifact().site(*index).kind() {SiteKind::Exit(kind) => kind,kind => panic!("{kind:?} is no exit"),})@@ -3070,7 +3079,7 @@ fn aarch64_property_access_disassembles() {assert!(text.contains("ldrb"), "{text}");// Object check, shape switch and two loads; object, shape, chain and// holder load checks; object, shape and store checks.- assert_eq!(compiled.sites().len(), 11, "{text}");+ assert_eq!(compiled.artifact().site_count(), 11, "{text}");let compiled =compile_for::<crate::asm::x86_64::MacroAssembler>(&snapshot, &|_| true, &mut crate::scratch::Scratch::new()).unwrap();@@ -3172,7 +3181,7 @@ mod inlining {// Compiled code published the callee's frame for its Exp, linked to// the caller like an interpreter inline call and uninitialized, and// popped it again.- assert!(!compiled.sites().iter().any(|site| site.kind == SiteKind::Publish));+ assert!(!compiled.artifact().sites().any(|site| site.kind() == SiteKind::Publish));assert_eq!(machine.vm[0], machine.frame.as_ptr() as u64);assert_eq!(machine.vm[3], machine.interpreter_stack.as_ptr() as u64);let pushed = &machine.interpreter_stack;@@ -3233,9 +3242,9 @@ mod inlining {assert!(machine.state.borrow().exits_taken.is_empty(), "leaves are no exits");assert!(compiled+ .artifact().sites()- .iter()- .any(|site| site.kind == SiteKind::Leave && site.frames.len() > 1)+ .any(|site| site.kind() == SiteKind::Leave && site.frame_count() > 1));assert_eq!(slot(&machine, l(1)), value::int32(10));assert_eq!(machine.slot(r(6)), machine.slot(c(1)));@@ -3271,7 +3280,7 @@ mod inlining {);assert_eq!(result, returned(value::int32(25)));assert_eq!(machine.vm[3], machine.interpreter_stack.as_ptr() as u64);- assert!(!compiled.sites().iter().any(|site| site.kind == SiteKind::Publish));+ assert!(!compiled.artifact().sites().any(|site| site.kind() == SiteKind::Publish));// The slow path of an Add of undefined runs in the callee's frame,// which compiled code publishes, and continues after popping it: 10@@ -3284,7 +3293,7 @@ mod inlining {assert_eq!(machine.vm[0], machine.frame.as_ptr() as u64);assert_eq!(machine.vm[3], machine.interpreter_stack.as_ptr() as u64);// NB: Compiled code publishes the frames, not the runtime.- assert!(!compiled.sites().iter().any(|site| site.kind == SiteKind::Publish));+ assert!(!compiled.artifact().sites().any(|site| site.kind() == SiteKind::Publish));// A slow path that does not continue leaves the interpreter in the// callee's frame.@@ -3314,7 +3323,7 @@ mod inlining {assert_eq!(result.status, RESUME);let state = machine.state.borrow();assert_eq!(- compiled.sites()[state.exits_taken[0] as usize].kind,+ compiled.artifact().site(state.exits_taken[0]).kind(),SiteKind::Exit(ExitKind::BadCallTarget));assert_eq!(state.exit_frames[0].len(), 1);@@ -3465,7 +3474,7 @@ mod virtual_arguments {assert_eq!(result.status, RESUME);let state = machine.state.borrow();assert_eq!(- compiled.sites()[state.exits_taken[0] as usize].kind,+ compiled.artifact().site(state.exits_taken[0]).kind(),SiteKind::Exit(ExitKind::ArgumentsIndex));let (_, _, _, values) = &state.exit_frames[0][0];diff --git a/Libraries/LibJS/Rust/src/jit/code.rs b/Libraries/LibJS/Rust/src/jit/code.rsindex 9e320b9ccff..9fe11dcd099 100644--- a/Libraries/LibJS/Rust/src/jit/code.rs+++ b/Libraries/LibJS/Rust/src/jit/code.rs@@ -11,9 +11,10 @@ use core::ffi::c_void;use core::ops::ControlFlow;use std::collections::HashMap;+use libjs_jit::artifact::{Artifact, FrameView, Layout, Patch, SiteView};use libjs_jit::bytecode::{EnvironmentCoordinate, decode_instruction};+use libjs_jit::code::ExitKind;pub use libjs_jit::code::INLINED_CALL_SITE_BIT;-use libjs_jit::code::{ExitKind, Site};use libjs_runtime_macros::Trace;use super::entry_table::{JIT_ENTRY_SLOT_MASK, JitEntryTable, NO_JIT_ENTRY_SLOT};@@ -137,6 +138,15 @@ pub enum InlinedFunction {Builtin(Gc<NativeJavaScriptBackedFunction>),}+/// A word of the tables of installed code (see `libjs_jit::artifact`).+pub type TableWord = u32;++/// A site of installed code.+pub type Site<'a> = SiteView<'a, TableWord>;++/// The interpreter state of one frame at a site of installed code.+pub type FrameState<'a> = FrameView<'a, TableWord>;+/// Installed machine code for one executable, with what exits need to rebuild interpreter frames. While JIT code runs/// frames of its executable, it stays attached to the executable (in its slot of the JIT entry table, where/// `libjs_jit_exit()` finds it through the frame's executable), even once discarded.@@ -151,28 +161,16 @@ pub struct JitCode {interpreted_frame_count_to_forget_at: Cell<usize>,memory: ExecutableMemory,entry: JitEntry,- sites: Vec<Site>,+ /// The tables of the code that the runtime reads once the code is installed, which have `layout`.+ tables: Box<[TableWord]>,+ layout: Layout,/// The cells the code compares against or uses. The executable the code is attached to keeps them alive, so they/// keep their addresses for as long as the code may run.embedded_cells: Vec<Gc<CellHeader>>,snapshot_executables: Vec<SnapshotExecutable>,- /// Where a frame running in the interpreter at `pc` can continue in this code (see `osr_entry()`).- osr_entries: Vec<(u32, JitEntry)>,- /// The loop back edges from where a frame running in the interpreter reaches one of the `osr_entries` without- /// leaving the loop it is in.- osr_loop_back_edges: Vec<u32>,- /// The loop back edges in the loops around those of the `osr_entries`, from where a frame running in the- /// interpreter may reach one of them on a later iteration.- osr_outer_loop_back_edges: Vec<u32>,- /// The pcs of the `Catch` of the exception handlers that have no catch entry only because they never caught an- /// exception before the compile.- uncaught_handlers: Vec<u32>,/// Identifies the code among all code the VM installed, for the dependencies it registers (see/// `super::dependencies`).id: u64,- /// The bytes that invalidate the code at each offset of it: jumps to the exits of its `AssumeValid` nodes, which- /// 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,@@ -188,50 +186,43 @@ pub struct JitCode {}/// An object created for a frame running JIT code, standing for the object its code never allocated at `allocation`-/// (see `libjs_jit::code::VirtualObjectDescriptor`).+/// (see `libjs_jit::artifact::ObjectView`).struct MaterializedObject {frame: *const ExecutionContext,allocation: u32,object: Gc<Object>,}+/// The entry point at `offset` of the code in `memory`.+fn entry_at(memory: &ExecutableMemory, offset: u32) -> JitEntry {+ assert!((offset as usize) < memory.size());+ // SAFETY: The code has an entry point with the JitEntry calling convention at the offset.+ unsafe { core::mem::transmute::<*const u8, JitEntry>(memory.address().add(offset as usize)) }+}+impl JitCode {- #[allow(clippy::too_many_arguments)]+ /// Code in `memory` with its entry point at `entry_offset`, and with `tables`, which have `layout`.pub fn new(memory: ExecutableMemory,entry_offset: u32,- osr_entry_offsets: &[(u32, u32)],- osr_loop_back_edges: Vec<u32>,- sites: Vec<Site>,+ tables: Box<[TableWord]>,+ layout: Layout,embedded_cells: Vec<Gc<CellHeader>>,snapshot_executables: Vec<SnapshotExecutable>,_defer_gc: &DeferGc<'_>,) -> Self {- let entry_at = |offset: u32| {- assert!((offset as usize) < memory.size());- // SAFETY: The code has an entry point with the JitEntry calling convention at the offset.- unsafe { core::mem::transmute::<*const u8, JitEntry>(memory.address().add(offset as usize)) }- };- let entry = entry_at(entry_offset);- let osr_entries = osr_entry_offsets- .iter()- .map(|&(pc, offset)| (pc, entry_at(offset)))- .collect();+ let entry = entry_at(&memory, entry_offset);Self {exit_count: Cell::new(0),interpreted_frames: RefCell::new(HashMap::new()),interpreted_frame_count_to_forget_at: Cell::new(MIN_INTERPRETED_FRAME_COUNT_TO_FORGET_AT),memory,entry,- sites,+ tables,+ layout,embedded_cells,snapshot_executables,- osr_entries,- osr_loop_back_edges,- osr_outer_loop_back_edges: Vec::new(),- uncaught_handlers: Vec::new(),id: 0,- invalidation_patches: Vec::new(),invalidated: Cell::new(false),site_index_frame_offset: 0,register_dump_frame_offset: 0,@@ -239,6 +230,10 @@ impl JitCode {}}+ fn artifact(&self) -> Artifact<'_, TableWord> {+ Artifact::new(&self.tables, &self.layout)+ }+/// Gives the code where its frames keep the index of a site and the register dump the runtime reads.pub fn set_frame_offsets(&mut self, site_index_frame_offset: i32, register_dump_frame_offset: i32) {self.site_index_frame_offset = site_index_frame_offset;@@ -289,25 +284,15 @@ impl JitCode {.retain(|materialized| materialized.frame != frame);}- /// Gives the code its id among all code the VM installed, and the bytes that invalidate it.- pub fn set_invalidation(&mut self, id: u64, invalidation_patches: Vec<(u32, Vec<u8>)>) {+ /// Gives the code its id among all code the VM installed.+ pub fn set_id(&mut self, id: u64) {self.id = id;- self.invalidation_patches = invalidation_patches;- }-- /// Gives the code the loop back edges in the loops around those of its on-stack replacement entries.- pub fn set_osr_outer_loop_back_edges(&mut self, osr_outer_loop_back_edges: Vec<u32>) {- self.osr_outer_loop_back_edges = osr_outer_loop_back_edges;- }-- pub fn set_uncaught_handlers(&mut self, uncaught_handlers: Vec<u32>) {- self.uncaught_handlers = uncaught_handlers;}/// Whether the handler whose `Catch` is at `pc` has no catch entry only because it never caught an exception/// before the compile, so that a compile now would give it one.pub fn compiled_before_handler_caught(&self, pc: u32) -> bool {- self.uncaught_handlers.contains(&pc)+ self.artifact().uncaught_handlers().contains(pc)}pub fn id(&self) -> u64 {@@ -325,7 +310,9 @@ impl JitCode {if self.invalidated.replace(true) {return;}- self.memory.patch(&self.invalidation_patches);+ // NB: The patches are jumps to the exits of the `AssumeValid` nodes of the code, which are no-ops until then.+ let patches = self.artifact().invalidation_patches().collect::<Vec<Patch>>();+ self.memory.patch(&patches);}pub fn entry(&self) -> JitEntry {@@ -336,31 +323,25 @@ impl JitCode {/// loop back edge, the resume entry at a continuation of a generator's suspension, or the catch entry after the/// `Catch` of an exception handler.pub fn osr_entry(&self, pc: u32) -> Option<JitEntry> {- self.osr_entries- .iter()- .find(|(entry_pc, _)| *entry_pc == pc)- .map(|(_, entry)| *entry)+ self.artifact()+ .osr_entry(pc)+ .map(|offset| entry_at(&self.memory, offset))}/// Whether a frame running in the interpreter at the loop back edge `pc` reaches an on-stack replacement entry/// without leaving the loop it is in.pub fn reaches_osr_entry_from(&self, pc: u32) -> bool {- self.osr_loop_back_edges.contains(&pc)+ self.artifact().osr_loop_back_edges().contains(pc)}/// Whether a frame running in the interpreter at the loop back edge `pc` may reach an on-stack replacement entry/// on a later iteration of a loop it is in.pub fn may_reach_osr_entry_from(&self, pc: u32) -> bool {- self.osr_outer_loop_back_edges.contains(&pc)- }-- pub fn site(&self, index: u32) -> &Site {- &self.sites[index as usize]+ self.artifact().osr_outer_loop_back_edges().contains(pc)}- /// Takes the sites of code that died, so that they can be dropped elsewhere.- pub fn take_sites(&mut self) -> Vec<Site> {- core::mem::take(&mut self.sites)+ pub fn site(&self, index: u32) -> Site<'_> {+ self.artifact().site(index)}pub fn snapshot_executable(&self, index: u32) -> &SnapshotExecutable {@@ -559,18 +540,13 @@ impl Executable {let Some(table) = vm.jit.entry_table.as_ref() else {return;};- let Some(mut code) = table.free(+ let Some(code) = table.free(self.head.jit_entry_slot.get(),core::ptr::from_ref(&self.head) as u64,sweep,) else {return;};- // OPTIMIZATION: The compile threads allocated the sites, so one of them frees them, outside the collection- // this runs in.- if let Some(queue) = vm.jit.started_compile_queue() {- queue.drop_sites(code.take_sites());- }drop(code);}diff --git a/Libraries/LibJS/Rust/src/jit/compile_queue.rs b/Libraries/LibJS/Rust/src/jit/compile_queue.rsindex d78f5e9dcaa..1fcd19de303 100644--- a/Libraries/LibJS/Rust/src/jit/compile_queue.rs+++ b/Libraries/LibJS/Rust/src/jit/compile_queue.rs@@ -14,7 +14,7 @@ use std::sync::{Arc, OnceLock};use std::time::Duration;use libjs_jit::CompileFailure;-use libjs_jit::code::{CompiledCode, Site};+use libjs_jit::code::CompiledCode;use libjs_jit::compile_pool::{CompilePool, CompilePoolClient};use libjs_jit::scratch::Scratch;use libjs_jit::snapshot::Snapshot;@@ -92,12 +92,6 @@ impl CompileQueue {}));}- /// Has a compile thread drop the sites of code that died. The compile threads allocated them, so they free them- /// faster than the thread that collects the code, and outside its collection. This outlives the VM.- pub fn drop_sites(&self, sites: Vec<Site>) {- self.client.pool().run_unowned(Box::new(move || drop(sites)));- }-/// The results of the jobs that finished since the last call, waiting for one to finish if none has. The queue must/// have a job.pub fn wait_for_finished(&self) -> Vec<(u64, CompileResult)> {diff --git a/Libraries/LibJS/Rust/src/jit/entry_exit.rs b/Libraries/LibJS/Rust/src/jit/entry_exit.rsindex 554ba48b8d8..5629cd96d5b 100644--- a/Libraries/LibJS/Rust/src/jit/entry_exit.rs+++ b/Libraries/LibJS/Rust/src/jit/entry_exit.rs@@ -236,7 +236,7 @@ pub unsafe extern "C" fn libjs_jit_exit(// NB: The frame's executable keeps the code attached while JIT code runs the frame, also after it was discarded.let executable = executable_of(frame_of(root));let code = executable.jit_code(vm).expect("the code is attached");- match code.site(site).kind {+ match code.site(site).kind() {SiteKind::Exit(_) => translate::exit(vm, root, code, site, dump),SiteKind::Leave => translate::leave(vm, root, code, site, dump),SiteKind::Publish => translate::publish(vm, root, code, site, dump),@@ -297,8 +297,8 @@ pub unsafe extern "C" fn libjs_jit_finish_inlined_direct_call(.jit_code(vm_ref).expect("the code is attached").site(site)- .frames[0]- .pc;+ .frame(0)+ .pc();// SAFETY: The innermost frame of the inlined calls is the call's frame now.unsafe { super::calls::libjs_jit_finish_direct_call(vm, innermost.as_ptr(), pc, status) }}diff --git a/Libraries/LibJS/Rust/src/jit/executable_memory.rs b/Libraries/LibJS/Rust/src/jit/executable_memory.rsindex 21393f6e261..eacbec8ddf8 100644--- a/Libraries/LibJS/Rust/src/jit/executable_memory.rs+++ b/Libraries/LibJS/Rust/src/jit/executable_memory.rs@@ -19,6 +19,8 @@use core::cell::RefCell;use std::rc::Rc;+use libjs_jit::artifact::Patch;+#[cfg(windows)]use ak::windows_code_memory;@@ -484,19 +486,19 @@ impl ExecutableMemory {self.address}- /// Overwrites the code at each offset with the bytes that go there, which the code is not running at the time.- pub fn patch(&self, patches: &[(u32, Vec<u8>)]) {+ /// Overwrites the code at the offset of each patch with its bytes, which the code is not running at the time.+ pub fn patch(&self, patches: &[Patch]) {if patches.is_empty() {return;}let writes: Vec<CodeWrite<'_>> = patches.iter()- .map(|(offset, bytes)| {- assert!(*offset as usize + bytes.len() <= self.size);+ .map(|patch| {+ assert!(patch.offset as usize + patch.bytes().len() <= self.size);CodeWrite {// NB: The offset is within the memory, as asserted.- destination: self.address.wrapping_add(*offset as usize),- code: bytes,+ destination: self.address.wrapping_add(patch.offset as usize),+ code: patch.bytes(),}}).collect();diff --git a/Libraries/LibJS/Rust/src/jit/tier_up.rs b/Libraries/LibJS/Rust/src/jit/tier_up.rsindex 3c1b23781e8..0a1437d40e9 100644--- a/Libraries/LibJS/Rust/src/jit/tier_up.rs+++ b/Libraries/LibJS/Rust/src/jit/tier_up.rs@@ -369,21 +369,14 @@ fn install(let mut code = JitCode::new(memory,compiled.entry_offset,- &artifact.osr_entries().collect::<Vec<_>>(),- artifact.osr_loop_back_edges().iter().collect(),- compiled.sites(),+ compiled.words[..compiled.layout.kept_len()].into(),+ compiled.layout,embedded_cells,snapshot,defer_gc,);- let invalidation_patches = artifact- .invalidation_patches()- .map(|patch| (patch.offset, patch.bytes().to_vec()))- .collect();- code.set_invalidation(id, invalidation_patches);+ code.set_id(id);code.set_frame_offsets(compiled.site_index_frame_offset, compiled.register_dump_frame_offset);- code.set_osr_outer_loop_back_edges(artifact.osr_outer_loop_back_edges().iter().collect());- code.set_uncaught_handlers(artifact.uncaught_handlers().iter().collect());let dependencies = artifact.dependencies().collect::<Vec<_>>();vm.jit.dependents.register(vm, executable, id, &dependencies);// NB: A callee's tier-up check may install the code while its caller still runs in the interpreter, possiblydiff --git a/Libraries/LibJS/Rust/src/jit/translate.rs b/Libraries/LibJS/Rust/src/jit/translate.rsindex e8358fa0192..c15d69c5114 100644--- a/Libraries/LibJS/Rust/src/jit/translate.rs+++ b/Libraries/LibJS/Rust/src/jit/translate.rs@@ -7,7 +7,7 @@//! The translator from the state of compiled code at one of its sites to the interpreter's state.//!//! A site is a point of compiled code with a chain of frame states, innermost first (see-//! `libjs_jit::code::Site`): an exit, a leave (a slow path that did not continue in compiled code), a slow path or+//! `libjs_jit::artifact::SiteView`): an exit, a leave (a slow path that did not continue in compiled code), a slow path or//! call in an inlined callee that runs in the frames of the inlined calls it is in, or a call in an inlined callee that//! runs without them. The outermost frame state is the compiled function's own frame; the others are frames of inlined//! calls, which exist only as values of compiled code until the translator writes them.@@ -24,14 +24,13 @@ use core::ptr::NonNull;use std::collections::HashMap;use libjs_abi::register;-use libjs_jit::code::{- CALLEE_SLOT, FrameState, Repr, ResumeMode, Site, SiteKind, ValueLocation, VirtualObjectDescriptorKind,-};+use libjs_jit::code::{CALLEE_SLOT, Repr, ResumeMode, SiteKind, ValueLocation, VirtualObjectDescriptorKind};use libjs_runtime_macros::Trace;use super::allocation::clone_function;use super::code::{- CompileState, EXIT_COUNT_BEFORE_DISCARD, FRUITLESS_LOOP_CHECKS_AFTER_EXIT, InlinedFunction, JitCode,+ CompileState, EXIT_COUNT_BEFORE_DISCARD, FRUITLESS_LOOP_CHECKS_AFTER_EXIT, FrameState, InlinedFunction, JitCode,+ Site,};use super::{executable_of, frame_of, frames_above};use crate::bytecode::executable::Executable;@@ -173,7 +172,7 @@ struct SiteValues<'a> {vm: &'a Vm,code: &'a JitCode,root: NonNull<ExecutionContext>,- site: &'a Site,+ site: Site<'a>,dump: &'a RegisterDump,created: Deferred<'a, HashMap<u32, Gc<Object>>>,/// Whether the objects created are remembered for the frame, for a frame that continues in compiled code until it@@ -189,7 +188,7 @@ impl<'a> SiteValues<'a> {vm: &'a Vm,code: &'a JitCode,root: NonNull<ExecutionContext>,- site: &'a Site,+ site: Site<'a>,dump: &'a RegisterDump,defer_gc: &'a DeferGc<'_>,) -> Self {@@ -212,16 +211,16 @@ impl<'a> SiteValues<'a> {if let Some(object) = self.created.get(&index) {return Value::from_object(*object);}- let description = &self.site.objects[index as usize];+ let description = self.site.object(index);// 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.as_ptr(), description.allocation)+ .materialized_object(self.root.as_ptr(), description.allocation()){self.created.insert(index, object);return Value::from_object(object);}- let shape = match description.kind {+ let shape = match description.kind() {VirtualObjectDescriptorKind::Object { shape } => shape,VirtualObjectDescriptorKind::Closure { sample } => {// SAFETY: The code embeds the sample, which keeps it alive.@@ -229,14 +228,14 @@ impl<'a> SiteValues<'a> {let closure = clone_function(self.vm,sample,- read_cell_address(description.properties[0], self.dump),- read_cell_address(description.properties[1], self.dump),+ read_cell_address(description.property(0).expect("a closure has environments"), self.dump),+ read_cell_address(description.property(1).expect("a closure has environments"), self.dump),).upcast::<Object>();self.created.insert(index, closure);if self.remember {self.code- .remember_materialized_object(self.root.as_ptr(), description.allocation, closure);+ .remember_materialized_object(self.root.as_ptr(), description.allocation(), closure);}return Value::from_object(closure);}@@ -248,12 +247,12 @@ impl<'a> SiteValues<'a> {self.created.insert(index, object);if self.remember {self.code- .remember_materialized_object(self.root.as_ptr(), description.allocation, object);+ .remember_materialized_object(self.root.as_ptr(), description.allocation(), object);}let property_count = shape.property_count();for index in 0..property_count {- let value = match description.properties.get(index as usize) {- Some(location) => self.value(*location),+ let value = match description.property(index as usize) {+ Some(location) => self.value(location),None => Value::UNDEFINED,};object.initialize_direct(index, value);@@ -266,9 +265,11 @@ impl<'a> SiteValues<'a> {/// `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 {+ 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) => {+ (Some(frame_pointer), ValueLocation::VirtualObject(_))+ if frame_state.legacy_arguments().contains(&slot) =>+ {deferred_argument_marker(frame_pointer)}_ => self.value(location),@@ -277,18 +278,14 @@ impl<'a> SiteValues<'a> {/// 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 {- let closure = frame_state- .values- .iter()- .find(|(slot, _)| *slot == CALLEE_SLOT)- .map(|(_, location)| self.value(*location));+ fn function(&mut self, code: &JitCode, frame_state: FrameState<'_>) -> InlinedFunction {+ let closure = frame_state.callee().map(|location| self.value(location));match closure {Some(closure) => InlinedFunction::Ecmascript(as_ecmascript_function_object(closure.as_object()).expect("an inlined closure is a function"),),None => code- .snapshot_executable(frame_state.executable)+ .snapshot_executable(frame_state.executable()).function.expect("an inlined executable has a function"),}@@ -318,13 +315,8 @@ fn arguments_base_of(executable: &Executable) -> 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)+fn argument_location(frame_state: FrameState<'_>, executable: &Executable, argument: u32) -> Option<ValueLocation> {+ frame_state.value(arguments_base_of(executable) + argument)}/// Whether `code` is the code `compiled_executable` has installed. What discarded code learns counts for no later@@ -386,14 +378,14 @@ fn call_instruction_shape(executable: &Executable, pc: u32) -> (u32, u32, CallKi/// The linkage of the frame of `executable` at the call of `frame_state`: its frame continues after the call (or/// CallConstruct, or the GetById of a getter or the PutById of a setter) instruction once the callee returns into its/// destination.-fn call_linkage(executable: &Executable, frame_state: &FrameState) -> CallLinkage {- let ResumeMode::ResumeAfter { dst } = frame_state.mode else {+fn call_linkage(executable: &Executable, frame_state: FrameState<'_>) -> CallLinkage {+ let ResumeMode::ResumeAfter { dst } = frame_state.mode() else {unreachable!("frames at calls resume after them");};- let pc = frame_state.pc;+ let pc = frame_state.pc();let (argument_count, length, kind) = call_instruction_shape(executable, pc);CallLinkage {- passed_argument_count: frame_state.passed_argument_count.unwrap_or(argument_count),+ passed_argument_count: frame_state.passed_argument_count().unwrap_or(argument_count),return_pc: pc + length,dst,is_construct: kind != CallKind::Call,@@ -539,13 +531,13 @@ enum Destination {fn write_frame_state(vm: &Vm,frame: &ExecutionContext,- frame_state: &FrameState,+ frame_state: FrameState<'_>,values: &mut SiteValues<'_>,destination: Destination,) {// NB: The frame holds the slots listed as in it, and the destination of the instruction it resumes after is never// cleared.- let resume_destination = match frame_state.mode {+ let resume_destination = match frame_state.mode() {ResumeMode::ResumeAfter { dst } => Some(dst),ResumeMode::ResumeAt => None,};@@ -561,8 +553,8 @@ fn write_frame_state(// NB: Frame states list every live slot, so the others are dead. Clearing them keeps the interpreter from seeing// values the compiled code no longer maintains, and drops references to them. Both lists are in slot order.let registers_and_locals_count = executable_of(frame).registers_and_locals_count();- let mut held = frame_state.in_frame.iter().copied().peekable();- let mut written = frame_state.values.iter().map(|(slot, _)| *slot).peekable();+ let mut held = frame_state.in_frame().iter().peekable();+ let mut written = frame_state.slots().iter().peekable();for index in register::RESERVED_REGISTER_COUNT..registers_and_locals_count {let is_held = sorted_slots_contain(&mut held, index);let is_written = sorted_slots_contain(&mut written, index);@@ -575,22 +567,22 @@ fn write_frame_state(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 {+ 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 {+ if slot == CALLEE_SLOT || Some(slot) == kept {continue;}if let ValueLocation::ArgumentsObject { mapped } = location {- arguments_object_slots.push((*slot, *mapped));+ arguments_object_slots.push((slot, mapped));continue;}- let value = if *slot >= arguments_base {- values.argument_value(*slot, *location, frame_state)+ let value = if slot >= arguments_base {+ values.argument_value(slot, location, frame_state)} else {- values.value(*location)+ values.value(location)};has_deferred_arguments |= deferred_argument_frame_pointer(value).is_some();- slots[*slot as usize].set(value);+ slots[slot as usize].set(value);}// 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.@@ -629,14 +621,14 @@ fn push_site_frames(innermost_destination: Destination,) -> NonNull<ExecutionContext> {let site = values.site;- let frame_states = &site.frames;- assert!(!frame_states.is_empty());+ let frame_count = site.frame_count();let mut frame = root;let mut linkage = None;- for (index, frame_state) in frame_states.iter().enumerate().rev() {- let is_root = index + 1 == frame_states.len();+ for index in (0..frame_count).rev() {+ let frame_state = site.frame(index);+ let is_root = index + 1 == frame_count;if is_root {- assert_eq!(frame_state.executable, 0);+ assert_eq!(frame_state.executable(), 0);} else {let function = values.function(code, frame_state);frame = push_frame(@@ -655,7 +647,7 @@ fn push_site_frames(Destination::WriteOldValue};write_frame_state(vm, frame_ref, frame_state, values, destination);- frame_ref.program_counter.set(frame_state.pc);+ frame_ref.program_counter.set(frame_state.pc());}if !is_root {let this_value = frame_ref.register(register::THIS_VALUE).get();@@ -675,7 +667,7 @@ fn push_site_frames(/// The interpreter then continues in the innermost frame.pub(super) fn exit(vm: &Vm, root: NonNull<ExecutionContext>, code: &JitCode, index: u32, dump: &RegisterDump) {let site = code.site(index);- let SiteKind::Exit(kind) = site.kind else {+ let SiteKind::Exit(kind) = site.kind() else {unreachable!("exits are sites of exits");};// NB: Exits the "stress-exits" option causes teach the executable nothing.@@ -707,13 +699,13 @@ pub(super) fn exit(vm: &Vm, root: NonNull<ExecutionContext>, code: &JitCode, indDestination::Keep,);code.forget_materialized_objects(root.as_ptr());- let frame_state = &site.frames[0];+ let frame_state = site.frame(0);let frame_ref = frame_of(innermost);let executable = executable_of(frame_ref);- if let ResumeMode::ResumeAfter { .. } = frame_state.mode {+ if let ResumeMode::ResumeAfter { .. } = frame_state.mode() {// NB: The call already stored its result in its destination slot.let bytecode = executable.bytecode();- let pc = frame_state.pc;+ let pc = frame_state.pc();let length = instruction_length_from_bytes(bytecode[pc as usize], bytecode, pc as usize).expect("the bytecode is valid") as u32;frame_ref.program_counter.set(pc + length);@@ -726,7 +718,7 @@ pub(super) fn exit(vm: &Vm, root: NonNull<ExecutionContext>, code: &JitCode, indeprintln!("JIT exit: {} pc {} {:?}{stress}, code {:p}/{}",super::describe_executable(&executable),- frame_state.pc,+ frame_state.pc(),kind,compiled_executable.as_ptr(),compiled_executable.jit_discard_count()@@ -735,7 +727,7 @@ pub(super) fn exit(vm: &Vm, root: NonNull<ExecutionContext>, code: &JitCode, indeprintln!("JIT exit: {} pc {} {:?}{stress}, inlined into {}, code {:p}/{}",super::describe_executable(&executable),- frame_state.pc,+ frame_state.pc(),kind,super::describe_executable(&compiled_executable),compiled_executable.as_ptr(),@@ -761,26 +753,26 @@ pub(super) fn exit(vm: &Vm, root: NonNull<ExecutionContext>, code: &JitCode, indframe = NonNull::new(frame_of(frame).caller_frame.get()).expect("materialized frames are linked to the root");}vm.jit.count_coverage(format_args!("exit.{kind:?}"));- if site.frames.len() > 1 {+ if site.frame_count() > 1 {vm.jit.count_coverage("exit.from-inlined-code");}// NB: Exits in inlined builtins count for the code they were inlined into only.// NB: Invalidated code was discarded, and its recompile sees that what it depended on no longer holds. An interrupt// speculated nothing, and nothing runs after it.- let snapshot_executable = code.snapshot_executable(frame_state.executable);+ let snapshot_executable = code.snapshot_executable(frame_state.executable());let learned = if matches!(kind,libjs_jit::code::ExitKind::Invalidated | libjs_jit::code::ExitKind::Interrupted) {false} else if matches!(snapshot_executable.function, Some(InlinedFunction::Builtin(_))) {- let index = compiled_executable.add_jit_builtin_exit_site((executable.as_ptr() as u64, frame_state.pc, kind));+ let index = compiled_executable.add_jit_builtin_exit_site((executable.as_ptr() as u64, frame_state.pc(), kind));index >= code.snapshot_executable(0).known_builtin_exit_sites} else {// NB: Sites in inlined callees are their executables', but the compiled code learns from them too.- let new_site = executable.add_jit_exit_site((frame_state.pc, kind)) >= snapshot_executable.known_exit_sites;+ let new_site = executable.add_jit_exit_site((frame_state.pc(), kind)) >= snapshot_executable.known_exit_sites;let learned_shapes = kind == libjs_jit::code::ExitKind::BadShape- && executable.note_jit_shape_exit(frame_state.pc, &snapshot_executable.property_cache_sizes);+ && executable.note_jit_shape_exit(frame_state.pc(), &snapshot_executable.property_cache_sizes);new_site || learned_shapes};if learned && is_installed_code(vm, &compiled_executable, code) {@@ -803,28 +795,28 @@ pub(super) fn exit(vm: &Vm, root: NonNull<ExecutionContext>, code: &JitCode, ind/// a handler of an inlined callee caught like an exit.pub(super) fn leave(vm: &Vm, root: NonNull<ExecutionContext>, code: &JitCode, index: u32, dump: &RegisterDump) {let site = code.site(index);- assert_eq!(site.kind, SiteKind::Leave);+ 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;- let pushed = frames.len().min(frame_states.len() - 1);+ let frame_count = site.frame_count();+ let pushed = frames.len().min(frame_count - 1);// 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, code, root, site, dump, &defer_gc);- let mut write = |frame: &ExecutionContext, frame_state: &FrameState| {- let expected = code.snapshot_executable(frame_state.executable).executable;+ let mut write = |frame: &ExecutionContext, frame_state: FrameState<'_>| {+ let expected = code.snapshot_executable(frame_state.executable()).executable;assert!(executable_of(frame) == expected);write_frame_state(vm, frame, frame_state, &mut values, Destination::WriteOldValue);};- write(frame_of(root), frame_states.last().expect("there is a frame state"));+ write(frame_of(root), site.frame(frame_count - 1));for index in 0..pushed {// NB: The slow path ran in the innermost frame, whose outputs its frame state lists as in the frame.let frame = frames[frames.len() - 1 - index];- write(frame_of(frame), &frame_states[frame_states.len() - 2 - index]);+ write(frame_of(frame), site.frame(frame_count - 2 - index));}code.forget_materialized_objects(root.as_ptr());@@ -851,21 +843,22 @@ pub(super) fn leave(vm: &Vm, root: NonNull<ExecutionContext>, code: &JitCode, in/// runs in the innermost one, which is the running frame.pub(super) fn publish(vm: &Vm, root: NonNull<ExecutionContext>, code: &JitCode, index: u32, dump: &RegisterDump) {let site = code.site(index);- assert_eq!(site.kind, SiteKind::Publish);+ assert_eq!(site.kind(), SiteKind::Publish);assert_eq!(vm.running_execution_context(), Some(root));- let frame_states = &site.frames;- assert!(frame_states.len() >= 2);+ let frame_count = site.frame_count();+ assert!(frame_count >= 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, code, root, site, dump, &defer_gc);// 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);+ let root_frame_state = site.frame(frame_count - 1);+ frame_of(root).program_counter.set(root_frame_state.pc());let mut linkage = call_linkage(&executable_of(frame_of(root)), root_frame_state);let mut caller = root;- for (index, frame_state) in frame_states.iter().enumerate().rev().skip(1) {+ for index in (0..frame_count - 1).rev() {+ let frame_state = site.frame(index);let function = values.function(code, frame_state);let frame = push_frame(vm, frame_of(caller), function, linkage, FrameSlots::Uninitialized);caller = frame;@@ -873,18 +866,18 @@ pub(super) fn publish(vm: &Vm, root: NonNull<ExecutionContext>, code: &JitCode,let executable = executable_of(frame_ref);let arguments_base = arguments_base_of(&executable);let slots = frame_ref.slots();- for (slot, location) in &frame_state.values {- if *slot == register::THIS_VALUE {- let this_value = values.value(*location);- slots[*slot as usize].set(this_value);+ for (slot, location) in frame_state.values() {+ if slot == register::THIS_VALUE {+ let this_value = values.value(location);+ slots[slot as usize].set(this_value);if this_value != Value::EMPTY {frame_ref.this_value.set(this_value);}- } else if *slot != CALLEE_SLOT && *slot >= arguments_base {- slots[*slot as usize].set(values.argument_value(*slot, *location, frame_state));+ } else if slot != CALLEE_SLOT && slot >= arguments_base {+ slots[slot as usize].set(values.argument_value(slot, location, frame_state));}}- frame_ref.program_counter.set(frame_state.pc);+ frame_ref.program_counter.set(frame_state.pc());if index != 0 {linkage = call_linkage(&executable, frame_state);}@@ -907,8 +900,8 @@ pub(super) fn materialize_call_site_frames(let compiled_executable = executable_of(frame_of(root));let code = compiled_executable.jit_code(vm).expect("the code is attached");let site = code.site(index);- assert_eq!(site.kind, SiteKind::Call);- assert!(site.frames.len() >= 2);+ assert_eq!(site.kind(), SiteKind::Call);+ assert!(site.frame_count() >= 2);let stack = vm.interpreter_stack();let running = vm.head.running_execution_context.get();@@ -919,7 +912,7 @@ pub(super) fn materialize_call_site_frames(callee.as_ptr().cast::<u8>()- .wrapping_sub(site.inlined_frame_bytes as usize),+ .wrapping_sub(site.inlined_frame_bytes() as usize),);}vm.head.running_execution_context.set(root.as_ptr());@@ -943,7 +936,7 @@ pub(super) fn materialize_call_site_frames(if let Some(callee) = callee {assert!(stack.top.get() <= callee.as_ptr().cast());- let linkage = call_linkage(&executable_of(frame_of(innermost)), &site.frames[0]);+ let linkage = call_linkage(&executable_of(frame_of(innermost)), site.frame(0));let callee_ref = frame_of(callee);callee_ref.caller_frame.set(innermost.as_ptr());callee_ref.caller_return_pc.set(linkage.return_pc);@@ -995,24 +988,21 @@ pub fn call_site_frames<'vm>(.jit_code(vm).expect("a frame at a call site in an inlined callee runs its JIT code");let site = code.site(index);- assert_eq!(site.kind, SiteKind::Call);+ assert_eq!(site.kind(), SiteKind::Call);let dump = RegisterDump::of_stack_slots(frame_pointer);- let (_, inlined) = site.frames.split_last().expect("a call site has frames");- let frames = MarkedVec::with_capacity(vm, inlined.len());- for (index, frame_state) in inlined.iter().enumerate() {- let snapshot_executable = code.snapshot_executable(frame_state.executable);+ // NB: The last frame is the compiled function's.+ let inlined_count = site.frame_count() - 1;+ let frames = MarkedVec::with_capacity(vm, inlined_count);+ for (index, frame_state) in site.frames().take(inlined_count).enumerate() {+ let snapshot_executable = code.snapshot_executable(frame_state.executable());// NB: Frames of inlined closures run the closure that was called. Walks create no objects, and the closure// never is one the code did not create.- let closure = frame_state- .values- .iter()- .find(|(slot, _)| *slot == CALLEE_SLOT)- .and_then(|(_, location)| match location {- ValueLocation::Stack(..) | ValueLocation::Constant(_) | ValueLocation::Frame(_) => {- Some(read_location(*location, &dump, NonNull::from(frame)))- }- _ => None,- });+ let closure = frame_state.callee().and_then(|location| match location {+ ValueLocation::Stack(..) | ValueLocation::Constant(_) | ValueLocation::Frame(_) => {+ Some(read_location(location, &dump, NonNull::from(frame)))+ }+ _ => None,+ });let function = match closure {Some(closure) => as_ecmascript_function_object(closure.as_object()).expect("an inlined closure is a function")@@ -1028,7 +1018,7 @@ pub fn call_site_frames<'vm>(frames.push(CallSiteFrame {function,executable: snapshot_executable.executable,- program_counter: frame_state.pc,+ program_counter: frame_state.pc(),frame_state: index,});}@@ -1052,11 +1042,11 @@ pub fn call_site_frame_arguments<'d>(.jit_code(vm).expect("a frame at a call site in an inlined callee runs its JIT code");let site = code.site(index);- let caller_frame_state = &site.frames[frame_state + 1];- let caller_executable = code.snapshot_executable(caller_frame_state.executable).executable;+ let caller_frame_state = site.frame(frame_state + 1);+ let caller_executable = code.snapshot_executable(caller_frame_state.executable()).executable;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 frame_state = site.frame(frame_state);+ let executable = code.snapshot_executable(frame_state.executable()).executable;// 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, code, NonNull::from(frame), site, &dump, defer_gc);@@ -1116,9 +1106,9 @@ fn deferred_argument(vm: &Vm, frame: &ExecutionContext, argument: u32, frame_poi.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 frame_state = site.frame(site.frame_count() - 2 - depth);let executable = executable_of(frame);- assert!(code.snapshot_executable(frame_state.executable).executable == executable);+ 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(_)));@@ -1126,7 +1116,7 @@ fn deferred_argument(vm: &Vm, frame: &ExecutionContext, argument: u32, frame_poilet 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 {+ let dump = match site.kind() {SiteKind::Publish => RegisterDump::in_jit_frame(code, frame_pointer),_ => RegisterDump::of_stack_slots(frame_pointer),};@@ -1142,10 +1132,10 @@ fn deferred_argument(vm: &Vm, frame: &ExecutionContext, argument: u32, frame_poi/// 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);+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 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) {@@ -1156,7 +1146,7 @@ fn note_legacy_arguments_read(vm: &Vm, root: &ExecutionContext, code: &JitCode,"JIT invalidate: {}, legacy arguments of {} read at pc {}",super::describe_executable(&compiled_executable),super::describe_executable(&executable),- frame_state.pc+ frame_state.pc());}code.invalidate();