Skip to content

Truly independent web browser

LibJS/JIT: Write the tables of compiled code as one array of words

Andreas Kling7d9765bff537
diff --git a/Libraries/LibJS/JIT/Rust/Cargo.toml b/Libraries/LibJS/JIT/Rust/Cargo.toml
index e82136432f2..ff66d517c7d 100644
--- a/Libraries/LibJS/JIT/Rust/Cargo.toml
+++ b/Libraries/LibJS/JIT/Rust/Cargo.toml
@@ -8,6 +8,9 @@ crate-type = ["rlib"]
# After changing dependencies, regenerate the Flatpak sources:
# python3 Meta/CMake/flatpak/generate-cargo-sources.py
+[dependencies]
+ak = { path = "../../../../AK/Rust" }
+
[build-dependencies]
flapc = { path = "../../Flap" }
@@ -19,7 +22,6 @@ iced-x86 = { version = "1.22", default-features = false, features = ["decoder",
farm64 = { package = "fARM64", version = "0.0.2", features = ["alloc"] }
[dev-dependencies]
-ak = { path = "../../../../AK/Rust" }
farm64 = { package = "fARM64", version = "0.0.2", features = ["alloc"] }
iced-x86 = { version = "1.22", default-features = false, features = ["decoder", "intel", "std"] }
libc = "0.2"
diff --git a/Libraries/LibJS/JIT/Rust/src/artifact.rs b/Libraries/LibJS/JIT/Rust/src/artifact.rs
new file mode 100644
index 00000000000..b8fc9f621e7
--- /dev/null
+++ b/Libraries/LibJS/JIT/Rust/src/artifact.rs
@@ -0,0 +1,984 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The tables of compiled code: what the runtime reads to install the code, to enter it, and to translate its state
+//! into interpreter frames at its sites (see `code::SiteKind`).
+//!
+//! The tables are the sections of one array of 32-bit words, whose bounds a `Layout` holds. A record is a fixed
+//! number of words, and records refer to each other and to runs of words by index. So the array holds no pointer: a
+//! copy of it is the same tables, and the runtime reads them where they are, through the views of this module.
+//!
+//! A frame state of the graph becomes one frame record, however many sites have it and however many frame states
+//! have it as their parent. What two sites with the same frame state differ in is where the values are, so each site
+//! has a run of locations of its own: those of the values of its frames, innermost frame first and in slot order
+//! within a frame, then those of the properties of its objects.
+
+use core::cell::Cell;
+use core::ops::Range;
+
+use ak::Column;
+
+use crate::CompileFailure;
+use crate::code::CALLEE_SLOT;
+use crate::code::Dependency;
+use crate::code::ExitKind;
+use crate::code::Repr;
+use crate::code::ResumeMode;
+use crate::code::SiteKind;
+use crate::code::ValueLocation;
+use crate::code::VirtualObjectDescriptorKind;
+use crate::snapshot::CellId;
+
+/// A table of compiled code. Their order here is their order in the array.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Section {
+ /// A record per site, by site index.
+ Sites,
+ /// A record per frame state that a site has, directly or as the caller of another.
+ Frames,
+ /// The slots of the values of each frame, a sorted run per frame.
+ Slots,
+ /// The slots each frame holds already (see `FrameView::in_frame()`), a sorted run per frame.
+ InFrame,
+ /// A record per object that the code never allocated, a run per frame that is the innermost one of a site.
+ Objects,
+ /// Where the values are, a run per site.
+ Locations,
+ /// The 64-bit values that locations refer to, as two words each, low half first.
+ Wide,
+ /// The pcs of the on-stack replacement entries, sorted.
+ OsrPcs,
+ /// The code offset of each on-stack replacement entry, in the order of their pcs.
+ OsrOffsets,
+ /// See `CompiledCode::osr_loop_back_edges()`. Sorted.
+ OsrLoopBackEdges,
+ /// See `CompiledCode::osr_outer_loop_back_edges()`. Sorted.
+ OsrOuterLoopBackEdges,
+ /// See `ir::Graph::uncaught_handlers`. Sorted.
+ UncaughtHandlers,
+ /// A record per invalidation patch.
+ Patches,
+ /// The cells the code embeds, as two words each. Only the install reads this section and the next.
+ EmbeddedCells,
+ /// A record per dependency.
+ Dependencies,
+}
+
+const SECTION_COUNT: usize = Section::Dependencies as usize + 1;
+
+/// The sections the runtime reads after it installed the code are the first ones.
+const LAST_KEPT_SECTION: Section = Section::Patches;
+
+/// In place of an index, a slot or a count: there is none.
+const NONE: u32 = u32::MAX;
+
+const SITE_WORDS: usize = 4;
+/// The kind of the site in the low byte, and the kind of the exit of an exit site in the next one.
+const SITE_KIND: usize = 0;
+/// The record of the innermost frame.
+const SITE_FRAME: usize = 1;
+/// Where the run of locations of the site starts.
+const SITE_LOCATIONS: usize = 2;
+const SITE_INLINED_FRAME_BYTES: usize = 3;
+
+const SITE_KIND_EXIT: u32 = 0;
+const SITE_KIND_LEAVE: u32 = 1;
+const SITE_KIND_PUBLISH: u32 = 2;
+const SITE_KIND_CALL: u32 = 3;
+
+const FRAME_WORDS: usize = 14;
+const FRAME_EXECUTABLE: usize = 0;
+const FRAME_PC: usize = 1;
+/// The destination of a frame that resumes after its instruction.
+const FRAME_RESUME_DESTINATION: usize = 2;
+const FRAME_PASSED_ARGUMENT_COUNT: usize = 3;
+const FRAME_LEGACY_ARGUMENTS_START: usize = 4;
+const FRAME_LEGACY_ARGUMENTS_END: usize = 5;
+/// The record of the frame of the caller, or `NONE` for the frame of the compiled function.
+const FRAME_PARENT: usize = 6;
+/// Whether the frame resumes after its instruction in the low bit, and how many callers the frame has in the rest.
+const FRAME_DEPTH: usize = 7;
+const FRAME_VALUE_COUNT: usize = 8;
+const FRAME_SLOTS: usize = 9;
+const FRAME_IN_FRAME: usize = 10;
+const FRAME_IN_FRAME_COUNT: usize = 11;
+/// The objects of the sites the frame is the innermost one of, or `NONE` while nothing asked for them.
+const FRAME_OBJECTS: usize = 12;
+const FRAME_OBJECT_COUNT: usize = 13;
+
+const OBJECT_WORDS: usize = 6;
+const OBJECT_KIND: usize = 0;
+const OBJECT_ALLOCATION: usize = 1;
+/// The shape or the sample, as two words.
+const OBJECT_CELL: usize = 2;
+/// Where the locations of the properties start in the run of a site.
+const OBJECT_PROPERTIES: usize = 4;
+const OBJECT_PROPERTY_COUNT: usize = 5;
+
+const OBJECT_KIND_OBJECT: u32 = 0;
+const OBJECT_KIND_CLOSURE: u32 = 1;
+
+const WIDE_WORDS: usize = 2;
+
+const PATCH_WORDS: usize = 4;
+const PATCH_OFFSET: usize = 0;
+const PATCH_LENGTH: usize = 1;
+const PATCH_BYTES: usize = 2;
+
+/// The most bytes an invalidation patch has.
+pub const MAX_PATCH_LENGTH: usize = 8;
+
+const CELL_WORDS: usize = 2;
+
+const DEPENDENCY_WORDS: usize = 5;
+
+// A location is one word: its kind in the low three bits, the representation of the value in the next three, and a
+// payload in the rest.
+const LOCATION_KIND_MASK: u32 = 0b111;
+const LOCATION_REPR_SHIFT: u32 = 3;
+const LOCATION_REPR_MASK: u32 = 0b111;
+const LOCATION_PAYLOAD_SHIFT: u32 = 6;
+const LOCATION_PAYLOAD_LIMIT: u32 = 1 << (u32::BITS - LOCATION_PAYLOAD_SHIFT);
+
+/// The payload is the register.
+const LOCATION_REGISTER: u32 = 0;
+/// The payload is the offset, which has a sign.
+const LOCATION_STACK: u32 = 1;
+/// The payload is the slot.
+const LOCATION_FRAME: u32 = 2;
+/// The payload is the index of the constant among the 64-bit values.
+const LOCATION_CONSTANT: u32 = 3;
+/// The payload is whether the object is mapped.
+const LOCATION_ARGUMENTS_OBJECT: u32 = 4;
+/// The payload is the index of the object among those of the site.
+const LOCATION_VIRTUAL_OBJECT: u32 = 5;
+
+/// Where each table of compiled code is in its array of words.
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct Layout {
+ /// Where each section ends, which is where the next one starts.
+ ends: [u32; SECTION_COUNT],
+}
+
+impl Layout {
+ fn range(&self, section: Section) -> Range<usize> {
+ let index = section as usize;
+ let start = if index == 0 { 0 } else { self.ends[index - 1] };
+ start as usize..self.ends[index] as usize
+ }
+
+ /// How many words the tables have that the runtime reads after it installed the code. They are the first ones.
+ pub fn kept_len(&self) -> usize {
+ self.ends[LAST_KEPT_SECTION as usize] as usize
+ }
+}
+
+/// A word of the tables, wherever they are.
+pub trait Word {
+ fn word(&self) -> u32;
+}
+
+impl Word for u32 {
+ fn word(&self) -> u32 {
+ *self
+ }
+}
+
+/// A word of tables in memory that code with other tables there shares.
+impl Word for Cell<u32> {
+ fn word(&self) -> u32 {
+ self.get()
+ }
+}
+
+fn halves(value: u64) -> [u32; 2] {
+ [value as u32, (value >> 32) as u32]
+}
+
+fn from_halves<W: Word>(words: &[W]) -> u64 {
+ u64::from(words[0].word()) | u64::from(words[1].word()) << 32
+}
+
+fn count_of(len: usize) -> u32 {
+ u32::try_from(len).expect("the tables of compiled code have fewer than 4 Gi words")
+}
+
+/// A frame for `ArtifactWriter::add_frame()`.
+pub struct Frame {
+ /// See `FrameView::executable()` and the functions after it.
+ pub executable: u32,
+ pub pc: u32,
+ pub mode: ResumeMode,
+ pub passed_argument_count: Option<u32>,
+ pub legacy_arguments: Range<u32>,
+ /// The record of the frame of the caller, for a frame of an inlined call.
+ pub parent: Option<u32>,
+}
+
+/// What `ArtifactWriter::finish()` adds to the tables: what the compiler has as a whole when the code is complete.
+#[derive(Default)]
+pub struct Tail<'a> {
+ /// See `Artifact::osr_entries()`. In pc order.
+ pub osr_entries: &'a [(u32, u32)],
+ pub osr_loop_back_edges: &'a [u32],
+ pub osr_outer_loop_back_edges: &'a [u32],
+ pub uncaught_handlers: &'a [u32],
+ /// See `Artifact::invalidation_patches()`.
+ pub invalidation_patches: &'a [(u32, Vec<u8>)],
+ pub embedded_cells: &'a [CellId],
+ pub dependencies: &'a [Dependency],
+}
+
+/// Writes the tables of compiled code. The memory it takes for one compile serves the next.
+pub struct ArtifactWriter {
+ sites: Column<u32>,
+ frames: Column<u32>,
+ slots: Column<u32>,
+ in_frame: Column<u32>,
+ objects: Column<u32>,
+ locations: Column<u32>,
+ wide: Column<u32>,
+ /// The tables as one array, once the code is complete.
+ words: Column<u32>,
+}
+
+impl Default for ArtifactWriter {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl ArtifactWriter {
+ // NB: These are how much of each the tables of one compile can have. They are far above what the code of real
+ // functions needs, and a compile that needs more fails.
+ const MAX_SITES: usize = 1 << 20;
+ const MAX_FRAMES: usize = 1 << 20;
+ const MAX_SLOTS: usize = 1 << 22;
+ const MAX_OBJECTS: usize = 1 << 18;
+ const MAX_LOCATIONS: usize = 1 << 24;
+ const MAX_WIDE_VALUES: usize = 1 << 20;
+ const MAX_WORDS: usize = 1 << 25;
+
+ pub fn new() -> Self {
+ Self {
+ sites: Column::new(Self::MAX_SITES * SITE_WORDS, c"JIT sites"),
+ frames: Column::new(Self::MAX_FRAMES * FRAME_WORDS, c"JIT frames"),
+ slots: Column::new(Self::MAX_SLOTS, c"JIT frame slots"),
+ in_frame: Column::new(Self::MAX_SLOTS, c"JIT slots in frame"),
+ objects: Column::new(Self::MAX_OBJECTS * OBJECT_WORDS, c"JIT objects"),
+ locations: Column::new(Self::MAX_LOCATIONS, c"JIT locations"),
+ wide: Column::new(Self::MAX_WIDE_VALUES * WIDE_WORDS, c"JIT wide values"),
+ words: Column::new(Self::MAX_WORDS, c"JIT tables"),
+ }
+ }
+
+ /// Starts the tables of another compile.
+ pub fn clear(&mut self) {
+ self.sites.clear();
+ self.frames.clear();
+ self.slots.clear();
+ self.in_frame.clear();
+ self.objects.clear();
+ self.locations.clear();
+ self.wide.clear();
+ self.words.clear();
+ }
+
+ /// Gives the memory of the writer back to the system. It takes memory again when it writes.
+ pub fn release_memory(&mut self) {
+ self.clear();
+ self.sites.trim(0);
+ self.frames.trim(0);
+ self.slots.trim(0);
+ self.in_frame.trim(0);
+ self.objects.trim(0);
+ self.locations.trim(0);
+ self.wide.trim(0);
+ self.words.trim(0);
+ }
+
+ /// Adds a frame with values in `slots` and with `in_frame` (see `FrameView::in_frame()`), both in any order.
+ /// Returns its record.
+ pub fn add_frame(
+ &mut self,
+ frame: &Frame,
+ slots: impl Iterator<Item = u32>,
+ in_frame: &[u32],
+ ) -> Result<u32, CompileFailure> {
+ let slots_start = self.slots.len();
+ for slot in slots {
+ self.slots.try_push(slot)?;
+ }
+ self.slots[slots_start..].sort_unstable();
+ let in_frame_start = self.in_frame.len();
+ self.in_frame.try_extend_from_slice(in_frame)?;
+ self.in_frame[in_frame_start..].sort_unstable();
+ let (resumes_after, resume_destination) = match frame.mode {
+ ResumeMode::ResumeAt => (0, 0),
+ ResumeMode::ResumeAfter { dst } => (1, dst),
+ };
+ let depth = match frame.parent {
+ Some(parent) => (self.frames[parent as usize * FRAME_WORDS + FRAME_DEPTH] >> 1) + 1,
+ None => 0,
+ };
+ // NB: No frame has that many arguments, so the word that stands for none is free.
+ if frame.passed_argument_count == Some(NONE) || depth > u32::MAX >> 1 {
+ return Err(CompileFailure::TooLarge);
+ }
+ let record = self.frames.len() / FRAME_WORDS;
+ let mut words = [0; FRAME_WORDS];
+ words[FRAME_EXECUTABLE] = frame.executable;
+ words[FRAME_PC] = frame.pc;
+ words[FRAME_RESUME_DESTINATION] = resume_destination;
+ words[FRAME_PASSED_ARGUMENT_COUNT] = frame.passed_argument_count.unwrap_or(NONE);
+ words[FRAME_LEGACY_ARGUMENTS_START] = frame.legacy_arguments.start;
+ words[FRAME_LEGACY_ARGUMENTS_END] = frame.legacy_arguments.end;
+ words[FRAME_PARENT] = frame.parent.unwrap_or(NONE);
+ words[FRAME_DEPTH] = depth << 1 | resumes_after;
+ words[FRAME_VALUE_COUNT] = count_of(self.slots.len() - slots_start);
+ words[FRAME_SLOTS] = count_of(slots_start);
+ words[FRAME_IN_FRAME] = count_of(in_frame_start);
+ words[FRAME_IN_FRAME_COUNT] = count_of(in_frame.len());
+ words[FRAME_OBJECTS] = NONE;
+ self.frames.try_extend_from_slice(&words)?;
+ Ok(count_of(record))
+ }
+
+ /// Whether `frame` has the objects of the sites it is the innermost frame of (see `set_frame_objects()`).
+ pub fn frame_has_objects(&self, frame: u32) -> bool {
+ self.frames[frame as usize * FRAME_WORDS + FRAME_OBJECTS] != NONE
+ }
+
+ /// Gives `frame` the objects of the sites it is the innermost frame of, as the kind, the allocation and the
+ /// number of properties of each. The locations of their properties follow those of the frames' values in the run
+ /// of each site, in the same order.
+ pub fn set_frame_objects(
+ &mut self,
+ frame: u32,
+ objects: impl Iterator<Item = (VirtualObjectDescriptorKind, u32, u32)>,
+ ) -> Result<(), CompileFailure> {
+ let mut properties = 0;
+ let mut ancestor = frame;
+ while ancestor != NONE {
+ let record = &self.frames[ancestor as usize * FRAME_WORDS..][..FRAME_WORDS];
+ properties += record[FRAME_VALUE_COUNT];
+ ancestor = record[FRAME_PARENT];
+ }
+ let start = self.objects.len() / OBJECT_WORDS;
+ for (kind, allocation, property_count) in objects {
+ let (kind, cell) = match kind {
+ VirtualObjectDescriptorKind::Object { shape } => (OBJECT_KIND_OBJECT, shape),
+ VirtualObjectDescriptorKind::Closure { sample } => (OBJECT_KIND_CLOSURE, sample),
+ };
+ let mut words = [0; OBJECT_WORDS];
+ words[OBJECT_KIND] = kind;
+ words[OBJECT_ALLOCATION] = allocation;
+ words[OBJECT_CELL..][..2].copy_from_slice(&halves(cell.0));
+ words[OBJECT_PROPERTIES] = properties;
+ words[OBJECT_PROPERTY_COUNT] = property_count;
+ self.objects.try_extend_from_slice(&words)?;
+ properties = properties.checked_add(property_count).ok_or(CompileFailure::TooLarge)?;
+ }
+ let count = self.objects.len() / OBJECT_WORDS - start;
+ let record = &mut self.frames[frame as usize * FRAME_WORDS..][..FRAME_WORDS];
+ record[FRAME_OBJECTS] = count_of(start);
+ record[FRAME_OBJECT_COUNT] = count_of(count);
+ Ok(())
+ }
+
+ /// The word for `location`.
+ pub fn location(&mut self, location: ValueLocation) -> Result<u32, CompileFailure> {
+ let (kind, repr, payload) = match location {
+ ValueLocation::Register(register, repr) => (LOCATION_REGISTER, repr, u32::from(register)),
+ ValueLocation::Stack(offset, repr) => {
+ // NB: The shifts keep the bits of an offset that fits, and its sign.
+ let shifted = offset << LOCATION_PAYLOAD_SHIFT;
+ if shifted >> LOCATION_PAYLOAD_SHIFT != offset {
+ return Err(CompileFailure::TooLarge);
+ }
+ (LOCATION_STACK, repr, shifted.cast_unsigned() >> LOCATION_PAYLOAD_SHIFT)
+ }
+ ValueLocation::Frame(slot) => (LOCATION_FRAME, Repr::Tagged, slot),
+ ValueLocation::Constant(bits) => {
+ let index = self.wide.len() / WIDE_WORDS;
+ self.wide.try_extend_from_slice(&halves(bits))?;
+ (LOCATION_CONSTANT, Repr::Tagged, count_of(index))
+ }
+ ValueLocation::ArgumentsObject { mapped } => (LOCATION_ARGUMENTS_OBJECT, Repr::Tagged, u32::from(mapped)),
+ ValueLocation::VirtualObject(index) => (LOCATION_VIRTUAL_OBJECT, Repr::Tagged, index),
+ };
+ if payload >= LOCATION_PAYLOAD_LIMIT {
+ return Err(CompileFailure::TooLarge);
+ }
+ Ok(kind | (repr as u32) << LOCATION_REPR_SHIFT | payload << LOCATION_PAYLOAD_SHIFT)
+ }
+
+ /// How many locations there are: where the run of the next site starts.
+ pub fn location_count(&self) -> u32 {
+ count_of(self.locations.len())
+ }
+
+ /// Adds the word of a location (see `location()`) to the run of the site that is added next.
+ pub fn add_location(&mut self, word: u32) -> Result<(), CompileFailure> {
+ Ok(self.locations.try_push(word)?)
+ }
+
+ /// Adds a site with `frame` as its innermost frame, whose run of locations starts at `locations` and ends where
+ /// the locations end now. Returns its index.
+ pub fn add_site(
+ &mut self,
+ kind: SiteKind,
+ frame: u32,
+ locations: u32,
+ inlined_frame_bytes: u32,
+ ) -> Result<u32, CompileFailure> {
+ let index = self.sites.len() / SITE_WORDS;
+ let kind = match kind {
+ SiteKind::Exit(kind) => SITE_KIND_EXIT | (kind as u32) << 8,
+ SiteKind::Leave => SITE_KIND_LEAVE,
+ SiteKind::Publish => SITE_KIND_PUBLISH,
+ SiteKind::Call => SITE_KIND_CALL,
+ };
+ let mut words = [0; SITE_WORDS];
+ words[SITE_KIND] = kind;
+ words[SITE_FRAME] = frame;
+ words[SITE_LOCATIONS] = locations;
+ words[SITE_INLINED_FRAME_BYTES] = inlined_frame_bytes;
+ self.sites.try_extend_from_slice(&words)?;
+ Ok(count_of(index))
+ }
+
+ /// Completes the tables with `tail`, as one array (see `words()`) with the layout this returns.
+ pub fn finish(&mut self, tail: &Tail<'_>) -> Result<Layout, CompileFailure> {
+ let Self {
+ sites,
+ frames,
+ slots,
+ in_frame,
+ objects,
+ locations,
+ wide,
+ words,
+ } = self;
+ words.clear();
+ let mut layout = Layout::default();
+ let mut next_section = 0;
+ let mut end = |section: Section, words: &Column<u32>| {
+ assert_eq!(
+ section as usize, next_section,
+ "the sections are written in their order"
+ );
+ layout.ends[section as usize] = count_of(words.len());
+ next_section += 1;
+ };
+
+ words.try_extend_from_slice(sites)?;
+ end(Section::Sites, words);
+ words.try_extend_from_slice(frames)?;
+ end(Section::Frames, words);
+ words.try_extend_from_slice(slots)?;
+ end(Section::Slots, words);
+ words.try_extend_from_slice(in_frame)?;
+ end(Section::InFrame, words);
+ words.try_extend_from_slice(objects)?;
+ end(Section::Objects, words);
+ words.try_extend_from_slice(locations)?;
+ end(Section::Locations, words);
+ words.try_extend_from_slice(wide)?;
+ end(Section::Wide, words);
+
+ // NB: The entries are in pc order in both sections, so the pair of an entry is at the same index of each.
+ assert!(tail.osr_entries.is_sorted());
+ for (pc, _) in tail.osr_entries {
+ words.try_push(*pc)?;
+ }
+ end(Section::OsrPcs, words);
+ for (_, offset) in tail.osr_entries {
+ words.try_push(*offset)?;
+ }
+ end(Section::OsrOffsets, words);
+
+ for (section, run) in [
+ (Section::OsrLoopBackEdges, tail.osr_loop_back_edges),
+ (Section::OsrOuterLoopBackEdges, tail.osr_outer_loop_back_edges),
+ (Section::UncaughtHandlers, tail.uncaught_handlers),
+ ] {
+ let start = words.len();
+ words.try_extend_from_slice(run)?;
+ words[start..].sort_unstable();
+ end(section, words);
+ }
+
+ for (offset, bytes) in tail.invalidation_patches {
+ let mut padded = [0; MAX_PATCH_LENGTH];
+ padded[..bytes.len()].copy_from_slice(bytes);
+ let mut record = [0; PATCH_WORDS];
+ record[PATCH_OFFSET] = *offset;
+ record[PATCH_LENGTH] = count_of(bytes.len());
+ record[PATCH_BYTES..][..2].copy_from_slice(&halves(u64::from_le_bytes(padded)));
+ words.try_extend_from_slice(&record)?;
+ }
+ end(Section::Patches, words);
+
+ for cell in tail.embedded_cells {
+ words.try_extend_from_slice(&halves(cell.0))?;
+ }
+ end(Section::EmbeddedCells, words);
+ for dependency in tail.dependencies {
+ let (kind, cell, value) = match *dependency {
+ Dependency::WatchpointSetValid(cell) => (0, cell, 0),
+ Dependency::GlobalDeclarations { environment, serial } => (1, environment, serial),
+ Dependency::GlobalBindingUnassigned { environment, index } => (2, environment, u64::from(index)),
+ Dependency::GlobalPropertyUnassigned { object, offset } => (3, object, u64::from(offset)),
+ Dependency::NoHtmlDdaObjects => (4, CellId(0), 0),
+ Dependency::StableShape(cell) => (5, cell, 0),
+ };
+ let mut record = [kind; DEPENDENCY_WORDS];
+ record[1..3].copy_from_slice(&halves(cell.0));
+ record[3..5].copy_from_slice(&halves(value));
+ words.try_extend_from_slice(&record)?;
+ }
+ end(Section::Dependencies, words);
+ assert_eq!(next_section, SECTION_COUNT);
+ Ok(layout)
+ }
+
+ /// The tables that `finish()` completed.
+ pub fn words(&self) -> &[u32] {
+ &self.words
+ }
+}
+
+/// The tables of compiled code in `words`, which have `layout`.
+pub struct Artifact<'a, W = u32> {
+ words: &'a [W],
+ layout: &'a Layout,
+}
+
+impl<W> Clone for Artifact<'_, W> {
+ fn clone(&self) -> Self {
+ *self
+ }
+}
+
+impl<W> Copy for Artifact<'_, W> {}
+
+impl<'a, W: Word> Artifact<'a, W> {
+ pub fn new(words: &'a [W], layout: &'a Layout) -> Self {
+ Self { words, layout }
+ }
+
+ fn section(self, section: Section) -> &'a [W] {
+ &self.words[self.layout.range(section)]
+ }
+
+ fn record(self, section: Section, index: u32, words: usize) -> &'a [W] {
+ &self.section(section)[index as usize * words..][..words]
+ }
+
+ fn records(self, section: Section, words: usize) -> impl ExactSizeIterator<Item = &'a [W]> {
+ self.section(section).chunks_exact(words)
+ }
+
+ fn location(self, word: u32) -> ValueLocation {
+ let payload = word >> LOCATION_PAYLOAD_SHIFT;
+ let repr = Repr::ALL[((word >> LOCATION_REPR_SHIFT) & LOCATION_REPR_MASK) as usize];
+ match word & LOCATION_KIND_MASK {
+ LOCATION_REGISTER => ValueLocation::Register(payload as u8, repr),
+ LOCATION_STACK => ValueLocation::Stack(
+ (payload << LOCATION_PAYLOAD_SHIFT).cast_signed() >> LOCATION_PAYLOAD_SHIFT,
+ repr,
+ ),
+ LOCATION_FRAME => ValueLocation::Frame(payload),
+ LOCATION_CONSTANT => ValueLocation::Constant(from_halves(self.record(Section::Wide, payload, WIDE_WORDS))),
+ LOCATION_ARGUMENTS_OBJECT => ValueLocation::ArgumentsObject { mapped: payload != 0 },
+ LOCATION_VIRTUAL_OBJECT => ValueLocation::VirtualObject(payload),
+ kind => unreachable!("{kind} is no kind of location"),
+ }
+ }
+
+ pub fn site_count(self) -> u32 {
+ count_of(self.section(Section::Sites).len() / SITE_WORDS)
+ }
+
+ /// The site with the index `index`: exit and leave stubs pass the index of theirs to the runtime, and calls in
+ /// inlined callees name theirs.
+ pub fn site(self, index: u32) -> SiteView<'a, W> {
+ SiteView {
+ artifact: self,
+ record: self.record(Section::Sites, index, SITE_WORDS),
+ }
+ }
+
+ pub fn sites(self) -> impl ExactSizeIterator<Item = SiteView<'a, W>> {
+ self.records(Section::Sites, SITE_WORDS)
+ .map(move |record| SiteView { artifact: self, record })
+ }
+
+ /// The on-stack replacement entry points, as (pc, offset within the code), in pc order: a frame running in the
+ /// interpreter that is at the loop back edge `pc` can continue there, with the same calling convention as the
+ /// entry point.
+ pub fn osr_entries(self) -> impl ExactSizeIterator<Item = (u32, u32)> {
+ let pcs = self.section(Section::OsrPcs).iter().map(W::word);
+ pcs.zip(self.section(Section::OsrOffsets).iter().map(W::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> {
+ Run(self.section(Section::OsrLoopBackEdges))
+ }
+
+ /// 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.
+ pub fn osr_outer_loop_back_edges(self) -> Run<'a, W> {
+ Run(self.section(Section::OsrOuterLoopBackEdges))
+ }
+
+ /// See `ir::Graph::uncaught_handlers`.
+ pub fn uncaught_handlers(self) -> Run<'a, W> {
+ Run(self.section(Section::UncaughtHandlers))
+ }
+
+ /// What invalidates the code: the bytes to write at each offset of it (see `Op::AssumeValid`).
+ pub fn invalidation_patches(self) -> impl ExactSizeIterator<Item = Patch> {
+ self.records(Section::Patches, PATCH_WORDS).map(|record| Patch {
+ offset: record[PATCH_OFFSET].word(),
+ length: record[PATCH_LENGTH].word() as usize,
+ bytes: from_halves(&record[PATCH_BYTES..]).to_le_bytes(),
+ })
+ }
+
+ /// Cells the code depends on (compares against or uses). The runtime keeps them alive for as long as the code
+ /// may run. Only tables that have every section have them.
+ pub fn embedded_cells(self) -> impl ExactSizeIterator<Item = CellId> {
+ self.records(Section::EmbeddedCells, CELL_WORDS)
+ .map(|record| CellId(from_halves(record)))
+ }
+
+ /// What the code assumes keeps holding. The runtime installs the code only if all of them still hold, and
+ /// invalidates it when one stops holding. Only tables that have every section have them.
+ pub fn dependencies(self) -> impl ExactSizeIterator<Item = Dependency> {
+ self.records(Section::Dependencies, DEPENDENCY_WORDS).map(|record| {
+ let cell = CellId(from_halves(&record[1..3]));
+ let value = from_halves(&record[3..5]);
+ match record[0].word() {
+ 0 => Dependency::WatchpointSetValid(cell),
+ 1 => Dependency::GlobalDeclarations {
+ environment: cell,
+ serial: value,
+ },
+ 2 => Dependency::GlobalBindingUnassigned {
+ environment: cell,
+ index: value as u32,
+ },
+ 3 => Dependency::GlobalPropertyUnassigned {
+ object: cell,
+ offset: value as u32,
+ },
+ 4 => Dependency::NoHtmlDdaObjects,
+ 5 => Dependency::StableShape(cell),
+ kind => unreachable!("{kind} is no kind of dependency"),
+ }
+ })
+ }
+}
+
+/// Bytes to write into compiled code.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct Patch {
+ /// Where in the code the bytes go.
+ pub offset: u32,
+ length: usize,
+ bytes: [u8; MAX_PATCH_LENGTH],
+}
+
+impl Patch {
+ pub fn bytes(&self) -> &[u8] {
+ &self.bytes[..self.length]
+ }
+}
+
+/// A sorted run of words.
+pub struct Run<'a, W = u32>(&'a [W]);
+
+impl<W> Clone for Run<'_, W> {
+ fn clone(&self) -> Self {
+ *self
+ }
+}
+
+impl<W> Copy for Run<'_, W> {}
+
+impl<'a, W: Word> Run<'a, W> {
+ pub fn len(self) -> usize {
+ self.0.len()
+ }
+
+ pub fn is_empty(self) -> bool {
+ self.0.is_empty()
+ }
+
+ pub fn iter(self) -> impl DoubleEndedIterator<Item = u32> + ExactSizeIterator + Clone + use<'a, W> {
+ self.0.iter().map(W::word)
+ }
+
+ pub fn contains(self, value: u32) -> bool {
+ self.0.binary_search_by(|word| word.word().cmp(&value)).is_ok()
+ }
+}
+
+/// 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.
+pub struct SiteView<'a, W = u32> {
+ artifact: Artifact<'a, W>,
+ record: &'a [W],
+}
+
+impl<W> Clone for SiteView<'_, W> {
+ fn clone(&self) -> Self {
+ *self
+ }
+}
+
+impl<W> Copy for SiteView<'_, W> {}
+
+impl<'a, W: Word> SiteView<'a, W> {
+ pub fn kind(self) -> SiteKind {
+ let word = self.record[SITE_KIND].word();
+ match word & 0xff {
+ SITE_KIND_EXIT => SiteKind::Exit(ExitKind::ALL[(word >> 8) as usize]),
+ SITE_KIND_LEAVE => SiteKind::Leave,
+ SITE_KIND_PUBLISH => SiteKind::Publish,
+ SITE_KIND_CALL => SiteKind::Call,
+ kind => unreachable!("{kind} is no kind of site"),
+ }
+ }
+
+ /// 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 fn inlined_frame_bytes(self) -> u32 {
+ self.record[SITE_INLINED_FRAME_BYTES].word()
+ }
+
+ fn innermost_frame(self) -> &'a [W] {
+ self.artifact
+ .record(Section::Frames, self.record[SITE_FRAME].word(), FRAME_WORDS)
+ }
+
+ fn locations(self) -> &'a [W] {
+ &self.artifact.section(Section::Locations)[self.record[SITE_LOCATIONS].word() as usize..]
+ }
+
+ /// How many frames are there: those of the inlined calls the site is in, and the compiled function's frame.
+ pub fn frame_count(self) -> usize {
+ (self.innermost_frame()[FRAME_DEPTH].word() >> 1) as usize + 1
+ }
+
+ /// The frames there, innermost first.
+ pub fn frames(self) -> Frames<'a, W> {
+ Frames {
+ artifact: self.artifact,
+ next: self.record[SITE_FRAME].word(),
+ locations: self.locations(),
+ }
+ }
+
+ /// The frame at `index` of `frames()`.
+ pub fn frame(self, index: usize) -> FrameView<'a, W> {
+ self.frames().nth(index).expect("the site has the frame")
+ }
+
+ pub fn object_count(self) -> u32 {
+ self.innermost_frame()[FRAME_OBJECT_COUNT].word()
+ }
+
+ /// The object at `index` among the objects the compiled code never allocated, which the frames' values refer to
+ /// (as `ValueLocation::VirtualObject`).
+ pub fn object(self, index: u32) -> ObjectView<'a, W> {
+ assert!(index < self.object_count());
+ let record = self.artifact.record(
+ Section::Objects,
+ self.innermost_frame()[FRAME_OBJECTS].word() + index,
+ OBJECT_WORDS,
+ );
+ let properties = &self.locations()[record[OBJECT_PROPERTIES].word() as usize..]
+ [..record[OBJECT_PROPERTY_COUNT].word() as usize];
+ ObjectView {
+ artifact: self.artifact,
+ record,
+ properties,
+ }
+ }
+
+ pub fn objects(self) -> impl ExactSizeIterator<Item = ObjectView<'a, W>> {
+ (0..self.object_count()).map(move |index| self.object(index))
+ }
+}
+
+/// The frames of a site, innermost first.
+pub struct Frames<'a, W = u32> {
+ artifact: Artifact<'a, W>,
+ /// The record of the next frame.
+ next: u32,
+ /// The locations of the site from those of the next frame on.
+ locations: &'a [W],
+}
+
+impl<'a, W: Word> Iterator for Frames<'a, W> {
+ type Item = FrameView<'a, W>;
+
+ fn next(&mut self) -> Option<FrameView<'a, W>> {
+ if self.next == NONE {
+ return None;
+ }
+ let record = self.artifact.record(Section::Frames, self.next, FRAME_WORDS);
+ let (locations, rest) = self.locations.split_at(record[FRAME_VALUE_COUNT].word() as usize);
+ self.next = record[FRAME_PARENT].word();
+ self.locations = rest;
+ Some(FrameView {
+ artifact: self.artifact,
+ record,
+ locations,
+ })
+ }
+}
+
+/// The interpreter state of one frame at a site.
+pub struct FrameView<'a, W = u32> {
+ artifact: Artifact<'a, W>,
+ record: &'a [W],
+ /// Where the values are, in the order of their slots.
+ locations: &'a [W],
+}
+
+impl<W> Clone for FrameView<'_, W> {
+ fn clone(&self) -> Self {
+ *self
+ }
+}
+
+impl<W> Copy for FrameView<'_, W> {}
+
+impl<'a, W: Word> FrameView<'a, W> {
+ /// Index into `Snapshot::executables`.
+ pub fn executable(self) -> u32 {
+ self.record[FRAME_EXECUTABLE].word()
+ }
+
+ pub fn pc(self) -> u32 {
+ self.record[FRAME_PC].word()
+ }
+
+ pub fn mode(self) -> ResumeMode {
+ if self.record[FRAME_DEPTH].word() & 1 == 0 {
+ ResumeMode::ResumeAt
+ } else {
+ ResumeMode::ResumeAfter {
+ dst: self.record[FRAME_RESUME_DESTINATION].word(),
+ }
+ }
+ }
+
+ /// See `ir::FrameState::passed_argument_count`.
+ pub fn passed_argument_count(self) -> Option<u32> {
+ Some(self.record[FRAME_PASSED_ARGUMENT_COUNT].word()).filter(|count| *count != NONE)
+ }
+
+ /// 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 fn legacy_arguments(self) -> Range<u32> {
+ self.record[FRAME_LEGACY_ARGUMENTS_START].word()..self.record[FRAME_LEGACY_ARGUMENTS_END].word()
+ }
+
+ /// The slots of `values()`.
+ pub fn slots(self) -> Run<'a, W> {
+ let slots = self.artifact.section(Section::Slots);
+ Run(&slots[self.record[FRAME_SLOTS].word() as usize..][..self.locations.len()])
+ }
+
+ /// The value of each frame slot that differs from what the frame already holds, as the slot and where the value
+ /// is, in slot order.
+ pub fn values(self) -> impl DoubleEndedIterator<Item = (u32, ValueLocation)> + ExactSizeIterator + use<'a, W> {
+ let locations = self
+ .locations
+ .iter()
+ .map(move |word| self.artifact.location(word.word()));
+ self.slots().iter().zip(locations)
+ }
+
+ /// Where the value of `slot` is, if it is among `values()`.
+ pub fn value(self, slot: u32) -> Option<ValueLocation> {
+ let index = self.slots().0.binary_search_by(|word| word.word().cmp(&slot)).ok()?;
+ Some(self.artifact.location(self.locations[index].word()))
+ }
+
+ /// Where the function object of a frame of an inlined closure is (see `CALLEE_SLOT`).
+ pub fn callee(self) -> Option<ValueLocation> {
+ // NB: No slot is above this one.
+ self.values()
+ .next_back()
+ .filter(|(slot, _)| *slot == CALLEE_SLOT)
+ .map(|(_, location)| location)
+ }
+
+ /// The live slots whose value the frame already holds (see `ir::FrameState::in_frame`), in slot order. Exits
+ /// clear the registers and locals that are neither among them nor among the values, except a `ResumeAfter`
+ /// destination, which exits never write either.
+ pub fn in_frame(self) -> Run<'a, W> {
+ let in_frame = self.artifact.section(Section::InFrame);
+ Run(&in_frame[self.record[FRAME_IN_FRAME].word() as usize..]
+ [..self.record[FRAME_IN_FRAME_COUNT].word() as usize])
+ }
+}
+
+/// An object the compiled code never allocated, which an exit creates as its kind says. Each one is created once per
+/// exit, before any is given its properties, so objects may refer to each other.
+pub struct ObjectView<'a, W = u32> {
+ artifact: Artifact<'a, W>,
+ record: &'a [W],
+ properties: &'a [W],
+}
+
+impl<W> Clone for ObjectView<'_, W> {
+ fn clone(&self) -> Self {
+ *self
+ }
+}
+
+impl<W> Copy for ObjectView<'_, W> {}
+
+impl<'a, W: Word> ObjectView<'a, W> {
+ pub fn kind(self) -> VirtualObjectDescriptorKind {
+ let cell = CellId(from_halves(&self.record[OBJECT_CELL..]));
+ match self.record[OBJECT_KIND].word() {
+ OBJECT_KIND_OBJECT => VirtualObjectDescriptorKind::Object { shape: cell },
+ OBJECT_KIND_CLOSURE => VirtualObjectDescriptorKind::Closure { sample: cell },
+ kind => unreachable!("{kind} is no kind of object"),
+ }
+ }
+
+ /// 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 fn allocation(self) -> u32 {
+ self.record[OBJECT_ALLOCATION].word()
+ }
+
+ /// Where the value at `index` of those the kind describes is, if the object has that many.
+ pub fn property(self, index: usize) -> Option<ValueLocation> {
+ self.properties
+ .get(index)
+ .map(|word| self.artifact.location(word.word()))
+ }
+
+ /// Where the values are that the kind describes.
+ pub fn properties(self) -> impl ExactSizeIterator<Item = ValueLocation> + use<'a, W> {
+ self.properties
+ .iter()
+ .map(move |word| self.artifact.location(word.word()))
+ }
+}
diff --git a/Libraries/LibJS/JIT/Rust/src/code.rs b/Libraries/LibJS/JIT/Rust/src/code.rs
index 3638252a197..1b6cf880771 100644
--- a/Libraries/LibJS/JIT/Rust/src/code.rs
+++ b/Libraries/LibJS/JIT/Rust/src/code.rs
@@ -7,6 +7,9 @@
//! The output of a compile job: machine code and the metadata the runtime
//! needs to install it and to exit from it into the interpreter.
+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.
@@ -19,33 +22,6 @@ pub struct CompiledCode {
pub data_offset: u32,
/// Offset of the entry point within `code`.
pub entry_offset: u32,
- /// On-stack replacement entry points, as (pc, offset within `code`): a
- /// frame running in the interpreter that is at the loop back edge `pc`
- /// can continue there, with the same calling convention as the entry
- /// point.
- pub osr_entries: Vec<(u32, u32)>,
- /// 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 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.
- pub osr_outer_loop_back_edges: Vec<u32>,
- /// See `ir::Graph::uncaught_handlers`.
- pub uncaught_handlers: Vec<u32>,
- /// The sites of the code, by index: exit and leave stubs pass the index of
- /// theirs to the runtime, and calls in inlined callees name theirs.
- pub sites: Vec<Site>,
- /// Cells the code depends on (compares against or uses). The runtime keeps
- /// them alive for as long as the code may run.
- pub embedded_cells: Vec<CellId>,
- /// What the code assumes keeps holding. The runtime installs the code
- /// only if all of them still hold, and invalidates it when one stops
- /// holding.
- pub dependencies: Vec<Dependency>,
- /// 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
@@ -57,6 +33,9 @@ pub struct CompiledCode {
/// `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 tables of the code (see `artifact()`), which have `layout`.
+ pub words: Vec<u32>,
+ pub layout: Layout,
/// The debug dumps `CompileOptions` asked for, as text to print.
pub dump: Option<String>,
/// With `CompileOptions::coverage`, what the code contains (see
@@ -64,6 +43,18 @@ pub struct CompiledCode {
pub coverage: Vec<String>,
}
+impl CompiledCode {
+ /// What the runtime reads to install the code, to enter it, and to translate its state into interpreter frames.
+ 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
/// compiled code in the second return register.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -149,6 +140,37 @@ pub enum ExitKind {
LegacyArgumentsRead,
}
+impl ExitKind {
+ /// Every kind, each at the index that is its discriminant.
+ pub const ALL: [Self; 17] = [
+ Self::NoFeedback,
+ Self::NotObject,
+ Self::BadShape,
+ Self::BadCallTarget,
+ Self::UnexpectedValue,
+ Self::SlowPath,
+ Self::ArgumentsIndex,
+ Self::NotInt32,
+ Self::Overflow,
+ Self::BadElements,
+ Self::OutOfBounds,
+ Self::BadType,
+ Self::Uninitialized,
+ Self::Hoisted,
+ Self::Invalidated,
+ Self::Interrupted,
+ Self::LegacyArgumentsRead,
+ ];
+}
+
+const _: () = {
+ let mut index = 0;
+ while index < ExitKind::ALL.len() {
+ assert!(ExitKind::ALL[index] as usize == index);
+ index += 1;
+ }
+};
+
/// Something compiled code assumes keeps holding, without checking it where
/// it relies on it. The runtime invalidates the code when it stops holding:
/// every `Op::AssumeValid` of the code then exits, and the code is
@@ -196,6 +218,35 @@ pub struct Site {
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)]
@@ -331,3 +382,16 @@ pub enum Repr {
/// closure the code never allocated (see `VirtualObjectDescriptorKind`).
Pointer,
}
+
+impl Repr {
+ /// Every representation, each at the index that is its discriminant.
+ pub const ALL: [Self; 5] = [Self::Tagged, Self::Int32, Self::Float64, Self::Bool, Self::Pointer];
+}
+
+const _: () = {
+ let mut index = 0;
+ while index < Repr::ALL.len() {
+ assert!(Repr::ALL[index] as usize == index);
+ index += 1;
+ }
+};
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
index baee49a3916..0b20c6ec306 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
@@ -50,7 +50,7 @@ mod float64;
mod named_storage;
mod probes;
mod property_iterator;
-mod sites;
+pub(crate) mod sites;
mod slow_path;
mod slow_path_calls;
mod speculation;
@@ -65,6 +65,7 @@ pub use slow_path::slow_path_call;
pub use slow_path::slow_path_symbol;
use crate::CompileFailure;
+use crate::artifact::Artifact;
use crate::asm::Address;
use crate::asm::Architecture;
use crate::asm::Condition;
@@ -90,7 +91,6 @@ use crate::code::CALLEE_SLOT;
use crate::code::ExitKind;
use crate::code::JitStatus;
use crate::code::Repr;
-use crate::code::Site;
use crate::code::SiteKind;
use crate::code::ValueLocation;
use crate::fast_hash::{HashMap, HashSet};
@@ -109,12 +109,13 @@ use crate::regalloc::Location;
use crate::regalloc::Move;
use crate::regalloc::RegisterMask;
use crate::regalloc::RegisterSet;
+use crate::scratch::Scratch;
use crate::snapshot::COMPRESSED_POINTER_SHIFT;
use crate::snapshot::CellId;
use crate::snapshot::ExecutableSnapshot;
use crate::snapshot::RuntimeInfo;
use crate::snapshot::StressOptions;
-pub(crate) use sites::site;
+use sites::SiteSource;
/// Bit 32 of a slow path control word marks a continuation in the same frame.
const CONTINUATION_BIT: u64 = 1 << 32;
@@ -207,7 +208,6 @@ pub struct GeneratedCode {
/// Where the instructions end and the constants they load begin.
pub data_offset: u32,
pub entry_offset: u32,
- pub sites: Vec<Site>,
/// What the code from each offset on was generated for, in emission
/// order. Only `dump-asm` reads it.
pub annotations: Vec<(u32, CodeAnnotation)>,
@@ -233,8 +233,8 @@ pub enum CodeAnnotation {
BlockEndMoves,
/// Out-of-line code of a node, emitted after the blocks.
Deferred(NodeId),
- /// The code that takes the exit or leave site `index` (an index into
- /// `sites`) of `node`.
+ /// The code that takes the exit or leave site `index` (see
+ /// `Artifact::site()`) of `node`.
Exit {
index: u32,
node: NodeId,
@@ -415,8 +415,9 @@ struct LeaveStub {
}
/// Generates code for `graph` with `allocation`, whose registers came from
-/// `target_registers::<M>()`. With `verify` (and in debug builds), checks
-/// that every lowering matches its `lowering_info()`.
+/// `target_registers::<M>()`, and writes the sites of the code into the
+/// tables of `scratch`. With `verify` (and in debug builds), checks that
+/// every lowering matches its `lowering_info()`.
pub fn generate<M: PortableMacroAssembler>(
graph: &Graph,
allocation: &Allocation,
@@ -424,6 +425,7 @@ pub fn generate<M: PortableMacroAssembler>(
runtime: &RuntimeInfo,
stress: StressOptions,
verify: bool,
+ scratch: &mut Scratch,
) -> Result<GeneratedCode, CompileFailure> {
let (_, pinned) = target_registers::<M>();
let (gpr_dump_count, fpr_dump_count) = register_dump_counts::<M>();
@@ -498,11 +500,13 @@ pub fn generate<M: PortableMacroAssembler>(
panic!("lowerings that do not match their declarations:\n{errors}");
}
- let sites = codegen
- .sites
- .iter()
- .map(|(node, kind)| codegen.site_descriptor(*node, *kind))
- .collect();
+ scratch.artifact.clear();
+ scratch.sites.begin(graph)?;
+ for (node, kind) in &codegen.sites {
+ codegen.with_site_source(*node, *kind, |site| {
+ site.write(&mut scratch.sites, &mut scratch.artifact)
+ })?;
+ }
let annotations = std::mem::take(&mut codegen.annotations);
let invalidation_patches = codegen
.invalidation_points
@@ -526,7 +530,6 @@ pub fn generate<M: PortableMacroAssembler>(
code,
data_offset,
entry_offset: 0,
- sites,
annotations,
osr_entries,
invalidation_patches,
@@ -535,18 +538,6 @@ pub fn generate<M: PortableMacroAssembler>(
})
}
-/// Points `location`, a register among `saves` (registers with the frame
-/// pointer offsets of their words in the saves area), at its word there.
-fn relocate_saved_register(location: &mut ValueLocation, saves: &[(Gpr, i32)]) {
- // NB: Float64 values are in floating point registers, which are not saved.
- if let ValueLocation::Register(register, repr) = *location
- && repr != crate::code::Repr::Float64
- && let Some((_, offset)) = saves.iter().find(|(saved, _)| saved.0 == register)
- {
- *location = ValueLocation::Stack(*offset, repr);
- }
-}
-
/// The machine code as disassembly, under headers naming the block, IR node
/// or tail each run of instructions was generated for. Calls of runtime
/// helpers and well-known values are named.
@@ -556,6 +547,7 @@ pub fn dump_code(
runtime: &RuntimeInfo,
architecture: Architecture,
generated: &GeneratedCode,
+ artifact: Artifact<'_>,
) -> String {
use std::fmt::Write;
@@ -603,7 +595,7 @@ pub fn dump_code(
}
CodeAnnotation::Tail(name) => writeln!(out, "{name}:").unwrap(),
CodeAnnotation::Exit { index, node } => {
- let kind = match generated.sites[*index as usize].kind {
+ let kind = match artifact.site(*index).kind() {
SiteKind::Exit(kind) => format!("{kind:?}"),
kind => format!("{kind:?}"),
};
@@ -617,7 +609,7 @@ pub fn dump_code(
}
out.push('\n');
}
- let count = |kind: fn(SiteKind) -> bool| generated.sites.iter().filter(|site| kind(site.kind)).count();
+ let count = |kind: fn(SiteKind) -> bool| artifact.sites().filter(|site| kind(site.kind())).count();
writeln!(
out,
"{} instructions, {} bytes, {} exits, {} leaves, {} publish sites, {} call sites",
@@ -848,31 +840,29 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
registers
}
- /// The site of kind `kind` for the frame state of `node`, with where
- /// the runtime finds each value once the code reached it.
- fn site_descriptor(&self, node: NodeId, kind: SiteKind) -> Site {
- let fp_offset = |slot: u32| self.frame_pointer_offset(slot);
- let mut descriptor = site(self.graph, self.allocation, node, kind, &fp_offset);
+ /// Calls `with` with what the site of kind `kind` for the frame state of
+ /// `node` is written from: where the runtime finds each value once the
+ /// code reached the site.
+ fn with_site_source<T>(&self, node: NodeId, kind: SiteKind, with: impl FnOnce(&SiteSource<'_>) -> T) -> T {
// NB: A slow path call keeps the registers it saved in the saves
// area while it runs, where its exits find them.
- if let Op::CallSlowPath {
+ let saves = if let Op::CallSlowPath {
saves_registers: true, ..
} = self.graph.node(node).op
{
let saved = slow_path_calls::slow_path_saved_registers_of::<M>(self.allocation.node(node));
- let saves = self.save_slot_offsets(&saved);
- for frame in &mut descriptor.frames {
- for (_, location) in &mut frame.values {
- relocate_saved_register(location, &saves);
- }
- }
- for object in &mut descriptor.objects {
- for location in &mut object.properties {
- relocate_saved_register(location, &saves);
- }
- }
- }
- descriptor
+ self.save_slot_offsets(&saved)
+ } else {
+ Vec::new()
+ };
+ with(&SiteSource {
+ graph: self.graph,
+ allocation: self.allocation,
+ node,
+ kind,
+ stack_slot_offset: &|slot| self.frame_pointer_offset(slot),
+ saves: &saves,
+ })
}
/// The offset of the local at `offset` from the frame pointer.
@@ -3277,8 +3267,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
let Some((handler_pc, exception_dst, entry_pc, entry)) = self.catch_entry_of(leave_frame.node)? else {
return Ok(());
};
- let descriptor = self.site_descriptor(leave_frame.node, SiteKind::Leave);
- let values = &descriptor.frames.last().expect("a site has a frame state").values;
+ let values = self.with_site_source(leave_frame.node, SiteKind::Leave, |site| site.root_frame_values());
let writable = |location: &ValueLocation| {
!matches!(
location,
@@ -3333,7 +3322,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
self.masm.bind(initialized);
let value = M::RETURN_GPRS[0];
let number = M::ARGUMENT_FPRS[0];
- for (slot, location) in values {
+ for (slot, location) in &values {
match *location {
ValueLocation::Constant(bits) => self.masm.move_imm64(value, bits),
ValueLocation::Register(register, Repr::Float64) => {
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/sites.rs b/Libraries/LibJS/JIT/Rust/src/codegen/sites.rs
index 78e179bcf10..cd2bd0568f2 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/sites.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/sites.rs
@@ -4,16 +4,20 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-//! The sites of compiled code (see `code::Site`): where the translator finds
-//! the values of a node's frame state, from the register allocation.
+//! The sites of compiled code (see `artifact::SiteView`): where the translator finds the values of a node's frame
+//! state, from the register allocation.
-use crate::code::FrameState as CodeFrameState;
+use ak::Column;
+
+use crate::CompileFailure;
+use crate::artifact::ArtifactWriter;
+use crate::artifact::Frame;
+use crate::asm::Gpr;
use crate::code::Repr;
-use crate::code::Site;
use crate::code::SiteKind;
use crate::code::ValueLocation;
-use crate::code::VirtualObjectDescriptor;
use crate::code::VirtualObjectDescriptorKind;
+use crate::ir::FrameStateId;
use crate::ir::Graph;
use crate::ir::NodeId;
use crate::ir::Op;
@@ -22,28 +26,114 @@ use crate::regalloc::Allocation;
use crate::regalloc::FPR_BASE;
use crate::regalloc::Location;
-/// Builds the site of kind `kind` for the frame state of `node`, converting
-/// spill slots to frame offsets with `stack_slot_offset`.
-pub(crate) fn site(
- graph: &Graph,
- allocation: &Allocation,
- node: NodeId,
+/// In place of the record of a frame state: it has none.
+const NO_RECORD: u32 = u32::MAX;
+
+/// What the sites of a compile are written with. Its memory serves the next compile.
+pub(crate) struct SiteScratch {
+ /// The record of each frame state of the graph in the tables of the code, by the index of the frame state.
+ frame_records: Column<u32>,
+ /// The frame states of a chain that have no record.
+ pending: Column<u32>,
+ /// The values of a frame at a site, as the slot in the high half and the word of the location in the low half.
+ values: Column<u64>,
+}
+
+impl SiteScratch {
+ // NB: A compile whose graph has more frame states, or a frame state with more values or callers, fails.
+ const MAX_FRAME_STATES: usize = 1 << 24;
+ const MAX_FRAME_VALUES: usize = 1 << 22;
+ const MAX_FRAME_DEPTH: usize = 1 << 16;
+
+ pub(crate) fn new() -> Self {
+ Self {
+ frame_records: Column::new(Self::MAX_FRAME_STATES, c"JIT frame state records"),
+ pending: Column::new(Self::MAX_FRAME_DEPTH, c"JIT frame state chain"),
+ values: Column::new(Self::MAX_FRAME_VALUES, c"JIT frame values"),
+ }
+ }
+
+ pub(crate) fn release_memory(&mut self) {
+ self.frame_records.clear();
+ self.frame_records.trim(0);
+ self.pending.clear();
+ self.pending.trim(0);
+ self.values.clear();
+ self.values.trim(0);
+ }
+
+ /// Starts the sites of the code of `graph`, in tables that hold nothing.
+ pub(crate) fn begin(&mut self, graph: &Graph) -> Result<(), CompileFailure> {
+ self.frame_records.clear();
+ Ok(self.frame_records.try_resize(graph.frame_states.len(), NO_RECORD)?)
+ }
+
+ /// The record of `frame_state`, which gets one with its callers if it has none.
+ fn frame_record(
+ &mut self,
+ graph: &Graph,
+ frame_state: FrameStateId,
+ artifact: &mut ArtifactWriter,
+ ) -> Result<u32, CompileFailure> {
+ self.pending.clear();
+ let mut parent = None;
+ let mut next = Some(frame_state);
+ while let Some(id) = next {
+ let record = self.frame_records[id.index()];
+ if record != NO_RECORD {
+ parent = Some(record);
+ break;
+ }
+ self.pending.try_push(id.0)?;
+ next = graph.frame_state(id).parent;
+ }
+ // NB: The record of a frame names that of its caller, so callers come first.
+ for index in (0..self.pending.len()).rev() {
+ let id = FrameStateId(self.pending[index]);
+ let state = graph.frame_state(id);
+ let frame = Frame {
+ executable: state.executable,
+ pc: state.pc,
+ mode: state.mode,
+ passed_argument_count: state.passed_argument_count,
+ legacy_arguments: state.legacy_arguments.clone(),
+ parent,
+ };
+ let record = artifact.add_frame(&frame, state.values.iter().map(|(slot, _)| *slot), &state.in_frame)?;
+ self.frame_records[id.index()] = record;
+ parent = Some(record);
+ }
+ Ok(parent.expect("a chain has a frame state"))
+ }
+}
+
+/// Where a site of kind `kind` finds the values of the frame state of `node`, one after the other in the order of
+/// `Graph::frame_state_values()`.
+struct Locations<'a> {
+ graph: &'a Graph,
+ allocation: &'a Allocation,
kind: SiteKind,
- stack_slot_offset: &dyn Fn(u32) -> i32,
-) -> Site {
- let frame_state = graph.node(node).frame_state.expect("the node has a frame state");
- let chain = graph.frame_state_chain(frame_state);
- let objects = graph.virtual_objects(frame_state);
- let mut exit_values = allocation.node(node).exit_values.iter();
- let mut location_of = |value: NodeId| {
- let (slot, location) = *exit_values.next().expect("every frame state value has a location");
- if let Some(index) = objects.iter().position(|object| *object == value) {
+ /// See `Graph::virtual_objects()`.
+ objects: &'a [NodeId],
+ exit_values: core::slice::Iter<'a, (u32, Location)>,
+ /// Converts spill slots to frame offsets.
+ stack_slot_offset: &'a dyn Fn(u32) -> i32,
+ /// Registers that are in the saves area at the site, with the frame pointer offsets of their words there.
+ saves: &'a [(Gpr, i32)],
+}
+
+impl Locations<'_> {
+ /// The slot and the location of `value`, the next value.
+ fn next(&mut self, value: NodeId) -> (u32, ValueLocation) {
+ let (slot, location) = *self.exit_values.next().expect("every frame state value has a location");
+ if let Some(index) = self.objects.iter().position(|object| *object == value) {
return (
slot,
ValueLocation::VirtualObject(u32::try_from(index).expect("objects fit in u32")),
);
}
- let repr = graph
+ let repr = self
+ .graph
.node(value)
.repr
.expect("frame state values have a representation");
@@ -51,83 +141,136 @@ pub(crate) fn site(
// NB: Stack walks and the runtime read the values of inlined call
// sites from the JIT frame while the call runs, without the
// registers. Values live across calls have stack slots.
- Location::Register(_) if kind == SiteKind::Call => match allocation.node(value).spill_slot {
- Some(slot) => ValueLocation::Stack(stack_slot_offset(slot), repr),
+ Location::Register(_) if self.kind == SiteKind::Call => match self.allocation.node(value).spill_slot {
+ Some(slot) => ValueLocation::Stack((self.stack_slot_offset)(slot), repr),
None => ValueLocation::Frame(
- crate::regalloc::frame_home(graph, value).expect("values live across calls are spilled"),
+ crate::regalloc::frame_home(self.graph, value).expect("values live across calls are spilled"),
),
},
// NB: Exits read float64 values from the floating point registers.
Location::Register(register) => ValueLocation::Register(register % FPR_BASE, repr),
- Location::Stack(slot) => ValueLocation::Stack(stack_slot_offset(slot), repr),
+ Location::Stack(slot) => ValueLocation::Stack((self.stack_slot_offset)(slot), repr),
Location::Frame(slot) => ValueLocation::Frame(slot),
Location::Constant(bits) => match crate::ir::value::virtual_arguments_kind(bits) {
Some(mapped) if repr == Repr::Tagged => ValueLocation::ArgumentsObject { mapped },
_ => ValueLocation::Constant(crate::ir::value::boxed_constant(bits, repr)),
},
};
+ // NB: Float64 values are in floating point registers, which are not saved.
+ if let ValueLocation::Register(register, repr) = location
+ && repr != Repr::Float64
+ && let Some((_, offset)) = self.saves.iter().find(|(saved, _)| saved.0 == register)
+ {
+ return (slot, ValueLocation::Stack(*offset, repr));
+ }
(slot, location)
- };
- let frames = chain
- .into_iter()
- .map(|frame_state| {
- let frame_state = graph.frame_state(frame_state);
- let mut values = frame_state
- .values
- .iter()
- .map(|(_, value)| location_of(*value))
- .collect::<Vec<_>>();
- values.sort_unstable_by_key(|(slot, _)| *slot);
- let mut in_frame = frame_state.in_frame.clone();
- in_frame.sort_unstable();
- CodeFrameState {
- executable: frame_state.executable,
- pc: frame_state.pc,
- mode: frame_state.mode,
- values: values.into_boxed_slice(),
- in_frame: in_frame.into_boxed_slice(),
- passed_argument_count: frame_state.passed_argument_count,
- legacy_arguments: frame_state.legacy_arguments.clone(),
+ }
+}
+
+/// What a site is written from.
+pub(crate) struct SiteSource<'a> {
+ pub graph: &'a Graph,
+ pub allocation: &'a Allocation,
+ /// The node whose frame state the site has.
+ pub node: NodeId,
+ pub kind: SiteKind,
+ /// Converts spill slots to frame offsets.
+ pub stack_slot_offset: &'a dyn Fn(u32) -> i32,
+ /// Registers that are in the saves area at the site and not where they were allocated, with the frame pointer
+ /// offsets of their words there.
+ pub saves: &'a [(Gpr, i32)],
+}
+
+impl SiteSource<'_> {
+ /// Adds the site to the tables of the code, as the next site.
+ pub(crate) fn write(&self, scratch: &mut SiteScratch, artifact: &mut ArtifactWriter) -> Result<(), CompileFailure> {
+ let graph = self.graph;
+ let frame_state = graph.node(self.node).frame_state.expect("the node has a frame state");
+ let frame = scratch.frame_record(graph, frame_state, artifact)?;
+ let objects = graph.virtual_objects(frame_state);
+ if !artifact.frame_has_objects(frame) {
+ let objects = objects.iter().map(|object| {
+ let Op::VirtualObject { kind, allocation } = graph.node(*object).op else {
+ unreachable!("virtual objects are VirtualObject nodes");
+ };
+ let kind = match kind {
+ VirtualObjectKind::Object { shape } => VirtualObjectDescriptorKind::Object { shape },
+ VirtualObjectKind::Closure { sample } => VirtualObjectDescriptorKind::Closure { sample },
+ };
+ let property_count = u32::try_from(graph.node(*object).inputs.len()).expect("inputs fit in u32");
+ (kind, allocation.0, property_count)
+ });
+ artifact.set_frame_objects(frame, objects)?;
+ }
+ let mut locations = self.locations(&objects);
+ let start = artifact.location_count();
+ let mut next = Some(frame_state);
+ while let Some(id) = next {
+ let state = graph.frame_state(id);
+ scratch.values.clear();
+ for (_, value) in &state.values {
+ let (slot, location) = locations.next(*value);
+ let word = artifact.location(location)?;
+ scratch.values.try_push(u64::from(slot) << 32 | u64::from(word))?;
}
- })
- .collect();
- // NB: The properties of the virtual objects follow the frames' values.
- let objects = objects
- .iter()
- .map(|object| {
- let Op::VirtualObject { kind, allocation } = graph.node(*object).op else {
- unreachable!("virtual objects are VirtualObject nodes");
- };
- let kind = match kind {
- VirtualObjectKind::Object { shape } => VirtualObjectDescriptorKind::Object { shape },
- VirtualObjectKind::Closure { sample } => VirtualObjectDescriptorKind::Closure { sample },
- };
- let properties = graph
- .node(*object)
- .inputs
- .iter()
- .map(|property| location_of(*property).1)
- .collect();
- VirtualObjectDescriptor {
- kind,
- allocation: allocation.0,
- properties,
+ // NB: The locations of a frame are in the order of its slots, which are in the high halves.
+ scratch.values.sort_unstable();
+ for value in scratch.values.iter() {
+ artifact.add_location(*value as u32)?;
}
- })
- .collect();
- let inlined_frame_bytes = match graph.node(node).op {
- Op::CallDirect {
- inlined_frame_bytes, ..
+ next = state.parent;
+ }
+ // NB: The properties of the virtual objects follow the frames' values.
+ for object in &objects {
+ for property in &graph.node(*object).inputs {
+ let (_, location) = locations.next(*property);
+ let word = artifact.location(location)?;
+ artifact.add_location(word)?;
+ }
+ }
+ let inlined_frame_bytes = match graph.node(self.node).op {
+ Op::CallDirect {
+ inlined_frame_bytes, ..
+ }
+ | Op::CallNative {
+ inlined_frame_bytes, ..
+ } if self.kind == SiteKind::Call => inlined_frame_bytes,
+ _ => 0,
+ };
+ artifact.add_site(self.kind, frame, start, inlined_frame_bytes)?;
+ Ok(())
+ }
+
+ /// The slots of the values of the compiled function's frame at the site and where the values are, in slot order.
+ pub(crate) fn root_frame_values(&self) -> Vec<(u32, ValueLocation)> {
+ let frame_state = self
+ .graph
+ .node(self.node)
+ .frame_state
+ .expect("the node has a frame state");
+ let objects = self.graph.virtual_objects(frame_state);
+ let mut locations = self.locations(&objects);
+ let mut values = Vec::new();
+ let mut next = Some(frame_state);
+ while let Some(id) = next {
+ let state = self.graph.frame_state(id);
+ values.clear();
+ values.extend(state.values.iter().map(|(_, value)| locations.next(*value)));
+ next = state.parent;
+ }
+ values.sort_unstable_by_key(|(slot, _)| *slot);
+ values
+ }
+
+ fn locations<'a>(&'a self, objects: &'a [NodeId]) -> Locations<'a> {
+ Locations {
+ graph: self.graph,
+ allocation: self.allocation,
+ kind: self.kind,
+ objects,
+ exit_values: self.allocation.node(self.node).exit_values.iter(),
+ stack_slot_offset: self.stack_slot_offset,
+ saves: self.saves,
}
- | Op::CallNative {
- inlined_frame_bytes, ..
- } if kind == SiteKind::Call => inlined_frame_bytes,
- _ => 0,
- };
- Site {
- kind,
- frames,
- objects,
- inlined_frame_bytes,
}
}
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs b/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs
index ace6a574a16..2b54c66bce7 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs
@@ -17,6 +17,7 @@ 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;
@@ -937,7 +938,7 @@ impl Machine {
.iter()
.map(|executable| executable.cell.0)
.collect();
- state.exits = compiled.sites.clone();
+ state.exits = compiled.sites();
state.exits_taken.clear();
}
let code = crate::asm::executable_code::ExecutableCode::new(&compiled.code);
@@ -980,8 +981,12 @@ fn compile_program_with(
.iter()
.map(|index| program.offsets[*index])
.collect::<Vec<_>>();
- let compiled = compile_for::<crate::asm::MacroAssembler>(&snapshot, &|pc| !never_ran_pcs.contains(&pc))
- .unwrap_or_else(|failure| panic!("compilation failed: {failure:?}"));
+ let compiled = compile_for::<crate::asm::MacroAssembler>(
+ &snapshot,
+ &|pc| !never_ran_pcs.contains(&pc),
+ &mut crate::scratch::Scratch::new(),
+ )
+ .unwrap_or_else(|failure| panic!("compilation failed: {failure:?}"));
(snapshot, compiled)
}
@@ -1177,8 +1182,9 @@ mod execution {
let (snapshot, compiled) = compile_program_with(program, test_layout(), never_ran, |snapshot| {
snapshot.options.osr_pc = Some(back_edge_pc(program));
});
- assert_eq!(compiled.osr_entries.len(), 1);
- let (pc, offset) = compiled.osr_entries[0];
+ let osr_entries = compiled.artifact().osr_entries().collect::<Vec<_>>();
+ assert_eq!(osr_entries.len(), 1);
+ let (pc, offset) = osr_entries[0];
assert_eq!(pc, program.offsets[back_edge]);
// The interpreter ran Enter and five iterations of the loop.
let mut machine = Machine::new(test_layout(), &[value::int32(10)]);
@@ -1230,8 +1236,9 @@ mod execution {
let (snapshot, compiled) = compile_program_with(&program, test_layout(), &[], |snapshot| {
snapshot.options.osr_pc = Some(back_edge_pc(&program));
});
- assert_eq!(compiled.osr_entries.len(), 1);
- let (pc, offset) = compiled.osr_entries[0];
+ let osr_entries = compiled.artifact().osr_entries().collect::<Vec<_>>();
+ assert_eq!(osr_entries.len(), 1);
+ let (pc, offset) = osr_entries[0];
assert_eq!(pc, program.offsets[7]);
// The interpreter ran five iterations.
let mut machine = Machine::new(test_layout(), &[value::int32(10)]);
@@ -1279,7 +1286,7 @@ mod execution {
let (_, compiled) = compile_program_with(&program, test_layout(), &[], |snapshot| {
snapshot.options.osr_pc = Some(back_edge_pc(&program));
});
- assert_eq!(compiled.osr_entries.len(), 1);
+ assert_eq!(compiled.artifact().osr_entries().len(), 1);
}
#[test]
@@ -1336,8 +1343,9 @@ mod execution {
snapshot.options.osr_pc = Some(back_edge_pc(&program));
snapshot.options.verify_ir = true;
});
- assert_eq!(compiled.osr_entries.len(), 1);
- let (pc, offset) = compiled.osr_entries[0];
+ let osr_entries = compiled.artifact().osr_entries().collect::<Vec<_>>();
+ assert_eq!(osr_entries.len(), 1);
+ let (pc, offset) = osr_entries[0];
assert_eq!(pc, program.offsets[8]);
// The interpreter ran five iterations of the inner loop.
let mut machine = Machine::new(test_layout(), &[value::int32(10)]);
@@ -1613,7 +1621,7 @@ mod execution {
]
});
let (_, compiled) = compile_program(&program, test_layout(), &[5]);
- assert!(compiled.sites.iter().any(|site| {
+ assert!(compiled.sites().iter().any(|site| {
site.frames[0]
.values
.iter()
@@ -2241,7 +2249,9 @@ fn jumps_skip_blocks_that_only_jump_on() {
});
let mut snapshot = crate::builder::tests::snapshot_for(&program, test_layout());
snapshot.runtime = runtime();
- let compiled = compile_for::<crate::asm::x86_64::MacroAssembler>(&snapshot, &|_| true).unwrap();
+ let compiled =
+ compile_for::<crate::asm::x86_64::MacroAssembler>(&snapshot, &|_| true, &mut crate::scratch::Scratch::new())
+ .unwrap();
let listing = crate::asm::disassembler::listing_with_data(
crate::asm::Architecture::X86_64,
&compiled.code,
@@ -2278,8 +2288,12 @@ fn prologues_check_the_stack_limit_before_they_move_the_stack_pointer() {
let program = assemble(|_| vec![Instruction::Enter, Instruction::Return { value: a(0) }]);
let mut snapshot = crate::builder::tests::snapshot_for(&program, test_layout());
snapshot.runtime = runtime();
- let x86_64 = compile_for::<crate::asm::x86_64::MacroAssembler>(&snapshot, &|_| true).unwrap();
- let aarch64 = compile_for::<crate::asm::aarch64::MacroAssembler>(&snapshot, &|_| true).unwrap();
+ let x86_64 =
+ compile_for::<crate::asm::x86_64::MacroAssembler>(&snapshot, &|_| true, &mut crate::scratch::Scratch::new())
+ .unwrap();
+ let aarch64 =
+ compile_for::<crate::asm::aarch64::MacroAssembler>(&snapshot, &|_| true, &mut crate::scratch::Scratch::new())
+ .unwrap();
for (architecture, compiled, is_branch, writes_stack) in [
(
crate::asm::Architecture::X86_64,
@@ -2357,7 +2371,12 @@ fn aarch64_code_disassembles() {
let mut snapshot = crate::builder::tests::snapshot_for(&program, test_layout());
snapshot.runtime = runtime();
let never_ran = program.offsets[5];
- let compiled = compile_for::<crate::asm::aarch64::MacroAssembler>(&snapshot, &|pc| pc != never_ran).unwrap();
+ let compiled = compile_for::<crate::asm::aarch64::MacroAssembler>(
+ &snapshot,
+ &|pc| pc != never_ran,
+ &mut crate::scratch::Scratch::new(),
+ )
+ .unwrap();
let lines = crate::asm::disassembler::aarch64(&compiled.code[..compiled.data_offset as usize]);
let text = lines.join("\n");
// The prologue links the frame right after the stack limit check, slow paths and helpers are called through
@@ -2370,13 +2389,18 @@ 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.sites().iter().map(|site| site.kind).collect::<Vec<_>>();
assert_eq!(
kinds,
[SiteKind::Exit(ExitKind::NoFeedback), SiteKind::Leave, SiteKind::Leave]
);
- let compiled = compile_for::<crate::asm::x86_64::MacroAssembler>(&snapshot, &|pc| pc != never_ran).unwrap();
+ let compiled = compile_for::<crate::asm::x86_64::MacroAssembler>(
+ &snapshot,
+ &|pc| pc != never_ran,
+ &mut crate::scratch::Scratch::new(),
+ )
+ .unwrap();
let lines = crate::asm::disassembler::x86_64(&compiled.code[..compiled.data_offset as usize]);
let check = lines
.iter()
@@ -2386,8 +2410,18 @@ fn aarch64_code_disassembles() {
// The dump names exits, slow paths and the shared tails on both architectures.
snapshot.options.dump_asm = true;
- let x86_64 = compile_for::<crate::asm::x86_64::MacroAssembler>(&snapshot, &|pc| pc != never_ran).unwrap();
- let aarch64 = compile_for::<crate::asm::aarch64::MacroAssembler>(&snapshot, &|pc| pc != never_ran).unwrap();
+ let x86_64 = compile_for::<crate::asm::x86_64::MacroAssembler>(
+ &snapshot,
+ &|pc| pc != never_ran,
+ &mut crate::scratch::Scratch::new(),
+ )
+ .unwrap();
+ let aarch64 = compile_for::<crate::asm::aarch64::MacroAssembler>(
+ &snapshot,
+ &|pc| pc != never_ran,
+ &mut crate::scratch::Scratch::new(),
+ )
+ .unwrap();
for dump in [x86_64.dump.unwrap(), aarch64.dump.unwrap()] {
assert!(dump.contains("Exit NoFeedback [fs"), "{dump}");
assert!(dump.contains("exit #0 (NoFeedback) of v"), "{dump}");
@@ -2437,8 +2471,12 @@ fn slow_paths_share_initialization_of_large_frames() {
.collect();
snapshot.executables[0].feedback.arith = vec![1 | 1 << 1 | 1 << 2 | 1 << 3];
snapshot.options.dump_asm = true;
- let aarch64 = compile_for::<crate::asm::aarch64::MacroAssembler>(&snapshot, &|_| true).unwrap();
- let x86_64 = compile_for::<crate::asm::x86_64::MacroAssembler>(&snapshot, &|_| true).unwrap();
+ let aarch64 =
+ compile_for::<crate::asm::aarch64::MacroAssembler>(&snapshot, &|_| true, &mut crate::scratch::Scratch::new())
+ .unwrap();
+ let x86_64 =
+ compile_for::<crate::asm::x86_64::MacroAssembler>(&snapshot, &|_| true, &mut crate::scratch::Scratch::new())
+ .unwrap();
for compiled in [aarch64, x86_64] {
assert!(
compiled.code.len() < 64 * 1024,
@@ -2498,7 +2536,9 @@ fn x86_64_shifts_find_their_amount_in_cl() {
let mut snapshot = crate::builder::tests::snapshot_for(&program, test_layout());
snapshot.runtime = runtime();
snapshot.executables[0].feedback.arith = vec![crate::snapshot::arith_feedback::INT32; 2];
- let compiled = compile_for::<crate::asm::x86_64::MacroAssembler>(&snapshot, &|_| true).unwrap();
+ let compiled =
+ compile_for::<crate::asm::x86_64::MacroAssembler>(&snapshot, &|_| true, &mut crate::scratch::Scratch::new())
+ .unwrap();
let text = crate::asm::disassembler::x86_64(&compiled.code[..compiled.data_offset as usize]).join("\n");
// NB: The macro assembler shifts amounts in other registers in a scratch register, saving RCX in another.
assert!(text.contains(", cl"), "{text}");
@@ -2512,7 +2552,8 @@ fn dumps_ir_and_code_on_request() {
snapshot.runtime = runtime();
snapshot.options.dump_ir = true;
snapshot.options.dump_asm = true;
- let compiled = compile_for::<crate::asm::MacroAssembler>(&snapshot, &|_| true).unwrap();
+ let compiled =
+ compile_for::<crate::asm::MacroAssembler>(&snapshot, &|_| true, &mut crate::scratch::Scratch::new()).unwrap();
let dump = compiled.dump.unwrap();
assert!(dump.contains("LoadSlot a0"), "{dump}");
assert!(dump.contains("prologue:"), "{dump}");
@@ -2535,7 +2576,8 @@ fn missing_slow_paths_fail_compilation_cleanly() {
});
let mut snapshot = crate::builder::tests::snapshot_for(&program, test_layout());
snapshot.runtime = runtime();
- let failure = compile_for::<crate::asm::MacroAssembler>(&snapshot, &|_| true).unwrap_err();
+ let failure = compile_for::<crate::asm::MacroAssembler>(&snapshot, &|_| true, &mut crate::scratch::Scratch::new())
+ .unwrap_err();
assert_eq!(
failure,
CompileFailure::MissingRuntimeHelper {
@@ -2624,7 +2666,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.sites()[*index as usize].kind {
SiteKind::Exit(kind) => kind,
kind => panic!("{kind:?} is no exit"),
})
@@ -2652,7 +2694,7 @@ mod property_access {
let hit = Object::new(&shape, &[0, value::int32(5)]);
let (result, _, compiled) = run_with_caches(&program, caches(), hit.value(), None);
assert_eq!(result, returned(value::int32(15)));
- assert_eq!(compiled.embedded_cells, [shape.id()]);
+ assert!(compiled.artifact().embedded_cells().eq([shape.id()]));
let miss = Object::new(&other_shape, &[0, value::int32(5)]);
let (result, machine, compiled) = run_with_caches(&program, caches(), miss.value(), None);
@@ -2714,7 +2756,7 @@ mod property_access {
let (result, _, compiled) = run_with_caches(&program, vec![cache(vec![entry])], receiver.value(), None);
assert_eq!(result, returned(value::int32(42)));
- assert_eq!(compiled.embedded_cells.len(), 3);
+ assert_eq!(compiled.artifact().embedded_cells().len(), 3);
// A changed dictionary generation means the shape changed in place.
let changed_receiver_shape = Cell::new([8, 0, 0]);
@@ -3021,13 +3063,17 @@ fn aarch64_property_access_disassembles() {
cache(vec![prototype_entry]),
cache(vec![own(ChangeOwnProperty, 0x3000, 2)]),
];
- let compiled = compile_for::<crate::asm::aarch64::MacroAssembler>(&snapshot, &|_| true).unwrap();
+ let compiled =
+ compile_for::<crate::asm::aarch64::MacroAssembler>(&snapshot, &|_| true, &mut crate::scratch::Scratch::new())
+ .unwrap();
let text = crate::asm::disassembler::aarch64(&compiled.code[..compiled.data_offset as usize]).join("\n");
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}");
- let compiled = compile_for::<crate::asm::x86_64::MacroAssembler>(&snapshot, &|_| true).unwrap();
+ assert_eq!(compiled.sites().len(), 11, "{text}");
+ let compiled =
+ compile_for::<crate::asm::x86_64::MacroAssembler>(&snapshot, &|_| true, &mut crate::scratch::Scratch::new())
+ .unwrap();
assert!(!crate::asm::disassembler::x86_64(&compiled.code[..compiled.data_offset as usize]).is_empty());
}
@@ -3110,7 +3156,9 @@ mod inlining {
});
}
configure(&mut snapshot);
- let compiled = compile_for::<crate::asm::MacroAssembler>(&snapshot, &|_| true).unwrap();
+ let compiled =
+ compile_for::<crate::asm::MacroAssembler>(&snapshot, &|_| true, &mut crate::scratch::Scratch::new())
+ .unwrap();
let mut machine = Machine::new(test_layout(), &[callee_value(boxed(&function_object))]);
prepare(&mut machine);
let result = machine.run(&snapshot, &compiled);
@@ -3124,7 +3172,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.sites().iter().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;
@@ -3185,7 +3233,7 @@ mod inlining {
assert!(machine.state.borrow().exits_taken.is_empty(), "leaves are no exits");
assert!(
compiled
- .sites
+ .sites()
.iter()
.any(|site| site.kind == SiteKind::Leave && site.frames.len() > 1)
);
@@ -3223,7 +3271,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.sites().iter().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
@@ -3236,7 +3284,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.sites().iter().any(|site| site.kind == SiteKind::Publish));
// A slow path that does not continue leaves the interpreter in the
// callee's frame.
@@ -3266,7 +3314,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.sites()[state.exits_taken[0] as usize].kind,
SiteKind::Exit(ExitKind::BadCallTarget)
);
assert_eq!(state.exit_frames[0].len(), 1);
@@ -3417,7 +3465,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.sites()[state.exits_taken[0] as usize].kind,
SiteKind::Exit(ExitKind::ArgumentsIndex)
);
let (_, _, _, values) = &state.exit_frames[0][0];
@@ -3654,10 +3702,20 @@ mod direct_calls {
fn direct_calls_store_constant_frame_fields_16_bytes_at_a_time() {
let callee = Callee::new();
let (snapshot, _) = compile_caller(callee.target(true, true));
- let compiled = compile_for::<crate::asm::aarch64::MacroAssembler>(&snapshot, &|_| true).unwrap();
+ let compiled = compile_for::<crate::asm::aarch64::MacroAssembler>(
+ &snapshot,
+ &|_| true,
+ &mut crate::scratch::Scratch::new(),
+ )
+ .unwrap();
let text = crate::asm::disassembler::aarch64(&compiled.code[..compiled.data_offset as usize]).join("\n");
assert!(text.contains("str q0, [x"), "{text}");
- let compiled = compile_for::<crate::asm::x86_64::MacroAssembler>(&snapshot, &|_| true).unwrap();
+ let compiled = compile_for::<crate::asm::x86_64::MacroAssembler>(
+ &snapshot,
+ &|_| true,
+ &mut crate::scratch::Scratch::new(),
+ )
+ .unwrap();
let text = crate::asm::disassembler::x86_64(&compiled.code[..compiled.data_offset as usize]).join("\n");
assert!(text.contains("movups xmmword ptr ["), "{text}");
}
@@ -3672,7 +3730,13 @@ mod direct_calls {
REALM,
GLOBAL_THIS,
] {
- assert!(compiled.embedded_cells.contains(&CellId(cell)), "{cell:#x}");
+ assert!(
+ compiled
+ .artifact()
+ .embedded_cells()
+ .any(|embedded| embedded == CellId(cell)),
+ "{cell:#x}"
+ );
}
}
@@ -3862,7 +3926,12 @@ mod direct_calls {
allocation.local_end_offset = 16;
allocation.local_cell_size_offset = 24;
});
- assert!(compiled.embedded_cells.contains(&CellId(0xcafe)));
+ assert!(
+ compiled
+ .artifact()
+ .embedded_cells()
+ .any(|embedded| embedded == CellId(0xcafe))
+ );
let mut machine = Machine::new(
caller_layout(),
&[callee.function_value(), value::int32(7), value::TRUE],
@@ -4614,7 +4683,9 @@ fn aarch64_direct_calls_disassemble() {
direct_call: Some(target),
..CallFeedbackSnapshot::default()
}];
- let compiled = compile_for::<crate::asm::aarch64::MacroAssembler>(&snapshot, &|_| true).unwrap();
+ let compiled =
+ compile_for::<crate::asm::aarch64::MacroAssembler>(&snapshot, &|_| true, &mut crate::scratch::Scratch::new())
+ .unwrap();
let text = crate::asm::disassembler::aarch64(&compiled.code[..compiled.data_offset as usize]).join("\n");
// The callee's entry, the runtime's finish helper, and the generic path.
assert!(text.matches("blr").count() >= 3, "{text}");
@@ -4647,7 +4718,9 @@ fn aarch64_inlined_calls_disassemble() {
});
let mut snapshot = snapshot_with_callee(&caller, &callee, function(true, false));
snapshot.runtime = runtime();
- let compiled = compile_for::<crate::asm::aarch64::MacroAssembler>(&snapshot, &|_| true).unwrap();
+ let compiled =
+ compile_for::<crate::asm::aarch64::MacroAssembler>(&snapshot, &|_| true, &mut crate::scratch::Scratch::new())
+ .unwrap();
let text = crate::asm::disassembler::aarch64(&compiled.code[..compiled.data_offset as usize]).join("\n");
// The slow path, the exit stub and the leave stub are the only calls:
// the callee's frame is published and popped inline.
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs b/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs
index cdd1b68892a..f4d580d372d 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs
@@ -349,7 +349,7 @@ fn compile_program(program: &Program, prepare_snapshot: impl FnOnce(&mut Snapsho
snapshot.runtime = marker_runtime();
snapshot.executables[0].feedback.arith = vec![GENERAL_FEEDBACK];
prepare_snapshot(&mut snapshot);
- let compiled = compile_for::<crate::asm::MacroAssembler>(&snapshot, &|_| true)
+ let compiled = compile_for::<crate::asm::MacroAssembler>(&snapshot, &|_| true, &mut crate::scratch::Scratch::new())
.unwrap_or_else(|failure| panic!("compilation failed: {failure:?}"));
(snapshot, compiled)
}
@@ -2745,7 +2745,8 @@ fn modulo_of_random_int32_values() {
let mut snapshot = crate::builder::tests::snapshot_for(&program, layout());
snapshot.runtime = marker_runtime();
snapshot.executables[0].feedback.arith = vec![INT32_RESULTS_FEEDBACK];
- let compiled = compile_for::<crate::asm::MacroAssembler>(&snapshot, &|_| true).unwrap();
+ let compiled =
+ compile_for::<crate::asm::MacroAssembler>(&snapshot, &|_| true, &mut crate::scratch::Scratch::new()).unwrap();
let mut random = crate::regalloc::tests::Random(0x1234_5678_9ABC_DEF1);
for _ in 0..20000 {
let pick = |random: &mut crate::regalloc::tests::Random| {
@@ -2984,11 +2985,15 @@ fn every_fast_path_compiles_for_both_architectures() {
for opcode in [OpCode::InitializeVariableBinding, OpCode::SetLexicalBinding] {
std::sync::Arc::make_mut(&mut snapshot.runtime.slow_paths)[opcode as usize] = marker_put as *const () as u64;
}
- let compiled = compile_for::<crate::asm::aarch64::MacroAssembler>(&snapshot, &|_| true).unwrap();
+ let compiled =
+ compile_for::<crate::asm::aarch64::MacroAssembler>(&snapshot, &|_| true, &mut crate::scratch::Scratch::new())
+ .unwrap();
let text = crate::asm::disassembler::aarch64(&compiled.code[..compiled.data_offset as usize]).join("\n");
// NB: Float32Array stores convert to single precision.
assert!(text.contains("fcvt s31, d"), "{text}");
- let compiled = compile_for::<crate::asm::x86_64::MacroAssembler>(&snapshot, &|_| true).unwrap();
+ let compiled =
+ compile_for::<crate::asm::x86_64::MacroAssembler>(&snapshot, &|_| true, &mut crate::scratch::Scratch::new())
+ .unwrap();
let text = crate::asm::disassembler::x86_64(&compiled.code[..compiled.data_offset as usize]).join("\n");
assert!(text.contains("cvtsd2ss"), "{text}");
}
diff --git a/Libraries/LibJS/JIT/Rust/src/lib.rs b/Libraries/LibJS/JIT/Rust/src/lib.rs
index 42a95f04148..1380429a761 100644
--- a/Libraries/LibJS/JIT/Rust/src/lib.rs
+++ b/Libraries/LibJS/JIT/Rust/src/lib.rs
@@ -11,6 +11,7 @@
//! thread). It calls nothing in the runtime and has no access to the GC heap, so
//! it can run on a worker thread.
+pub mod artifact;
pub mod asm;
pub mod bitset;
pub mod builder;
@@ -25,6 +26,7 @@ pub mod ir;
pub mod options;
pub mod passes;
pub mod regalloc;
+pub mod scratch;
pub mod snapshot;
pub mod sparse_bitset;
@@ -32,8 +34,11 @@ pub mod sparse_bitset;
#[cfg(all(test, windows, not(target_arch = "x86_64")))]
compile_error!("the tests of the JIT run on Windows on x86-64 only");
+use artifact::Artifact;
+use artifact::Tail;
use bytecode::OpCode;
use code::CompiledCode;
+use scratch::Scratch;
use snapshot::Snapshot;
/// Why a compile job did not produce code.
@@ -52,16 +57,28 @@ pub enum CompileFailure {
MissingRuntimeHelper { opcode: Option<OpCode> },
/// The assembler could not finish the code (a branch out of range).
CodeGeneration,
+ /// The compile needs more of something than the compiler has room for.
+ TooLarge,
}
-/// Compiles `snapshot.executables[0]` for the host architecture.
-pub fn compile(snapshot: &Snapshot) -> Result<CompiledCode, CompileFailure> {
- compile_for::<asm::MacroAssembler>(snapshot, &|pc| {
- snapshot
- .executables
- .first()
- .is_none_or(|executable| builder::has_run(executable, pc))
- })
+impl From<ak::ColumnFull> for CompileFailure {
+ fn from(_: ak::ColumnFull) -> Self {
+ Self::TooLarge
+ }
+}
+
+/// Compiles `snapshot.executables[0]` for the host architecture, with the memory of `scratch`.
+pub fn compile(snapshot: &Snapshot, scratch: &mut Scratch) -> Result<CompiledCode, CompileFailure> {
+ compile_for::<asm::MacroAssembler>(
+ snapshot,
+ &|pc| {
+ snapshot
+ .executables
+ .first()
+ .is_none_or(|executable| builder::has_run(executable, pc))
+ },
+ scratch,
+ )
}
/// With `StressOptions::few_registers`, how many registers values get
@@ -73,6 +90,7 @@ const STRESS_EXTRA_REGISTERS: u32 = 2;
pub fn compile_for<M: asm::PortableMacroAssembler>(
snapshot: &Snapshot,
has_run: &dyn Fn(u32) -> bool,
+ scratch: &mut Scratch,
) -> Result<CompiledCode, CompileFailure> {
let mut graph = builder::build_graph_with_feedback(snapshot, has_run)?;
let executable = &snapshot.executables[0];
@@ -99,14 +117,26 @@ pub fn compile_for<M: asm::PortableMacroAssembler>(
regalloc::dump_allocation(&graph, &allocation)
);
}
- let generated = codegen::generate::<M>(
+ let mut generated = codegen::generate::<M>(
&graph,
&allocation,
&snapshot.executables,
&snapshot.runtime,
snapshot.options.stress,
snapshot.options.verify_ir,
+ scratch,
)?;
+ generated.osr_entries.sort_unstable();
+ let layout = scratch.artifact.finish(&Tail {
+ osr_entries: &generated.osr_entries,
+ osr_loop_back_edges: &graph.osr_loop_back_edges,
+ osr_outer_loop_back_edges: &graph.osr_outer_loop_back_edges,
+ uncaught_handlers: &graph.uncaught_handlers,
+ invalidation_patches: &generated.invalidation_patches,
+ embedded_cells: &graph.embedded_cells,
+ dependencies: &graph.dependencies,
+ })?;
+ let words = scratch.artifact.words();
let mut dump = None;
if snapshot.options.dump_ir || snapshot.options.dump_asm || pass_dumps.is_some() {
@@ -122,6 +152,7 @@ pub fn compile_for<M: asm::PortableMacroAssembler>(
&snapshot.runtime,
M::ARCHITECTURE,
&generated,
+ Artifact::new(words, &layout),
));
}
dump = Some(text);
@@ -130,21 +161,15 @@ pub fn compile_for<M: asm::PortableMacroAssembler>(
data_offset: generated.data_offset,
code: generated.code,
entry_offset: generated.entry_offset,
- osr_entries: generated.osr_entries,
- sites: generated.sites,
+ site_index_frame_offset: generated.site_index_frame_offset,
+ register_dump_frame_offset: generated.register_dump_frame_offset,
+ words: words.to_vec(),
+ layout,
coverage: if snapshot.options.coverage {
coverage::coverage_keys(&graph)
} else {
Vec::new()
},
- osr_loop_back_edges: graph.osr_loop_back_edges,
- osr_outer_loop_back_edges: graph.osr_outer_loop_back_edges,
- uncaught_handlers: graph.uncaught_handlers,
- 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,
})
}
@@ -154,6 +179,7 @@ const _: () = {
const fn assert_send<T: Send>() {}
assert_send::<Snapshot>();
assert_send::<CompiledCode>();
+ assert_send::<Scratch>();
};
#[cfg(test)]
@@ -163,7 +189,10 @@ mod tests {
#[test]
fn compile_jobs_can_move_between_threads() {
let snapshot = Snapshot::default();
- let result = std::thread::spawn(move || compile(&snapshot)).join().unwrap();
+ let mut scratch = Scratch::new();
+ let result = std::thread::spawn(move || compile(&snapshot, &mut scratch))
+ .join()
+ .unwrap();
assert!(matches!(
result.unwrap_err(),
CompileFailure::InvalidBytecode { pc: 0, .. }
diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs
index b8bcb7d0390..dc2e3d411bf 100644
--- a/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs
+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs
@@ -5,6 +5,8 @@
*/
use super::*;
+use crate::artifact::Artifact;
+use crate::artifact::Tail;
use crate::builder::tests::build;
use crate::builder::tests::build_with_layout;
use crate::bytecode::FrameLayout;
@@ -12,10 +14,9 @@ use crate::bytecode::Instruction;
use crate::bytecode::Operand;
use crate::bytecode::test_support::*;
use crate::code::ExitKind;
-use crate::code::FrameState as CodeFrameState;
-use crate::code::Site;
use crate::code::SiteKind;
use crate::code::ValueLocation;
+use crate::codegen::sites::SiteSource;
use crate::ir::value;
#[track_caller]
@@ -685,37 +686,44 @@ fn exits_find_constants_registers_and_spilled_values() {
let graph = build_with_layout(&program, test_layout(), &[2]);
let allocation = allocate_and_verify(&graph);
let exit = find_node(&graph, |node| matches!(node.op, Op::Exit { .. }));
- let descriptor = crate::codegen::site(
- &graph,
- &allocation,
- exit,
- SiteKind::Exit(ExitKind::NoFeedback),
- &|slot| -8 * (i32::try_from(slot).unwrap() + 1),
- );
+ let mut scratch = crate::scratch::Scratch::new();
+ scratch.sites.begin(&graph).unwrap();
+ SiteSource {
+ graph: &graph,
+ allocation: &allocation,
+ node: exit,
+ kind: SiteKind::Exit(ExitKind::NoFeedback),
+ stack_slot_offset: &|slot| -8 * (i32::try_from(slot).unwrap() + 1),
+ saves: &[],
+ }
+ .write(&mut scratch.sites, &mut scratch.artifact)
+ .unwrap();
+ let layout = scratch.artifact.finish(&Tail::default()).unwrap();
+ let artifact = Artifact::new(scratch.artifact.words(), &layout);
let argument = find_node(&graph, |node| node.op == Op::LoadSlot { slot: a(0).raw() });
let Some(Location::Register(argument_register)) = allocation.node(argument).output else {
panic!("the argument is in a register");
};
+ assert_eq!(artifact.site_count(), 1);
+ let site = artifact.site(0);
+ assert_eq!(site.kind(), SiteKind::Exit(ExitKind::NoFeedback));
+ assert_eq!(site.frame_count(), 1);
+ assert_eq!(site.object_count(), 0);
+ assert_eq!(site.inlined_frame_bytes(), 0);
+ let frame = site.frame(0);
+ assert_eq!(frame.executable(), 0);
+ assert_eq!(frame.pc(), program.offsets[2]);
+ assert_eq!(frame.mode(), crate::code::ResumeMode::ResumeAt);
assert_eq!(
- descriptor,
- Site {
- kind: SiteKind::Exit(ExitKind::NoFeedback),
- frames: Box::new([CodeFrameState {
- executable: 0,
- pc: program.offsets[2],
- mode: crate::code::ResumeMode::ResumeAt,
- values: Box::new([
- (r(5).raw(), ValueLocation::Constant(value::int32(10))),
- (r(6).raw(), ValueLocation::Register(argument_register, Repr::Tagged)),
- ]),
- in_frame: Box::new([]),
- passed_argument_count: None,
- legacy_arguments: 0..0,
- }]),
- objects: Box::new([]),
- inlined_frame_bytes: 0,
- }
+ frame.values().collect::<Vec<_>>(),
+ [
+ (r(5).raw(), ValueLocation::Constant(value::int32(10))),
+ (r(6).raw(), ValueLocation::Register(argument_register, Repr::Tagged)),
+ ]
);
+ assert!(frame.in_frame().is_empty());
+ assert_eq!(frame.passed_argument_count(), None);
+ assert_eq!(frame.legacy_arguments(), 0..0);
}
#[test]
diff --git a/Libraries/LibJS/JIT/Rust/src/scratch.rs b/Libraries/LibJS/JIT/Rust/src/scratch.rs
new file mode 100644
index 00000000000..8c180a4f91e
--- /dev/null
+++ b/Libraries/LibJS/JIT/Rust/src/scratch.rs
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The memory a thread compiles with.
+
+use crate::artifact::ArtifactWriter;
+use crate::codegen::sites::SiteScratch;
+
+/// What a compile keeps its data in, apart from what the heap still holds of it. A thread that compiles has one, and
+/// every compile of the thread uses it: a compile leaves nothing in it that the next one reads, only the memory.
+/// The memory is in a few ranges of address space that are the scratch's own, so all of it can go back to the system
+/// at any time between two compiles (see `release_memory()`), whatever else the process allocated since.
+pub struct Scratch {
+ pub(crate) artifact: ArtifactWriter,
+ pub(crate) sites: SiteScratch,
+}
+
+impl Default for Scratch {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl Scratch {
+ /// A scratch, which takes no memory before a compile uses it.
+ pub fn new() -> Self {
+ Self {
+ artifact: ArtifactWriter::new(),
+ sites: SiteScratch::new(),
+ }
+ }
+
+ /// Gives the memory of the scratch back to the system. The next compile takes memory again.
+ pub fn release_memory(&mut self) {
+ self.artifact.release_memory();
+ self.sites.release_memory();
+ }
+}
diff --git a/Libraries/LibJS/Rust/src/jit/compile_queue.rs b/Libraries/LibJS/Rust/src/jit/compile_queue.rs
index 336e95c5810..d78f5e9dcaa 100644
--- a/Libraries/LibJS/Rust/src/jit/compile_queue.rs
+++ b/Libraries/LibJS/Rust/src/jit/compile_queue.rs
@@ -7,6 +7,7 @@
//! A VM's share of the compile threads of the process. Only snapshots go to them and only compile results come back: the
//! compiler never sees the heap.
+use std::cell::RefCell;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Receiver, Sender, channel};
use std::sync::{Arc, OnceLock};
@@ -15,6 +16,7 @@ use std::time::Duration;
use libjs_jit::CompileFailure;
use libjs_jit::code::{CompiledCode, Site};
use libjs_jit::compile_pool::{CompilePool, CompilePoolClient};
+use libjs_jit::scratch::Scratch;
use libjs_jit::snapshot::Snapshot;
pub type CompileResult = Result<CompiledCode, CompileFailure>;
@@ -22,18 +24,26 @@ pub type CompileResult = Result<CompiledCode, CompileFailure>;
/// How long a compile thread waits for another job before it gives the memory its jobs freed back to the system.
const IDLE_MEMORY_RELEASE_DELAY: Duration = Duration::from_secs(1);
+thread_local! {
+ /// What this thread compiles with (see `compile()`).
+ static SCRATCH: RefCell<Scratch> = RefCell::new(Scratch::new());
+}
+
+/// Compiles `snapshot` on this thread, with the memory the thread compiles with.
+pub fn compile(snapshot: &Snapshot) -> CompileResult {
+ SCRATCH.with_borrow_mut(|scratch| libjs_jit::compile(snapshot, scratch))
+}
+
/// The compile threads of the process. The first VM to compile decides how many there can be.
fn compile_pool(thread_count: usize) -> &'static Arc<CompilePool> {
static POOL: OnceLock<Arc<CompilePool>> = OnceLock::new();
POOL.get_or_init(|| {
- // NB: A compile can allocate a lot for a while, and the allocator keeps the memory a thread freed until the
- // thread allocates again, which an idle thread may never do.
- CompilePool::new(
- thread_count,
- "LibJS JIT",
- IDLE_MEMORY_RELEASE_DELAY,
- ak::release_unused_allocator_memory,
- )
+ CompilePool::new(thread_count, "LibJS JIT", IDLE_MEMORY_RELEASE_DELAY, || {
+ SCRATCH.with_borrow_mut(Scratch::release_memory);
+ // NB: A compile can allocate a lot for a while, and the allocator keeps the memory a thread freed until
+ // the thread allocates again, which an idle thread may never do.
+ ak::release_unused_allocator_memory();
+ })
})
}
@@ -65,7 +75,7 @@ impl CompileQueue {
self.client.submit(Box::new(move || {
let compiled = {
let _scratch = ak::ScratchHeapScope::enter();
- libjs_jit::compile(&snapshot)
+ compile(&snapshot)
};
// NB: Nearly all a compile allocates is gone when it ends. The code it leaves outlives it, and would keep
// the pages of its temporary data if it stayed there, so it moves out of the scratch heap here.
diff --git a/Libraries/LibJS/Rust/src/jit/tier_up.rs b/Libraries/LibJS/Rust/src/jit/tier_up.rs
index 8ece0737f06..3c1b23781e8 100644
--- a/Libraries/LibJS/Rust/src/jit/tier_up.rs
+++ b/Libraries/LibJS/Rust/src/jit/tier_up.rs
@@ -343,9 +343,9 @@ pub fn tier_up_check(vm: &Vm, encoded_pc: u64) -> i64 {
fn should_install(vm: &Vm, result: &CompileResult) -> bool {
result.as_ref().is_ok_and(|compiled| {
compiled
- .dependencies
- .iter()
- .all(|dependency| super::dependencies::holds(vm, dependency))
+ .artifact()
+ .dependencies()
+ .all(|dependency| super::dependencies::holds(vm, &dependency))
}) && !vm.debugging_enabled()
}
@@ -357,9 +357,9 @@ fn install(
snapshot: SnapshotExecutables,
defer_gc: &DeferGc<'_>,
) {
- let embedded_cells = compiled
- .embedded_cells
- .iter()
+ let artifact = compiled.artifact();
+ let embedded_cells = artifact
+ .embedded_cells()
.map(|cell| {
// SAFETY: The snapshot kept every cell it captured alive, and the code embeds only those.
unsafe { Gc::from_non_null(NonNull::new(cell.0 as *mut CellHeader).expect("embedded cells are not null")) }
@@ -369,18 +369,23 @@ fn install(
let mut code = JitCode::new(
memory,
compiled.entry_offset,
- &compiled.osr_entries,
- compiled.osr_loop_back_edges,
- compiled.sites,
+ &artifact.osr_entries().collect::<Vec<_>>(),
+ artifact.osr_loop_back_edges().iter().collect(),
+ compiled.sites(),
embedded_cells,
snapshot,
defer_gc,
);
- code.set_invalidation(id, compiled.invalidation_patches);
+ let invalidation_patches = artifact
+ .invalidation_patches()
+ .map(|patch| (patch.offset, patch.bytes().to_vec()))
+ .collect();
+ code.set_invalidation(id, invalidation_patches);
code.set_frame_offsets(compiled.site_index_frame_offset, compiled.register_dump_frame_offset);
- code.set_osr_outer_loop_back_edges(compiled.osr_outer_loop_back_edges);
- code.set_uncaught_handlers(compiled.uncaught_handlers);
- vm.jit.dependents.register(vm, executable, id, &compiled.dependencies);
+ 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, possibly
// past the loop the code has an on-stack replacement entry at.
vm.for_each_live_execution_context(|frame| {
@@ -478,7 +483,7 @@ fn compile(
} = capture_snapshot(vm, executable, function, realm, osr_pc, &defer_gc);
if sync {
// NB: Nothing collects garbage while compiling on this thread, so the snapshot's cells stay alive.
- let result = libjs_jit::compile(&snapshot);
+ let result = super::compile_queue::compile(&snapshot);
let memory = should_install(vm, &result).then(|| {
let code = &result.as_ref().expect("the compile succeeded").code;
let name = super::describe_executable(&executable);