Truly independent web browser
LibJS/JIT: Keep the result of a compile out of the heap
Andreas Kling347fbbb339e4
diff --git a/Libraries/LibJS/JIT/Rust/src/artifact.rs b/Libraries/LibJS/JIT/Rust/src/artifact.rsindex a2bea6db9df..3b204462a70 100644--- a/Libraries/LibJS/JIT/Rust/src/artifact.rs+++ b/Libraries/LibJS/JIT/Rust/src/artifact.rs@@ -241,10 +241,11 @@ pub struct ArtifactWriter {objects: Column<u32>,locations: Column<u32>,wide: Column<u32>,- /// The tables as one array, once the code is complete.- words: Column<u32>,}+/// The most words the tables of one compile can have (see `ArtifactWriter::finish()`).+pub const MAX_WORDS: usize = 1 << 25;+impl Default for ArtifactWriter {fn default() -> Self {Self::new()@@ -260,7 +261,6 @@ impl ArtifactWriter {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 {@@ -271,7 +271,6 @@ impl ArtifactWriter {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"),}}@@ -284,7 +283,6 @@ impl ArtifactWriter {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.@@ -297,7 +295,6 @@ impl ArtifactWriter {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.@@ -451,8 +448,9 @@ impl ArtifactWriter {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> {+ /// Completes the tables with `tail`, and writes them as one array into `words` in place of what it holds, with+ /// the layout this returns.+ pub fn finish(&mut self, tail: &Tail<'_>, words: &mut Column<u32>) -> Result<Layout, CompileFailure> {let Self {sites,frames,@@ -461,7 +459,6 @@ impl ArtifactWriter {objects,locations,wide,- words,} = self;words.clear();let mut layout = Layout::default();@@ -545,11 +542,6 @@ impl ArtifactWriter {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`.diff --git a/Libraries/LibJS/JIT/Rust/src/code.rs b/Libraries/LibJS/JIT/Rust/src/code.rsindex a62fae64e53..12f86907370 100644--- a/Libraries/LibJS/JIT/Rust/src/code.rs+++ b/Libraries/LibJS/JIT/Rust/src/code.rs@@ -7,16 +7,20 @@//! 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 ak::Column;+use crate::artifact::Artifact;use crate::artifact::Layout;+use crate::artifact::MAX_WORDS;use crate::snapshot::CellId;-/// Compiled machine code for one executable, not yet installed.-#[derive(Debug, Clone, Default)]+/// Compiled machine code for one executable, not yet installed. The code and its tables are in memory that comes+/// straight from the system, and that serves the next compile into this, so they are no blocks of the heap.+#[derive(Debug)]pub struct CompiledCode {/// Position independent code, apart from absolute helper addresses,/// followed by the constants it loads.- pub code: Vec<u8>,+ pub code: Column<u8>,/// Where the instructions end and the constants begin.pub data_offset: u32,/// Offset of the entry point within `code`.@@ -33,7 +37,7 @@ pub struct CompiledCode {/// 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 words: Column<u32>,pub layout: Layout,/// The debug dumps `CompileOptions` asked for, as text to print.pub dump: Option<String>,@@ -42,7 +46,47 @@ pub struct CompiledCode {pub coverage: Vec<String>,}+impl Default for CompiledCode {+ fn default() -> Self {+ Self::new()+ }+}+impl CompiledCode {+ /// The most bytes the code of one compile can have. A compile that needs more fails.+ const MAX_CODE_BYTES: usize = 1 << 27;++ /// What a compile writes its code into (see `compile()`). It takes no memory before then.+ pub fn new() -> Self {+ Self {+ code: Column::new(Self::MAX_CODE_BYTES, c"JIT compiled code"),+ data_offset: 0,+ entry_offset: 0,+ site_index_frame_offset: 0,+ register_dump_frame_offset: 0,+ words: Column::new(MAX_WORDS, c"JIT compiled tables"),+ layout: Layout::default(),+ dump: None,+ coverage: Vec::new(),+ }+ }++ /// Drops the code. This keeps its memory for the next compile.+ pub fn clear(&mut self) {+ self.code.clear();+ self.words.clear();+ self.layout = Layout::default();+ self.dump = None;+ self.coverage = Vec::new();+ }++ /// Gives memory back to the system: all that is past the code and its tables, and past the room for+ /// `code_bytes` bytes of code and for `words` words of tables.+ pub fn trim(&mut self, code_bytes: usize, words: usize) {+ self.code.trim(code_bytes);+ self.words.trim(words);+ }+/// 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)diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs b/Libraries/LibJS/JIT/Rust/src/codegen/tests.rsindex 758824397e2..dcddca357df 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs@@ -947,7 +947,7 @@ impl Machine {.iter().map(|executable| executable.cell.0).collect();- state.tables.clone_from(&compiled.words);+ state.tables = compiled.words.to_vec();state.layout = compiled.layout;state.exits_taken.clear();}diff --git a/Libraries/LibJS/JIT/Rust/src/lib.rs b/Libraries/LibJS/JIT/Rust/src/lib.rsindex 1380429a761..a09e58d8d26 100644--- a/Libraries/LibJS/JIT/Rust/src/lib.rs+++ b/Libraries/LibJS/JIT/Rust/src/lib.rs@@ -67,9 +67,10 @@ impl From<ak::ColumnFull> for CompileFailure {}}-/// 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>(+/// Compiles `snapshot.executables[0]` for the host architecture with the memory of `scratch`, into `compiled` in+/// place of what it holds. After a failure, `compiled` holds no complete code.+pub fn compile(snapshot: &Snapshot, scratch: &mut Scratch, compiled: &mut CompiledCode) -> Result<(), CompileFailure> {+ compile_into::<asm::MacroAssembler>(snapshot,&|pc| {snapshot@@ -78,6 +79,7 @@ pub fn compile(snapshot: &Snapshot, scratch: &mut Scratch) -> Result<CompiledCod.is_none_or(|executable| builder::has_run(executable, pc))},scratch,+ compiled,)}@@ -85,13 +87,27 @@ pub fn compile(snapshot: &Snapshot, scratch: &mut Scratch) -> Result<CompiledCod/// besides the ones calls use.const STRESS_EXTRA_REGISTERS: u32 = 2;-/// Compiles `snapshot.executables[0]` with the macro assembler `M`. The+/// Compiles `snapshot.executables[0]` with the macro assembler `M`, into memory of the code's own. The/// instructions for which `has_run(pc)` is false become unconditional exits.pub fn compile_for<M: asm::PortableMacroAssembler>(snapshot: &Snapshot,has_run: &dyn Fn(u32) -> bool,scratch: &mut Scratch,) -> Result<CompiledCode, CompileFailure> {+ let mut compiled = CompiledCode::new();+ compile_into::<M>(snapshot, has_run, scratch, &mut compiled)?;+ Ok(compiled)+}++/// Compiles `snapshot.executables[0]` with the macro assembler `M`, like `compile()`. The instructions for which+/// `has_run(pc)` is false become unconditional exits.+fn compile_into<M: asm::PortableMacroAssembler>(+ snapshot: &Snapshot,+ has_run: &dyn Fn(u32) -> bool,+ scratch: &mut Scratch,+ compiled: &mut CompiledCode,+) -> Result<(), CompileFailure> {+ compiled.clear();let mut graph = builder::build_graph_with_feedback(snapshot, has_run)?;let executable = &snapshot.executables[0];let pass_dumps = if snapshot.options.dump_passes {@@ -127,16 +143,19 @@ pub fn compile_for<M: asm::PortableMacroAssembler>(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 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,+ },+ &mut compiled.words,+ )?;+ compiled.code.try_extend_from_slice(&generated.code)?;let mut dump = None;if snapshot.options.dump_ir || snapshot.options.dump_asm || pass_dumps.is_some() {@@ -152,26 +171,23 @@ pub fn compile_for<M: asm::PortableMacroAssembler>(&snapshot.runtime,M::ARCHITECTURE,&generated,- Artifact::new(words, &layout),+ Artifact::new(&compiled.words, &layout),));}dump = Some(text);}- Ok(CompiledCode {- data_offset: generated.data_offset,- code: generated.code,- entry_offset: generated.entry_offset,- 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()- },- dump,- })+ compiled.data_offset = generated.data_offset;+ compiled.entry_offset = generated.entry_offset;+ compiled.site_index_frame_offset = generated.site_index_frame_offset;+ compiled.register_dump_frame_offset = generated.register_dump_frame_offset;+ compiled.layout = layout;+ compiled.dump = dump;+ compiled.coverage = if snapshot.options.coverage {+ coverage::coverage_keys(&graph)+ } else {+ Vec::new()+ };+ Ok(())}// Compile jobs move between threads.@@ -190,12 +206,17 @@ mod tests {fn compile_jobs_can_move_between_threads() {let snapshot = Snapshot::default();let mut scratch = Scratch::new();- let result = std::thread::spawn(move || compile(&snapshot, &mut scratch))- .join()- .unwrap();+ let mut compiled = CompiledCode::new();+ let (result, compiled) = std::thread::spawn(move || {+ let result = compile(&snapshot, &mut scratch, &mut compiled);+ (result, compiled)+ })+ .join()+ .unwrap();assert!(matches!(result.unwrap_err(),CompileFailure::InvalidBytecode { pc: 0, .. }));+ assert!(compiled.code.is_empty());}}diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rsindex dc2e3d411bf..16137775f8b 100644--- a/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs@@ -698,8 +698,9 @@ fn exits_find_constants_registers_and_spilled_values() {}.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 mut words = ak::Column::new(crate::artifact::MAX_WORDS, c"test");+ let layout = scratch.artifact.finish(&Tail::default(), &mut words).unwrap();+ let artifact = Artifact::new(&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");diff --git a/Libraries/LibJS/Rust/src/jit/compile_queue.rs b/Libraries/LibJS/Rust/src/jit/compile_queue.rsindex 1fcd19de303..a8ad8a26e5c 100644--- a/Libraries/LibJS/Rust/src/jit/compile_queue.rs+++ b/Libraries/LibJS/Rust/src/jit/compile_queue.rs@@ -7,10 +7,11 @@//! 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 core::ops::Deref;+use std::cell::{Cell, RefCell};use std::sync::atomic::{AtomicBool, Ordering};use std::sync::mpsc::{Receiver, Sender, channel};-use std::sync::{Arc, OnceLock};+use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError};use std::time::Duration;use libjs_jit::CompileFailure;@@ -19,27 +20,152 @@ use libjs_jit::compile_pool::{CompilePool, CompilePoolClient};use libjs_jit::scratch::Scratch;use libjs_jit::snapshot::Snapshot;-pub type CompileResult = Result<CompiledCode, CompileFailure>;+pub type CompileResult = Result<Compiled, 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);+/// How many results of compiles that nothing uses now keep their memory for the next compiles.+const SPARE_RESULTS: usize = 32;++/// How many bytes of code and words of tables such a result keeps the memory for when a compile takes it: the first+/// step a column grows by. The thread that compiles gives the rest back to the system, so that the thread of a VM,+/// which brings the results back, does not pay for that. A result that keeps more than this keeps pages that the+/// usual compile does not write.+const SPARE_CODE_BYTES: usize = 64 * 1024;+const SPARE_TABLE_WORDS: usize = 8 * 1024;++/// The results that nothing uses now. A compile thread writes the code and the tables of a compile into one, and the+/// thread of the VM that asked for the compile brings it back.+struct Spare {+ results: [Option<CompiledCode>; SPARE_RESULTS],+ /// How many compile threads had a task since they last were idle. The last of them to go idle gives the memory+ /// of the results back to the system.+ active_thread_count: usize,+}++static SPARE: Mutex<Spare> = Mutex::new(Spare {+ results: [const { None }; SPARE_RESULTS],+ active_thread_count: 0,+});++fn spare() -> MutexGuard<'static, Spare> {+ // NB: Nothing leaves the results half changed, so they are good to use after a thread panicked with the lock.+ SPARE.lock().unwrap_or_else(PoisonError::into_inner)+}thread_local! {/// What this thread compiles with (see `compile()`).static SCRATCH: RefCell<Scratch> = RefCell::new(Scratch::new());+ /// Whether this thread is one of `Spare::active_thread_count`.+ static THREAD_IS_ACTIVE: Cell<bool> = const { Cell::new(false) };+}++/// Notes that this compile thread has a job.+fn note_thread_is_active() {+ if !THREAD_IS_ACTIVE.replace(true) {+ spare().active_thread_count += 1;+ }+}++/// The task of a compile thread for a result that came back while all of them were idle (see `Compiled::drop()`),+/// which counted the thread as active already.+fn stay_active_for_late_result() {+ if THREAD_IS_ACTIVE.replace(true) {+ spare().active_thread_count -= 1;+ }+}++/// Notes that this compile thread went idle.+fn note_thread_is_idle() {+ if !THREAD_IS_ACTIVE.replace(false) {+ return;+ }+ let mut spare = spare();+ spare.active_thread_count -= 1;+ if spare.active_thread_count > 0 {+ return;+ }+ let results = core::mem::replace(&mut spare.results, [const { None }; SPARE_RESULTS]);+ drop(spare);+ // NB: The memory goes back to the system here, with the lock released.+ drop(results);}+/// The code of a finished compile, on its way to where it is installed. The code and its tables are in memory that is+/// no block of the heap (see `CompiledCode`), which serves a later compile once this is dropped.+pub struct Compiled {+ // NB: Only drop() takes the code.+ code: Option<CompiledCode>,+}++impl Compiled {+ fn new() -> Self {+ let result = spare().results.iter_mut().find_map(Option::take);+ let code = match result {+ Some(mut code) => {+ code.trim(SPARE_CODE_BYTES, SPARE_TABLE_WORDS);+ code+ }+ None => CompiledCode::default(),+ };+ Self { code: Some(code) }+ }+}++impl Deref for Compiled {+ type Target = CompiledCode;++ fn deref(&self) -> &CompiledCode {+ self.code.as_ref().expect("the code is there until it is dropped")+ }+}++impl Drop for Compiled {+ fn drop(&mut self) {+ let Some(mut code) = self.code.take() else {+ return;+ };+ // NB: This keeps all the memory of the result. The compile that takes it gives back what is too much.+ code.clear();+ let mut spare = spare();+ // NB: With no place left, the memory goes back to the system here.+ let Some(place) = spare.results.iter_mut().find(|place| place.is_none()) else {+ return;+ };+ *place = Some(code);+ if spare.active_thread_count > 0 {+ return;+ }+ // NB: The compile threads are idle, so none of them is going to give the memory of this result back. This+ // makes one of them go idle again, so that the thread of a VM does not pay for that. Without compile+ // threads, the result stays for the next compile on this thread.+ let Some(pool) = POOL.get() else {+ return;+ };+ spare.active_thread_count += 1;+ drop(spare);+ pool.run_unowned(Box::new(stay_active_for_late_result));+ }+}++/// 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);+/// 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))+ let mut compiled = Compiled::new();+ let code = compiled.code.as_mut().expect("the code is there until it is dropped");+ SCRATCH.with_borrow_mut(|scratch| libjs_jit::compile(snapshot, scratch, code))?;+ Ok(compiled)}+/// The compile threads of the process, once a VM has started them.+static POOL: OnceLock<Arc<CompilePool>> = OnceLock::new();+/// 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(|| {CompilePool::new(thread_count, "LibJS JIT", IDLE_MEMORY_RELEASE_DELAY, || {SCRATCH.with_borrow_mut(Scratch::release_memory);+ note_thread_is_idle();// 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();@@ -73,18 +199,14 @@ impl CompileQueue {let result_sender = self.result_sender.clone();let results_pending = Arc::clone(&self.results_pending);self.client.submit(Box::new(move || {- let compiled = {+ note_thread_is_active();+ // NB: Nearly all a compile allocates is gone when it ends, so that goes into the scratch heap. The code it+ // leaves outlives it, and is no block of a heap. Only the texts of the debug options are, which are+ // gone as soon as the code is installed.+ let result = {let _scratch = ak::ScratchHeapScope::enter();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.- #[allow(- clippy::map_clone,- clippy::redundant_clone,- reason = "the copy is what moves the code out of the scratch heap"- )]- let result = compiled.map(|code| code.clone());// NB: A VM that went away has no use for the result, and the thread goes on with other VMs' jobs.if result_sender.send((id, result)).is_ok() {results_pending.store(true, Ordering::Release);diff --git a/Libraries/LibJS/Rust/src/jit/tier_up.rs b/Libraries/LibJS/Rust/src/jit/tier_up.rsindex 3f8f0b3f214..60038315f13 100644--- a/Libraries/LibJS/Rust/src/jit/tier_up.rs+++ b/Libraries/LibJS/Rust/src/jit/tier_up.rs@@ -9,10 +9,8 @@use core::ops::ControlFlow;use core::ptr::NonNull;-use libjs_jit::code::CompiledCode;-use super::code::{CompileState, FRUITLESS_LOOP_CHECKS_AFTER_INSTALL, JitCode, SnapshotExecutable};-use super::compile_queue::CompileResult;+use super::compile_queue::{CompileResult, Compiled};use super::data_memory::DataMemory;use super::executable_memory::ExecutableMemory;use super::snapshot::{CapturedSnapshot, capture_snapshot};@@ -353,7 +351,7 @@ fn should_install(vm: &Vm, result: &CompileResult) -> bool {fn install(vm: &Vm,executable: Gc<Executable>,- compiled: CompiledCode,+ compiled: Compiled,memory: ExecutableMemory,snapshot: SnapshotExecutables,defer_gc: &DeferGc<'_>,@@ -483,7 +481,7 @@ fn compile(let name = super::describe_executable(&executable);ExecutableMemory::allocate(vm.jit.code_allocator(),- &[code.as_slice()],+ &[&code[..]],&[name.as_str()],vm.jit.options.perf_map,)@@ -593,7 +591,7 @@ fn install_compile_results(vm: &Vm, results: Vec<(u64, CompileResult)>, defer_gc.map(|(compile, _)| compile)};let codes: Vec<&[u8]> = installed()- .map(|(_, result)| result.as_ref().expect("the compile succeeded").code.as_slice())+ .map(|(_, result)| &result.as_ref().expect("the compile succeeded").code[..]).collect();let names: Vec<String> = installed().map(|(job, _)| super::describe_executable(&job.executable))