diff --git a/packages/codemode-rust/bench/Cargo.toml b/packages/codemode-rust/bench/Cargo.toml index 61666d41907..c78aded224e 100644 --- a/packages/codemode-rust/bench/Cargo.toml +++ b/packages/codemode-rust/bench/Cargo.toml @@ -11,6 +11,7 @@ serde_json = { version = "1", features = ["float_roundtrip"] } [features] # Per-run heap counts for the memory benchmarks (`examples/gc_bench.rs`). gc-stats = ["psychoscript/gc-stats"] +gc-sticky = ["psychoscript/gc-sticky"] [[example]] name = "gc_bench" diff --git a/packages/codemode-rust/crates/psychoscript/Cargo.toml b/packages/codemode-rust/crates/psychoscript/Cargo.toml index 17da7386530..7f0046f818b 100644 --- a/packages/codemode-rust/crates/psychoscript/Cargo.toml +++ b/packages/codemode-rust/crates/psychoscript/Cargo.toml @@ -10,6 +10,8 @@ description = "Embeddable Rust implementation of the PsychoScript language layer test262 = [] # Per-run heap counts and collection pauses through `Run::heap_stats`, for the memory benchmarks in bench/ only. gc-stats = [] +# A non-moving generational collector with sticky mark bits, on trial (`src/gc_sticky.rs`). +gc-sticky = [] [dependencies] icu_collator = { version = "2.4", default-features = false, features = ["compiled_data"] } diff --git a/packages/codemode-rust/crates/psychoscript/src/gc.rs b/packages/codemode-rust/crates/psychoscript/src/gc.rs index 76c5be5f344..2cba4f778eb 100644 --- a/packages/codemode-rust/crates/psychoscript/src/gc.rs +++ b/packages/codemode-rust/crates/psychoscript/src/gc.rs @@ -23,10 +23,14 @@ pub struct HeapStats { impl Vm { /// Live slots now: objects, cells, strings. A collector that reuses slots subtracts its free ones. pub fn heap_counts(&self) -> (u64, u64, u64) { + #[cfg(feature = "gc-sticky")] + let (objects, cells, strings) = self.free_counts(); + #[cfg(not(feature = "gc-sticky"))] + let (objects, cells, strings) = (0, 0, 0); ( - self.heap.len() as u64, - self.cells.len() as u64, - self.atoms.bufs.len() as u64, + (self.heap.len() - objects) as u64, + (self.cells.len() - cells) as u64, + (self.atoms.bufs.len() - strings) as u64, ) } @@ -43,7 +47,7 @@ impl Vm { } /// Records one collection step of `ns` nanoseconds. - #[allow(dead_code)] // for the collectors under trial + #[cfg_attr(not(feature = "gc-sticky"), allow(dead_code))] pub fn record_pause(&self, ns: u64) { let mut s = self.host.run.stats(); s.steps += 1; diff --git a/packages/codemode-rust/crates/psychoscript/src/gc_sticky.rs b/packages/codemode-rust/crates/psychoscript/src/gc_sticky.rs new file mode 100644 index 00000000000..9ee214a9b00 --- /dev/null +++ b/packages/codemode-rust/crates/psychoscript/src/gc_sticky.rs @@ -0,0 +1,762 @@ +//! A non-moving generational collector with sticky mark bits (`gc-sticky` builds), after Demers et al.: an object +//! marked by one collection stays marked, and so old, until the next major one. A minor collection marks from the +//! roots and from the old objects written since the last collection (the remembered set, which `Heap`'s write +//! barrier fills), walks only young objects, and sweeps only those allocated since. A major collection clears every +//! mark and sweeps the whole heap. Nothing moves, so ids stay stable; freed slots go on free lists. +//! +//! Collection happens only where the run stops with every value in VM structures, as a suspend stops it: `alloc` and +//! the step budget ask for a stop (`suspend_wanted`), and `Vm::run_until_stop` collects there and goes on. A run does +//! no collector work at all until it crosses its first threshold, and an idle run none until it allocates again. + +use std::borrow::Cow; +use std::sync::OnceLock; +use std::time::Instant; + +use crate::object::Obj; +use crate::reach::{Marks, Walk}; +use crate::strings::{NO_GROW, NO_WTF, StrBuf, StrId, Strings}; +use crate::value::{Id, Slot, Value}; +use crate::vm::{MAX_OBJECTS, Vm}; + +/// Collector states of objects, cells and strings. A young slot is unmarked; a free one is on a free list. +pub const YOUNG: u8 = 0; +pub const OLD: u8 = 1; +/// Old, and in the remembered set. +pub const REMEMBERED: u8 = 2; +const FREE: u8 = 3; + +/// Tuning, read once from the environment: the stress mode (`PSYCHOSCRIPT_GC_STRESS=1`) collects as often as it can; +/// `PSYCHOSCRIPT_GC_EVENT=0` turns off the collection at host stops; the other two size the first threshold and the +/// nursery, for measuring. +struct Knobs { + stress: bool, + event: bool, + first: usize, + nursery: usize, +} + +fn knobs() -> &'static Knobs { + static K: OnceLock = OnceLock::new(); + K.get_or_init(|| { + let var = |k: &str| std::env::var(k).ok(); + let num = |k: &str, d: usize| var(k).and_then(|v| v.parse().ok()).unwrap_or(d); + let stress = var("PSYCHOSCRIPT_GC_STRESS").is_some_and(|v| v == "1"); + Knobs { + stress, + event: var("PSYCHOSCRIPT_GC_EVENT").is_none_or(|v| v != "0"), + first: if stress { + 0 + } else { + num("PSYCHOSCRIPT_GC_FIRST", 32_768) + }, + nursery: if stress { + 1 + } else { + num("PSYCHOSCRIPT_GC_NURSERY", 16_384) + }, + } + }) +} + +/// A host stop collects once the run allocated this much since the last collection. +const EVENT_MIN: usize = 4_096; + +/// The heap size at which `alloc` first takes its slow path. +pub fn first_limit() -> usize { + knobs().first.min(MAX_OBJECTS) +} + +/// The run's objects by id. Taking one mutably goes through the write barrier. +pub struct Heap { + objs: Vec, + /// Each object's collector state once the collector started, else empty. + pub(crate) state: Vec, + /// Old objects taken mutably since the last collection, which may now refer to young ones. + pub(crate) remembered: Vec, +} + +impl Heap { + pub fn with_capacity(n: usize) -> Heap { + Heap { + objs: Vec::with_capacity(n), + state: Vec::new(), + remembered: Vec::new(), + } + } + + #[inline] + pub fn push(&mut self, o: Obj) { + self.objs.push(o); + } + + /// Every object, mutably, past the write barrier: only for fields that hold no references. + pub fn iter_mut(&mut self) -> std::slice::IterMut<'_, Obj> { + self.objs.iter_mut() + } + + /// An object replaced without the write barrier, for the collector itself. + pub(crate) fn put(&mut self, id: usize, o: Obj) { + self.objs[id] = o; + } + + #[cold] + #[inline(never)] + fn remember(&mut self, id: usize) { + self.state[id] = REMEMBERED; + self.remembered.push(id as Id); + } +} + +impl std::ops::Deref for Heap { + type Target = [Obj]; + + #[inline(always)] + fn deref(&self) -> &[Obj] { + &self.objs + } +} + +impl> std::ops::Index for Heap { + type Output = I::Output; + + #[inline(always)] + fn index(&self, i: I) -> &I::Output { + &self.objs[i] + } +} + +impl std::ops::IndexMut for Heap { + #[inline(always)] + fn index_mut(&mut self, i: usize) -> &mut Obj { + if self.state.get(i) == Some(&OLD) { + self.remember(i); + } + &mut self.objs[i] + } +} + +impl<'a> IntoIterator for &'a Heap { + type Item = &'a Obj; + type IntoIter = std::slice::Iter<'a, Obj>; + + fn into_iter(self) -> Self::IntoIter { + self.objs.iter() + } +} + +#[derive(Default)] +pub struct Gc { + pub active: bool, + /// A collection is due at the next stop. + pub wanted: bool, + /// The collector alone asked the run to stop, so it goes on once collected. + pub only: bool, + need_major: bool, + young: Vec, + free: Vec, + cell_state: Vec, + cell_young: Vec, + cell_free: Vec, + cell_remembered: Vec, + /// Old slots now, and right after the last major collection. + old: usize, + old_at_major: usize, + /// Atoms are permanent: a minor collection marks only the strings of those made since the last one. + atoms_seen: usize, + collections: u64, +} + +#[derive(Default)] +pub struct StrGc { + pub active: bool, + /// How many strings have their text in each `grow` buffer: one no string uses is dropped. + refs: Vec, + state: Vec, + young: Vec, + free: Vec, + grow_free: Vec, + /// Below this offset the short strings' buffer holds only old strings' text. + arena_mark: usize, +} + +struct Sticky { + objs: Vec, + cells: Vec, + strs: Vec, +} + +impl Marks for Sticky { + fn obj(&mut self, id: Id) -> bool { + mark(&mut self.objs, id as usize) + } + + fn str(&mut self, s: StrId) { + mark(&mut self.strs, s as usize); + } + + fn cell(&mut self, c: u32) -> bool { + mark(&mut self.cells, c as usize) + } +} + +fn mark(state: &mut [u8], i: usize) -> bool { + match state.get_mut(i) { + Some(g) if *g == YOUNG => { + *g = OLD; + true + } + _ => false, + } +} + +impl Vm { + /// `alloc` past its limit: the first time, the collector starts; then every allocation is tracked. + #[cold] + #[inline(never)] + pub(crate) fn alloc_slow(&mut self, obj: Obj) -> Id { + if !self.gc.active { + self.gc_activate(); + } + let id = match self.gc.free.pop() { + Some(id) => { + self.heap.put(id as usize, obj); + self.heap.state[id as usize] = YOUNG; + id + } + None => { + if self.heap.len() >= MAX_OBJECTS { + self.out_of_memory(); + } + self.heap.push(obj); + // A snapshot's restore pushes objects of its own. + self.heap.state.resize(self.heap.len(), YOUNG); + (self.heap.len() - 1) as Id + } + }; + self.gc.young.push(id); + if self.young_total() >= knobs().nursery { + self.gc_request(); + } + id + } + + #[inline] + pub(crate) fn new_cell(&mut self) -> u64 { + if self.gc.active { + return self.new_cell_slow(); + } + self.cells.push(Slot::UNINIT); + self.cells.len() as u64 - 1 + } + + #[cold] + #[inline(never)] + fn new_cell_slow(&mut self) -> u64 { + let c = match self.gc.cell_free.pop() { + Some(c) => { + self.cells[c as usize] = Slot::UNINIT; + self.gc.cell_state[c as usize] = YOUNG; + c + } + None => { + self.cells.push(Slot::UNINIT); + self.gc.cell_state.resize(self.cells.len(), YOUNG); + self.cells.len() as u32 - 1 + } + }; + self.gc.cell_young.push(c); + if self.young_total() >= knobs().nursery { + self.gc_request(); + } + c as u64 + } + + /// The write barrier of a cell about to be set. + #[inline(always)] + pub(crate) fn cell_barrier(&mut self, c: usize) { + if self.gc.cell_state.get(c) == Some(&OLD) { + self.remember_cell(c); + } + } + + #[cold] + #[inline(never)] + fn remember_cell(&mut self, c: usize) { + self.gc.cell_state[c] = REMEMBERED; + self.gc.cell_remembered.push(c as u32); + } + + /// From the step budget's slow path: starts the collector for a run that made many strings or cells, and asks + /// for a collection when the strings made since the last one fill the nursery. + pub(crate) fn gc_poll(&mut self) { + if !self.gc.active { + if self.atoms.bufs.len() >= 2 * knobs().first || self.cells.len() >= knobs().first { + self.gc_activate(); + } + return; + } + if self.young_total() >= knobs().nursery { + self.gc_request(); + } + } + + fn young_total(&self) -> usize { + self.gc.young.len() + self.gc.cell_young.len() + self.atoms.gc.young.len() + } + + fn gc_activate(&mut self) { + self.gc.active = true; + self.gc.need_major = true; + self.alloc_limit = 0; + self.heap.state = vec![YOUNG; self.heap.len()]; + self.gc.cell_state = vec![YOUNG; self.cells.len()]; + self.atoms.gc_activate(); + self.gc_request(); + } + + /// Asks for a stop to collect at. Asked again while one is due, since a host stop's round trip clears the request. + fn gc_request(&mut self) { + self.gc.wanted = true; + if !self.suspend_wanted { + self.suspend_wanted = true; + self.gc.only = true; + } + } + + /// Where the run stopped (`run_until_stop`): collects if a collection is due, or at a host stop after enough + /// allocation. Returns whether the run is to go on, having stopped only to collect. + pub(crate) fn gc_stop(&mut self) -> bool { + if self.suspended && (self.gc.wanted || self.gc.only) { + if self.gc.wanted && self.gc_safe() { + self.collect_auto(); + } + self.gc.wanted = false; + if std::mem::take(&mut self.gc.only) && !self.host.shared.requested() { + self.suspended = false; + self.suspend_wanted = false; + return true; + } + return false; + } + let k = knobs(); + let min = if k.stress { 1 } else { EVENT_MIN }; + if k.event + && self.gc.active + && !self.suspended + && self.outcome.is_none() + && self.fatal.is_none() + && self.young_total() >= min + && self.gc_safe() + { + self.collect_auto(); + } + false + } + + /// A conversion's replay keeps values in Rust until it ends. + fn gc_safe(&self) -> bool { + self.replay_meter.is_none() && self.replay.is_empty() && self.convert_req.is_none() + } + + fn collect_auto(&mut self) { + let g = &self.gc; + let major = g.need_major + || g.old > 2 * g.old_at_major.max(knobs().nursery) + || (knobs().stress && g.collections % 4 == 3); + self.collect(major); + } + + pub(crate) fn collect(&mut self, major: bool) { + let start = Instant::now(); + #[cfg(feature = "gc-stats")] + self.publish_stats(); + let base = self.snapshot_base; + self.heap.state.resize(self.heap.len(), YOUNG); + self.gc.cell_state.resize(self.cells.len(), YOUNG); + self.atoms.gc.state.resize(self.atoms.bufs.len(), YOUNG); + let mut marks = Sticky { + objs: std::mem::take(&mut self.heap.state), + cells: std::mem::take(&mut self.gc.cell_state), + strs: std::mem::take(&mut self.atoms.gc.state), + }; + let remembered = std::mem::take(&mut self.heap.remembered); + let cell_remembered = std::mem::take(&mut self.gc.cell_remembered); + if major { + for g in marks + .objs + .iter_mut() + .chain(marks.cells.iter_mut()) + .chain(marks.strs.iter_mut()) + { + if *g != FREE { + *g = YOUNG; + } + } + } + let mut w = Walk { + heap: &self.heap, + cells: &self.cells, + marks, + todo: Vec::new(), + }; + if major { + // What every fresh run makes is permanent. + for id in 0..base.heap.min(self.heap.len()) { + w.id(id as Id); + } + } else { + w.todo.extend_from_slice(&remembered); + for c in &cell_remembered { + w.val(&self.cells[*c as usize].get()); + } + } + crate::reach::roots(&mut w, self); + let atoms_from = if major { 0 } else { self.gc.atoms_seen }; + self.extra_roots(&mut w, atoms_from); + w.drain(); + let mut marks = w.marks; + if !major { + for id in remembered { + marks.objs[id as usize] = OLD; + } + for c in cell_remembered { + marks.cells[c as usize] = OLD; + } + } + self.heap.state = marks.objs; + self.gc.cell_state = marks.cells; + self.atoms.gc.state = marks.strs; + self.gc.atoms_seen = self.atoms.atom_str.len(); + let marked = start.elapsed().as_nanos() as u64; + let survivors = if major { + self.sweep_all(base.heap, base.cells, base.bufs) + } else { + self.sweep_young() + }; + let g = &mut self.gc; + if major { + g.old = survivors; + g.old_at_major = survivors; + } else { + g.old += survivors; + } + g.need_major = false; + g.wanted = false; + g.collections += 1; + let ns = start.elapsed().as_nanos() as u64; + if log() { + let (objects, cells, strings) = ( + self.heap.len() - self.gc.free.len(), + self.cells.len() - self.gc.cell_free.len(), + self.atoms.bufs.len() - self.atoms.gc.free.len(), + ); + eprintln!( + "gc {} {ns} ns (mark {marked}), {survivors} survivors, live {objects} objects {cells} cells {strings} strings, {} atoms", + if major { "major" } else { "minor" }, + self.atoms.atom_str.len() + ); + } + #[cfg(feature = "gc-stats")] + self.record_pause(ns); + } + + /// Roots `reach::roots` leaves out because a snapshot is taken where they are empty or permanent. + fn extra_roots(&self, w: &mut Walk<'_, Sticky>, atoms_from: usize) { + for q in &self.host.queued { + match q { + crate::host::Queued::Call(p, ..) | crate::host::Queued::Work(p, ..) => w.id(*p), + } + } + let r = &self.realm; + let s = &r.std; + for id in [ + r.object_proto, + r.function_proto, + r.array_proto, + r.string_proto, + r.number_proto, + r.boolean_proto, + r.symbol_proto, + r.error_proto, + r.type_error_proto, + r.range_error_proto, + r.syntax_error_proto, + r.reference_error_proto, + r.aggregate_error_proto, + r.promise_proto, + r.promise_then, + r.map_proto, + r.set_proto, + r.generator_proto, + r.async_generator_proto, + r.generator_function_proto, + r.async_function_proto, + r.async_generator_function_proto, + r.async_from_sync_proto, + r.generator_next, + r.iter_proto, + s.regexp, + s.date, + s.uint8, + s.buffer, + s.text_encoder, + s.text_decoder, + s.weak_map, + s.weak_set, + s.iterator_helper, + s.uri_error, + s.url, + s.params, + s.headers, + ] { + w.id(id); + } + for a in &self.atoms.atom_str[atoms_from.min(self.atoms.atom_str.len())..] { + w.val(&Value::Str(*a)); + } + } + + /// Frees the young slots no mark reached; the rest are old now. Returns how many survived. + fn sweep_young(&mut self) -> usize { + let mut survivors = 0; + let young = std::mem::take(&mut self.gc.young); + for id in &young { + if self.heap.state[*id as usize] == YOUNG { + self.free_obj(*id); + continue; + } + survivors += 1; + } + self.gc.young = reuse(young); + let young = std::mem::take(&mut self.gc.cell_young); + for c in &young { + if self.gc.cell_state[*c as usize] == YOUNG { + self.free_cell(*c); + continue; + } + survivors += 1; + } + self.gc.cell_young = reuse(young); + survivors + self.atoms.sweep_young() + } + + /// Frees every unmarked slot above what a fresh run makes. Returns how many are live. + fn sweep_all(&mut self, heap: usize, cells: usize, bufs: usize) -> usize { + let mut live = 0; + for id in heap..self.heap.len() { + match self.heap.state[id] { + YOUNG => self.free_obj(id as Id), + FREE => {} + _ => live += 1, + } + } + for c in cells..self.cells.len() { + match self.gc.cell_state[c] { + YOUNG => self.free_cell(c as u32), + FREE => {} + _ => live += 1, + } + } + self.gc.young.clear(); + self.gc.cell_young.clear(); + live + self.atoms.sweep_all(bufs) + } + + fn free_obj(&mut self, id: Id) { + self.heap + .put(id as usize, Obj::new(None, crate::object::Kind::Ordinary)); + self.heap.state[id as usize] = FREE; + self.gc.free.push(id); + } + + fn free_cell(&mut self, c: u32) { + self.cells[c as usize] = Slot::UNDEF; + self.gc.cell_state[c as usize] = FREE; + self.gc.cell_free.push(c); + } + + /// Free slots of each kind, which `heap_counts` leaves out. + #[cfg(feature = "gc-stats")] + pub(crate) fn free_counts(&self) -> (usize, usize, usize) { + ( + self.gc.free.len(), + self.gc.cell_free.len(), + self.atoms.gc.free.len(), + ) + } +} + +/// An emptied list's allocation back, unless it grew large. +fn reuse(mut v: Vec) -> Vec { + v.clear(); + if v.capacity() > 4 * knobs().nursery.max(1024) { + v.shrink_to(knobs().nursery); + } + v +} + +/// `PSYCHOSCRIPT_GC_LOG=1` prints each collection, for measuring. +fn log() -> bool { + static ON: OnceLock = OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("PSYCHOSCRIPT_GC_LOG").is_some_and(|v| v == "1")) +} + +fn empty() -> StrBuf { + StrBuf { + s: Cow::Borrowed(""), + ascii: true, + builder: false, + grow: NO_GROW, + len: 0, + aux: NO_WTF, + } +} + +impl Strings { + fn gc_activate(&mut self) { + self.gc.state = vec![YOUNG; self.bufs.len()]; + self.gc.refs = vec![0; self.grow.len()]; + for b in &self.bufs { + if b.grow != NO_GROW { + self.gc.refs[b.grow as usize] += 1; + } + } + self.gc.active = true; + } + + pub(crate) fn push_tracked(&mut self, b: StrBuf) -> StrId { + let id = match self.gc.free.pop() { + Some(id) => { + self.bufs[id as usize] = b; + self.gc.state[id as usize] = YOUNG; + id + } + None => { + self.bufs.push(b); + self.gc.state.resize(self.bufs.len(), YOUNG); + (self.bufs.len() - 1) as StrId + } + }; + self.gc.young.push(id); + id + } + + pub(crate) fn ref_grow(&mut self, g: usize) { + if g >= self.gc.refs.len() { + self.gc.refs.resize(self.grow.len(), 0); + } + self.gc.refs[g] += 1; + } + + /// A string stopped using `grow[g]`: the buffer is dropped once none does, unless it is the short strings'. + pub(crate) fn unref_grow(&mut self, g: usize) { + if !self.gc.active { + return; + } + let r = &mut self.gc.refs[g]; + *r = r.saturating_sub(1); + if *r == 0 && g as u32 != self.arena { + self.grow[g] = String::new(); + self.gc.grow_free.push(g as u32); + } + } + + pub(crate) fn move_grow_ref(&mut self, from: usize, to: usize) { + if self.gc.active { + self.ref_grow(to); + self.unref_grow(from); + } + } + + pub(crate) fn new_grow_tracked(&mut self, s: String) -> usize { + if let Some(g) = self.gc.grow_free.pop() { + self.grow[g as usize] = s; + return g as usize; + } + self.grow.push(s); + self.grow.len() - 1 + } + + /// `a` takes over the string `made` just got, which is left empty for the collector to free. + pub(crate) fn adopt(&mut self, a: StrId, made: StrId, builder: bool) { + let entry = std::mem::replace(&mut self.bufs[made as usize], empty()); + let old = std::mem::replace(&mut self.bufs[a as usize], entry); + self.bufs[a as usize].builder = builder; + if old.grow != NO_GROW { + self.unref_grow(old.grow as usize); + } + } + + fn free_str(&mut self, id: StrId) { + let b = std::mem::replace(&mut self.bufs[id as usize], empty()); + if b.grow != NO_GROW { + self.unref_grow(b.grow as usize); + } else if b.aux != NO_WTF { + self.wtf[b.aux as usize] = Box::default(); + } + self.gc.state[id as usize] = FREE; + self.gc.free.push(id); + } + + fn sweep_young(&mut self) -> usize { + let young = std::mem::take(&mut self.gc.young); + let mut survivors = 0; + for id in &young { + if self.gc.state[*id as usize] == YOUNG { + self.free_str(*id); + continue; + } + survivors += 1; + } + // The short strings' buffer past the mark holds young strings' text only: the survivors' is copied down. + if self.arena != NO_GROW { + let (g, mark) = (self.arena as usize, self.gc.arena_mark); + let mut tail = String::new(); + for id in &young { + let b = &self.bufs[*id as usize]; + if self.gc.state[*id as usize] == FREE + || b.grow as usize != g + || (b.aux + b.len) as usize <= mark + { + continue; + } + let (from, len) = (b.aux as usize, b.len as usize); + let at = mark + tail.len(); + tail.push_str(&self.grow[g][from..from + len]); + self.bufs[*id as usize].aux = at as u32; + } + let arena = &mut self.grow[g]; + arena.truncate(mark); + arena.push_str(&tail); + self.gc.arena_mark = arena.len(); + } + self.gc.young = reuse(young); + survivors + } + + fn sweep_all(&mut self, base: usize) -> usize { + let mut live = 0; + for id in base..self.bufs.len() { + match self.gc.state[id] { + YOUNG => self.free_str(id as StrId), + FREE => {} + _ => live += 1, + } + } + self.gc.young.clear(); + // The short strings' buffer is rebuilt from the text of the strings still in it. + if self.arena != NO_GROW { + let g = self.arena as usize; + let old = std::mem::take(&mut self.grow[g]); + let mut text = String::with_capacity(1024.max(old.len() / 2)); + for b in self.bufs.iter_mut().filter(|b| b.grow as usize == g) { + let from = b.aux as usize; + b.aux = text.len() as u32; + text.push_str(&old[from..from + b.len as usize]); + } + self.gc.arena_mark = text.len(); + self.grow[g] = text; + } + live + } +} diff --git a/packages/codemode-rust/crates/psychoscript/src/lib.rs b/packages/codemode-rust/crates/psychoscript/src/lib.rs index b83fed83196..f9ee8784eee 100644 --- a/packages/codemode-rust/crates/psychoscript/src/lib.rs +++ b/packages/codemode-rust/crates/psychoscript/src/lib.rs @@ -19,6 +19,8 @@ mod diagnostic; mod exec; #[cfg(feature = "gc-stats")] mod gc; +#[cfg(feature = "gc-sticky")] +mod gc_sticky; mod host; mod host_function; mod iteration; diff --git a/packages/codemode-rust/crates/psychoscript/src/object.rs b/packages/codemode-rust/crates/psychoscript/src/object.rs index 9ade77fa850..5124a578197 100644 --- a/packages/codemode-rust/crates/psychoscript/src/object.rs +++ b/packages/codemode-rust/crates/psychoscript/src/object.rs @@ -433,6 +433,13 @@ pub struct Obj { pub visit: u32, } +/// The run's objects by id. In `gc-sticky` builds taking one mutably goes through the collector's write barrier +/// (`gc_sticky::Heap`). +#[cfg(not(feature = "gc-sticky"))] +pub type Heap = Vec; +#[cfg(feature = "gc-sticky")] +pub use crate::gc_sticky::Heap; + impl Obj { pub fn new(proto: Option, kind: Kind) -> Obj { Obj { diff --git a/packages/codemode-rust/crates/psychoscript/src/offload.rs b/packages/codemode-rust/crates/psychoscript/src/offload.rs index 37b35880d2d..5d1e95cdaab 100644 --- a/packages/codemode-rust/crates/psychoscript/src/offload.rs +++ b/packages/codemode-rust/crates/psychoscript/src/offload.rs @@ -174,9 +174,6 @@ fn compute(r: &mut Running, home: &Home) { r.vm.stack_base = &probe as *const u8 as usize; r.vm.stack_budget = RUN_STACK_BUDGET; r.vm.host.offload().home = Some(home.clone()); - let _ = r.vm.continue_frames(); - if !r.vm.suspended { - let _ = r.vm.drive(); - } + r.vm.run_until_stop(); r.vm.host.offload().home = None; } diff --git a/packages/codemode-rust/crates/psychoscript/src/program.rs b/packages/codemode-rust/crates/psychoscript/src/program.rs index f12c5bdfd8d..6e0c8216a77 100644 --- a/packages/codemode-rust/crates/psychoscript/src/program.rs +++ b/packages/codemode-rust/crates/psychoscript/src/program.rs @@ -367,10 +367,7 @@ impl<'a> Program<'a> { worker.compute(r); continue; } - let _ = r.vm.continue_frames(); - if !r.vm.suspended { - let _ = r.vm.drive(); - } + r.vm.run_until_stop(); #[cfg(feature = "gc-stats")] r.vm.publish_stats(); if let Some(o) = &mut r.vm.host.offload { diff --git a/packages/codemode-rust/crates/psychoscript/src/reach.rs b/packages/codemode-rust/crates/psychoscript/src/reach.rs index c73a74e83ef..9817346069a 100644 --- a/packages/codemode-rust/crates/psychoscript/src/reach.rs +++ b/packages/codemode-rust/crates/psychoscript/src/reach.rs @@ -1,29 +1,72 @@ //! Which heap objects a run can still reach, for a snapshot: the reference saves only what is reachable, so a value -//! the program dropped never stops a resume. Every cell, stack slot and coroutine counts as a root. +//! the program dropped never stops a resume. Every cell, stack slot and coroutine counts as a root. A collector walks +//! the same roots with marks of its own (`Marks`). use crate::object::*; +use crate::strings::StrId; use crate::value::{Id, Slot, Value}; use crate::vm::{Frame, Job, Reaction, SavedFrame, Vm}; -struct Walk<'v> { - heap: &'v [Obj], - seen: Vec, - todo: Vec, +/// What a walk records as it meets things. +pub(crate) trait Marks { + /// Marks an object: whether its fields are still to be walked. + fn obj(&mut self, id: Id) -> bool; + fn str(&mut self, _s: StrId) {} + /// Marks a closure cell: whether its value is still to be walked. + fn cell(&mut self, _c: u32) -> bool { + false + } } -impl Walk<'_> { - fn id(&mut self, id: Id) { - if let Some(seen) = self.seen.get_mut(id as usize) - && !*seen - { - *seen = true; +struct Seen(Vec); + +impl Marks for Seen { + fn obj(&mut self, id: Id) -> bool { + match self.0.get_mut(id as usize) { + Some(seen) if !*seen => { + *seen = true; + true + } + _ => false, + } + } +} + +pub(crate) struct Walk<'v, M> { + pub heap: &'v [Obj], + pub cells: &'v [Slot], + pub marks: M, + pub todo: Vec, +} + +impl Walk<'_, M> { + pub fn id(&mut self, id: Id) { + if self.marks.obj(id) { self.todo.push(id); } } - fn val(&mut self, v: &Value) { - if let Value::Obj(id) = v { - self.id(*id); + pub fn val(&mut self, v: &Value) { + match v { + Value::Obj(id) => self.id(*id), + Value::Str(s) => self.marks.str(*s), + _ => {} + } + } + + pub fn cell(&mut self, c: u32) { + if self.marks.cell(c) + && let Some(s) = self.cells.get(c as usize) + { + self.val(&s.get()); + } + } + + /// Walks the objects met so far and everything they reach. + pub fn drain(&mut self) { + let heap = self.heap; + while let Some(id) = self.todo.pop() { + self.object(&heap[id as usize]); } } @@ -33,14 +76,23 @@ impl Walk<'_> { } } + /// A local captured by a closure holds its cell's raw index, which reads as a tiny number: any slot that could be + /// one counts as one, which at worst keeps a cell longer. fn slots(&mut self, slots: &[Slot]) { for s in slots { + if s.0 < self.cells.len() as u64 { + self.cell(s.0 as u32); + continue; + } self.val(&s.get()); } } fn frame(&mut self, f: &Frame) { self.vals(f.extra.iter()); + for c in f.upvals.iter() { + self.cell(*c); + } if let crate::vm::FrameKind::Generator(g, _) = f.kind { self.id(g); } @@ -124,8 +176,8 @@ impl Walk<'_> { | Kind::Bytes(_) | Kind::TextDecoder(_) | Kind::Headers(_) - | Kind::StrIter { .. } | Kind::Live(_) => {} + Kind::StrIter { s, .. } => self.marks.str(*s), Kind::Namespace(ns) => { if !ns.is_root() { self.id(ns.parent); @@ -133,7 +185,12 @@ impl Walk<'_> { } Kind::Array(items) | Kind::Arguments(items) => self.vals(items.iter()), Kind::ListIter { items, .. } => self.vals(items.iter()), - Kind::Closure(c) => self.val(&c.this), + Kind::Closure(c) => { + self.val(&c.this); + for u in c.upvals.iter() { + self.cell(*u); + } + } Kind::Native { data, .. } => self.val(data), Kind::Bound(b) => { self.val(&b.0); @@ -167,6 +224,7 @@ impl Walk<'_> { use crate::builtins::iterator::HelperOp; self.val(&h.iter); self.val(&h.next); + self.val(&h.site); match &h.op { HelperOp::Map(f) | HelperOp::Filter(f) => self.val(f), HelperOp::FlatMap(f, inner) => { @@ -204,13 +262,21 @@ impl Walk<'_> { pub fn reachable(vm: &Vm) -> Vec { let mut w = Walk { heap: &vm.heap, - seen: vec![false; vm.heap.len()], + cells: &vm.cells, + marks: Seen(vec![false; vm.heap.len()]), todo: Vec::new(), }; for id in 0..vm.snapshot_base.heap.min(vm.heap.len()) { w.id(id as Id); } w.slots(&vm.cells); + roots(&mut w, vm); + w.drain(); + w.marks.0 +} + +/// Meets what the run holds outside its heap, but for its cells and the objects every fresh run makes. +pub(crate) fn roots(w: &mut Walk<'_, M>, vm: &Vm) { w.slots(&vm.stack); for f in &vm.frames { w.frame(f); @@ -271,9 +337,4 @@ pub fn reachable(vm: &Vm) -> Vec { if let Some(o) = &vm.outcome { w.outcome(o); } - while let Some(id) = w.todo.pop() { - let o = &w.heap[id as usize]; - w.object(o); - } - w.seen } diff --git a/packages/codemode-rust/crates/psychoscript/src/strings.rs b/packages/codemode-rust/crates/psychoscript/src/strings.rs index a13902c6d5e..e6133cd8c7f 100644 --- a/packages/codemode-rust/crates/psychoscript/src/strings.rs +++ b/packages/codemode-rust/crates/psychoscript/src/strings.rs @@ -37,15 +37,15 @@ pub struct StrBuf { /// Only one local slot holds this string, so `+=` may append in place. pub builder: bool, /// When not `NO_GROW`, the text is the `len` bytes at `aux` in `Strings::grow[grow]` rather than `s`. - grow: u32, - len: u32, + pub(crate) grow: u32, + pub(crate) len: u32, /// For a string in a `grow` buffer, its offset there. Otherwise, when not `NO_WTF`, the text is a carrier and /// `Strings::wtf[aux]` holds the code units. - aux: u32, + pub(crate) aux: u32, } -const NO_GROW: u32 = u32::MAX; -const NO_WTF: u32 = u32::MAX; +pub(crate) const NO_GROW: u32 = u32::MAX; +pub(crate) const NO_WTF: u32 = u32::MAX; /// Starts an escape in a carrier text. U+10FFFF is a noncharacter, so real text almost never holds one. pub const MARK: char = '\u{10FFFF}'; @@ -160,13 +160,15 @@ const GROW_MIN: usize = 64; pub struct Strings { pub bufs: Vec, - grow: Vec, + pub(crate) grow: Vec, /// The `grow` buffer short strings are appended to, so making one allocates nothing of its own. - arena: u32, - wtf: Vec>, + pub(crate) arena: u32, + pub(crate) wtf: Vec>, map: FxHashMap, Atom>, - atom_str: Vec, + pub(crate) atom_str: Vec, atom_index: Vec, + #[cfg(feature = "gc-sticky")] + pub(crate) gc: crate::gc_sticky::StrGc, } /// A borrowed string with its ASCII flag and, for a carrier, its code units, for code-unit arithmetic. @@ -187,6 +189,8 @@ impl Strings { map: FxHashMap::default(), atom_str: Vec::new(), atom_index: Vec::new(), + #[cfg(feature = "gc-sticky")] + gc: Default::default(), }; for name in ["Symbol(Symbol.iterator)", "Symbol(Symbol.asyncIterator)"] { let id = s.alloc_static(name); @@ -239,14 +243,19 @@ impl Strings { } fn push(&mut self, s: Cow<'static, str>, ascii: bool) -> StrId { - self.bufs.push(StrBuf { + let b = StrBuf { s, ascii, builder: false, grow: NO_GROW, len: 0, aux: NO_WTF, - }); + }; + #[cfg(feature = "gc-sticky")] + if self.gc.active { + return self.push_tracked(b); + } + self.bufs.push(b); (self.bufs.len() - 1) as StrId } @@ -305,17 +314,33 @@ impl Strings { fn push_grown(&mut self, buf: String, g: usize, start: usize, ascii: bool) -> StrId { let len = (buf.len() - start) as u32; self.grow[g] = buf; - self.bufs.push(StrBuf { + let b = StrBuf { s: Cow::Borrowed(""), ascii, builder: false, grow: g as u32, len, aux: start as u32, - }); + }; + #[cfg(feature = "gc-sticky")] + if self.gc.active { + self.ref_grow(g); + return self.push_tracked(b); + } + self.bufs.push(b); (self.bufs.len() - 1) as StrId } + /// A new `grow` buffer's index. + fn new_grow(&mut self, s: String) -> usize { + #[cfg(feature = "gc-sticky")] + if self.gc.active { + return self.new_grow_tracked(s); + } + self.grow.push(s); + self.grow.len() - 1 + } + pub fn concat(&mut self, parts: &[StrId]) -> StrId { let Some((&first, rest)) = parts.split_first() else { return self.alloc_static(""); @@ -333,8 +358,7 @@ impl Strings { if f.grow != NO_GROW && self.grow[f.grow as usize].len() == (f.aux + f.len) as usize { (f.grow as usize, f.aux as usize, rest) } else if total >= GROW_MIN { - self.grow.push(String::with_capacity(total * 2)); - (self.grow.len() - 1, 0, parts) + (self.new_grow(String::with_capacity(total * 2)), 0, parts) } else { let g = self.arena(); (g, self.grow[g].len(), parts) @@ -368,6 +392,8 @@ impl Strings { let ab = &self.bufs[a as usize]; // A builder made short leaves the short strings' buffer for text of its own, which it extends from now on. if ab.grow == self.arena && ab.grow != NO_GROW { + #[cfg(feature = "gc-sticky")] + self.unref_grow(ab.grow as usize); let own = self.get(a).to_owned(); let entry = &mut self.bufs[a as usize]; entry.s = Cow::Owned(own); @@ -388,9 +414,11 @@ impl Strings { if self.grow[g].len() != (ab.aux + ab.len) as usize { let mut s = String::with_capacity(ab.len as usize * 2); s.push_str(self.get(a)); - self.grow.push(s); + let n = self.new_grow(s); + #[cfg(feature = "gc-sticky")] + self.move_grow_ref(g, n); let entry = &mut self.bufs[a as usize]; - entry.grow = (self.grow.len() - 1) as u32; + entry.grow = n as u32; entry.aux = 0; return self.push_in_place(a, b); } @@ -409,6 +437,9 @@ impl Strings { let joined = format!("{}{}", self.get(a), self.get(b)); let made = self.alloc(joined); let builder = self.bufs[a as usize].builder; + #[cfg(feature = "gc-sticky")] + return self.adopt(a, made, builder); + #[cfg(not(feature = "gc-sticky"))] if let Some(mut entry) = self.bufs.pop().filter(|_| made as usize == self.bufs.len()) { entry.builder = builder; self.bufs[a as usize] = entry; diff --git a/packages/codemode-rust/crates/psychoscript/src/vm.rs b/packages/codemode-rust/crates/psychoscript/src/vm.rs index 82099967af6..7e7ba5f4184 100644 --- a/packages/codemode-rust/crates/psychoscript/src/vm.rs +++ b/packages/codemode-rust/crates/psychoscript/src/vm.rs @@ -19,7 +19,7 @@ pub type Res = Result; pub type NativeFn = fn(&mut Vm, Value, &[Value], Id) -> Res; pub const MAX_DEPTH: usize = 10_000; -const MAX_OBJECTS: usize = 2_000_000; +pub(crate) const MAX_OBJECTS: usize = 2_000_000; pub(crate) const MAX_STRINGS: usize = 4_000_000; const MAX_NATIVE_DEPTH: usize = 400; pub(crate) const FUEL: i32 = 20_000; @@ -222,7 +222,7 @@ pub struct Realm { } pub struct Vm { - pub heap: Vec, + pub heap: Heap, pub cells: Vec, pub atoms: Strings, pub stack: Vec, @@ -301,6 +301,11 @@ pub struct Vm { /// The answers a rerun takes in order, and what the meter was when it started. pub(crate) replay: VecDeque, pub(crate) replay_meter: Option, + /// The collector's state, and the heap size at which `alloc` takes its slow path. + #[cfg(feature = "gc-sticky")] + pub(crate) gc: crate::gc_sticky::Gc, + #[cfg(feature = "gc-sticky")] + pub(crate) alloc_limit: usize, } impl Vm { @@ -334,7 +339,7 @@ impl Vm { .map(|d| d.as_nanos() as u64) .unwrap_or(0x9e3779b97f4a7c15); Vm { - heap: Vec::with_capacity(1024), + heap: Heap::with_capacity(1024), cells: Vec::new(), atoms, stack: Vec::with_capacity(1024), @@ -386,6 +391,10 @@ impl Vm { convert_req: None, replay: VecDeque::new(), replay_meter: None, + #[cfg(feature = "gc-sticky")] + gc: crate::gc_sticky::Gc::default(), + #[cfg(feature = "gc-sticky")] + alloc_limit: crate::gc_sticky::first_limit(), } } @@ -411,6 +420,11 @@ impl Vm { #[inline] pub fn alloc(&mut self, obj: Obj) -> Id { + #[cfg(feature = "gc-sticky")] + if self.heap.len() >= self.alloc_limit { + return self.alloc_slow(obj); + } + #[cfg(not(feature = "gc-sticky"))] if self.heap.len() >= MAX_OBJECTS { self.out_of_memory(); } @@ -601,6 +615,8 @@ impl Vm { self.handover(); } } + #[cfg(feature = "gc-sticky")] + self.gc_poll(); let mut r = Ok(()); if check && !replaying && self.host.meter.fuel <= 0 { self.host.meter.fuel = FUEL; @@ -781,7 +797,7 @@ impl Vm { } if self.json_walks == u32::MAX { self.json_walks = 0; - for o in &mut self.heap { + for o in self.heap.iter_mut() { o.visit = 0; } } @@ -899,6 +915,13 @@ impl Vm { if self.host.shared.requested() { self.suspend_wanted = true; } + #[cfg(feature = "gc-sticky")] + if self.roundtrip_every > 0 + || self.host.offload.as_ref().is_some_and(|o| o.due) + || self.host.shared.requested() + { + self.gc.only = false; + } } /// Starts counting steps for the round-trip test mode. @@ -2572,6 +2595,22 @@ impl Vm { r } + /// Continues the run until it stops: for the host, for a suspend, or at its end. + #[cfg_attr(not(feature = "gc-sticky"), allow(clippy::never_loop))] + pub fn run_until_stop(&mut self) { + loop { + let _ = self.continue_frames(); + if !self.suspended { + let _ = self.drive(); + } + #[cfg(feature = "gc-sticky")] + if self.gc_stop() { + continue; + } + return; + } + } + /// Continues frames a suspend left on the job stack, as the entry point that started them would have. pub fn continue_frames(&mut self) -> Result<(), Value> { if self.frames.is_empty() { @@ -2801,8 +2840,13 @@ impl Vm { self.stack.push(v); } Op::NewCell(i) => { - self.cells.push(Slot::UNINIT); - let c = self.cells.len() as u64 - 1; + #[cfg(feature = "gc-sticky")] + let c = self.new_cell(); + #[cfg(not(feature = "gc-sticky"))] + let c = { + self.cells.push(Slot::UNINIT); + self.cells.len() as u64 - 1 + }; self.stack[base + i as usize] = Slot(c); } Op::GetCell(i) => { @@ -2821,6 +2865,8 @@ impl Vm { Op::SetCell(i) => { let v = self.stack.pop().unwrap_or_default(); let c = self.stack[base + i as usize].0 as usize; + #[cfg(feature = "gc-sticky")] + self.cell_barrier(c); if let Some(cell) = self.cells.get_mut(c) { *cell = v; } @@ -2841,6 +2887,8 @@ impl Vm { Op::SetUpval(i) => { let v = self.stack.pop().unwrap_or_default(); let c = self.frames[fi].upvals[i as usize]; + #[cfg(feature = "gc-sticky")] + self.cell_barrier(c as usize); self.cells[c as usize] = v; } Op::GetGlobal(g) => {