Skip to content

Commit 789b94f

Browse files
hearnadamkommander
andauthored
perf(rust): the fresh runtime is made once per process and copied by each run (#85)
* perf(rust): the fresh runtime is made once per process and copied by each run A run built about 290 built-in objects, 380 strings and 250 names from scratch, whatever its program: 352k instructions, most of what a short program cost. builtins::image() makes them once. Every compile starts from its strings (Strings::fresh), so they have the same ids in every run, and Vm::new copies its heap instead of running setup. A VM whose strings did not start from the image is still set up from scratch, as the image is. Also sizes a fresh run's arenas for what it makes (286 objects, not room for 1,024), and has the compiler note whether the program names 'constructor', which the string table no longer says. examples/corpus: 15.88M to 11.91M instructions; setup 352k to 100k. return 1: 360k to 111k. Idle waiting run: 154.7 to 84.5 KB. * fix(rust): snapshot format 3, so a state saved by 0.1.2 or earlier is refused instead of misread Program strings now come after the image's (Strings::fresh), so a state from an earlier build can decode a string id as a different string while its build id still matches. The format bump changes the build id too. --------- Co-authored-by: Sebastian Herrlinger <hasta84@gmail.com>
1 parent fa82fd6 commit 789b94f

9 files changed

Lines changed: 179 additions & 19 deletions

File tree

‎rust/crates/psychoscript/src/builtins/mod.rs‎

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,53 @@ use crate::object::*;
2525
use crate::value::{Id, Value};
2626
use crate::vm::{NativeFn, Res, Vm};
2727

28+
/// The fresh runtime, made once for the process: what `Vm::new_scratch` and `Vm::setup` make before any program or
29+
/// host global, which is the same for every run. A run copies it instead of making it again, which was most of what
30+
/// a short program cost. Its strings come first in every run's (`Strings::fresh`), so its atoms and string ids are
31+
/// the same in all of them.
32+
pub(crate) struct Image {
33+
pub atoms: crate::strings::Strings,
34+
pub heap: crate::collector::Heap,
35+
pub realm: crate::vm::Realm,
36+
pub names: crate::vm::Names,
37+
pub global_map: rustc_hash::FxHashMap<Atom, Value>,
38+
pub char_strs: Vec<crate::strings::StrId>,
39+
}
40+
41+
impl Image {
42+
/// Whether `atoms` started as this image's: its strings and atoms are the first of them.
43+
pub fn seeds(&self, atoms: &crate::strings::Strings) -> bool {
44+
let (bufs, count) = self.atoms.counts();
45+
let (have_bufs, have) = atoms.counts();
46+
have_bufs >= bufs
47+
&& have >= count
48+
&& atoms.lookup("length") == Some(self.names.length)
49+
&& atoms.lookup("buffer") == Some(self.names.buffer)
50+
}
51+
}
52+
53+
pub(crate) fn image() -> &'static Image {
54+
static IMAGE: std::sync::OnceLock<Image> = std::sync::OnceLock::new();
55+
IMAGE.get_or_init(|| {
56+
let mut vm = Vm::new_scratch(
57+
crate::host::RunHost::bare(),
58+
crate::Limits::default(),
59+
crate::strings::Strings::new(),
60+
);
61+
vm.setup();
62+
Image {
63+
atoms: std::mem::replace(&mut vm.atoms, crate::strings::Strings::new()),
64+
heap: vm.heap.clone_base(),
65+
realm: vm.realm.clone(),
66+
names: vm.names.clone(),
67+
global_map: std::mem::take(&mut vm.global_map),
68+
char_strs: std::mem::take(&mut vm.char_strs),
69+
}
70+
})
71+
}
72+
2873
/// Prototypes of the standard-library kinds beyond the core ones in `Realm`.
29-
#[derive(Default)]
74+
#[derive(Clone, Default)]
3075
pub struct StdProtos {
3176
pub regexp: Id,
3277
pub date: Id,
@@ -342,7 +387,11 @@ impl Vm {
342387
Value::Obj(id)
343388
}
344389

390+
/// Makes the fresh runtime's built-ins, unless the VM was made with them (`Vm::new` from the image).
345391
pub fn setup(&mut self) {
392+
if !self.heap.is_empty() {
393+
return;
394+
}
346395
let object_proto = self.alloc(Obj::new(None, Kind::Ordinary));
347396
self.realm.object_proto = object_proto;
348397
// Function.prototype is itself a function that accepts anything and returns undefined, as in JS.

‎rust/crates/psychoscript/src/collector.rs‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,16 @@ impl Heap {
118118
}
119119
}
120120

121+
/// A copy of a fresh runtime's heap, which holds only what `Obj::clone_base` copies, with room for a small
122+
/// program's own objects.
123+
pub(crate) fn clone_base(&self) -> Heap {
124+
let mut heap = Heap::with_capacity(self.len() + 34);
125+
for o in self.iter() {
126+
heap.push(o.clone_base());
127+
}
128+
heap
129+
}
130+
121131
/// The bytes of storage object `i` (`Kind::Storage`), past the barrier: bytes hold no references, so writing them
122132
/// changes nothing marking must see.
123133
#[inline(always)]

‎rust/crates/psychoscript/src/compiler.rs‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,7 @@ fn compile_as(source: &str, atoms: &mut Strings, internal: bool) -> R<Program> {
170170
bigints: c.bigints,
171171
globals: c.globals,
172172
templates: c.templates,
173-
names_constructor: c.atoms.lookup("constructor").is_some(),
173+
names_constructor: c.names_constructor,
174174
})
175175
}
176176

@@ -1205,6 +1205,9 @@ struct Compiler<'a, 's> {
12051205
readonly: FxHashSet<SymbolId>,
12061206
/// The name `await` names were renamed to for parsing (see `rename_await_names`), which compiles as `await`.
12071207
await_alias: Option<String>,
1208+
/// The program names `constructor` as a key or a binding (`Program::names_constructor`). Its strings start as
1209+
/// the image's, which hold the name already, so they do not say.
1210+
names_constructor: bool,
12081211
/// Parameters of a function with parameter expressions, which are in their TDZ until bound in order.
12091212
param_tdz: FxHashSet<SymbolId>,
12101213
/// Function scopes whose `arguments` is read, and whether an arrow inside reads it.
@@ -1256,6 +1259,7 @@ impl<'a, 's> Compiler<'a, 's> {
12561259
switch_scopes: FxHashSet::default(),
12571260
readonly: FxHashSet::default(),
12581261
await_alias: None,
1262+
names_constructor: false,
12591263
param_tdz: FxHashSet::default(),
12601264
args_owner: FxHashMap::default(),
12611265
unbound: FxHashSet::default(),
@@ -1462,6 +1466,7 @@ impl<'a, 's> Compiler<'a, 's> {
14621466

14631467
fn atom(&mut self, s: &str) -> Atom {
14641468
let s = self.real_name(s);
1469+
self.names_constructor |= s == "constructor";
14651470
self.atoms.intern(s)
14661471
}
14671472

‎rust/crates/psychoscript/src/object.rs‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -654,6 +654,39 @@ impl Obj {
654654
}
655655
}
656656

657+
/// A copy of an object of the fresh runtime, whose kinds are the few with nothing a run owns alone.
658+
pub(crate) fn clone_base(&self) -> Obj {
659+
let kind = match &self.kind {
660+
Kind::Ordinary => Kind::Ordinary,
661+
Kind::Array(items) => Kind::Array(items.clone()),
662+
Kind::Native {
663+
f,
664+
data,
665+
name,
666+
length,
667+
ctor,
668+
} => Kind::Native {
669+
f: *f,
670+
data: *data,
671+
name: *name,
672+
length: *length,
673+
ctor: *ctor,
674+
},
675+
Kind::Accessor(a) => Kind::Accessor(a.clone()),
676+
Kind::Namespace(n) => Kind::Namespace(*n),
677+
Kind::Error(None) => Kind::Error(None),
678+
Kind::Date(t) => Kind::Date(*t),
679+
_ => unreachable!("a fresh runtime makes no object of this kind"),
680+
};
681+
Obj {
682+
proto: self.proto,
683+
props: self.props.clone(),
684+
kind,
685+
flags: self.flags,
686+
visit: 0,
687+
}
688+
}
689+
657690
pub fn is_callable(&self) -> bool {
658691
match &self.kind {
659692
Kind::Closure(_) | Kind::Native { .. } | Kind::Bound(_) => true,

‎rust/crates/psychoscript/src/run.rs‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ impl<'a> From<&'a Compiled> for Code<'a> {
8383

8484
/// Parses and compiles a program, or the diagnostic a run of it would fail with before running anything.
8585
pub fn compile_program(code: &str) -> Result<Compiled, Diagnostic> {
86-
let mut atoms = Strings::new();
86+
let mut atoms = Strings::fresh();
8787
let program = compile(code, &mut atoms).map_err(|e| compile_diagnostic(code, e))?;
8888
Ok(Compiled(Arc::new(CompiledProgram {
8989
code: Arc::from(code),
@@ -166,7 +166,7 @@ pub fn start(
166166
let (code, mut program, atoms) = match code {
167167
Code::Compiled(c) => (c.0.code.clone(), c.0.program.clone(), c.0.atoms.clone()),
168168
Code::Source(code) => {
169-
let mut atoms = Strings::new();
169+
let mut atoms = Strings::fresh();
170170
match compile(code, &mut atoms) {
171171
Ok(p) => (Arc::from(code), p, atoms),
172172
Err(e) => return Err(Box::new(failed(compile_diagnostic(code, e)))),
@@ -211,7 +211,7 @@ pub fn start_for_resume(
211211
restored: crate::snapshot::Restored,
212212
) -> Result<Resumed, crate::snapshot::SnapshotError> {
213213
let code = restored.code;
214-
let mut atoms = Strings::new();
214+
let mut atoms = Strings::fresh();
215215
let mut program = compile(&code, &mut atoms).map_err(|_| {
216216
crate::snapshot::SnapshotError::new(
217217
"Source main does not compile in this build, so it can't resume.",

‎rust/crates/psychoscript/src/snapshot.rs‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ use crate::vm::{
3030
use crate::{DiagnosticKind, Json, Limits};
3131

3232
/// Bumped whenever the shape of saved state changes.
33-
pub const FORMAT: u64 = 2;
33+
pub const FORMAT: u64 = 3;
3434

3535
/// A run's saved state: plain JSON, with a `header` that says where it can resume. A state changed since it was saved
3636
/// is refused, by a hash of it in the header; the hash guards against damage, not forgery, so resume only states your
@@ -120,7 +120,7 @@ fn natives() -> &'static Natives {
120120
let mut vm = Vm::new(
121121
host::RunHost::bare(),
122122
Limits::default(),
123-
crate::strings::Strings::new(),
123+
crate::strings::Strings::fresh(),
124124
);
125125
vm.setup();
126126
let base = vm.heap.len();
@@ -391,7 +391,7 @@ pub fn capture(vm: &Vm, c: &Capture) -> Result<Snapshot, Refusal> {
391391
};
392392
let state = enc.state(c).map_err(|e| Refusal::Other(e.message))?;
393393
let base = vm.snapshot_base;
394-
let program = crate::run::compile(c.code, &mut crate::strings::Strings::new())
394+
let program = crate::run::compile(c.code, &mut crate::strings::Strings::fresh())
395395
.map_err(|e| Refusal::Other(e.message))?;
396396
let limits = *vm.limits;
397397
let metadata = vm.host.run.metadata();
@@ -947,7 +947,7 @@ fn hex_bytes(s: &str) -> R<Vec<u8>> {
947947

948948
/// Each object of a fresh run's base, encoded, to see which ones the run changed.
949949
fn baseline(vm: &Vm, code: &str) -> R<Vec<J>> {
950-
let mut atoms = crate::strings::Strings::new();
950+
let mut atoms = crate::strings::Strings::fresh();
951951
let program =
952952
crate::run::compile(code, &mut atoms).map_err(|e| SnapshotError::new(e.message))?;
953953
let h = &vm.host;

‎rust/crates/psychoscript/src/strings.rs‎

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -222,13 +222,15 @@ pub struct StrRef<'a> {
222222
impl Strings {
223223
pub fn new() -> Self {
224224
let mut s = Strings {
225-
bufs: Vec::new(),
225+
// Sized for what a fresh runtime makes (about 380 strings, 250 of them atoms), so setting one up grows none
226+
// of these.
227+
bufs: Vec::with_capacity(448),
226228
grow: Vec::new(),
227229
arena: NO_GROW,
228230
wtf: Vec::new(),
229-
map: FxHashMap::default(),
230-
atom_str: Vec::new(),
231-
atom_index: Vec::new(),
231+
map: FxHashMap::with_capacity_and_hasher(448, Default::default()),
232+
atom_str: Vec::with_capacity(320),
233+
atom_index: Vec::with_capacity(320),
232234
gc_limit: crate::collector::first_limit(),
233235
gc: Default::default(),
234236
};
@@ -245,6 +247,30 @@ impl Strings {
245247
s
246248
}
247249

250+
/// The strings a compile starts from: the fresh runtime's (`builtins::image`), so they have the same ids in
251+
/// every run and a run's VM is a copy of the image.
252+
pub fn fresh() -> Self {
253+
let image = &crate::builtins::image().atoms;
254+
// Copied with room for a short program's own strings and names: a plain copy has none, and its first push
255+
// would double it.
256+
fn roomy<T: Clone>(from: &[T], room: usize) -> Vec<T> {
257+
let mut v = Vec::with_capacity(from.len() + room);
258+
v.extend_from_slice(from);
259+
v
260+
}
261+
Strings {
262+
bufs: roomy(&image.bufs, 64),
263+
grow: image.grow.clone(),
264+
arena: image.arena,
265+
wtf: image.wtf.clone(),
266+
map: image.map.clone(),
267+
atom_str: roomy(&image.atom_str, 32),
268+
atom_index: roomy(&image.atom_index, 32),
269+
gc_limit: image.gc_limit,
270+
gc: image.gc.clone(),
271+
}
272+
}
273+
248274
#[inline]
249275
pub fn alloc(&mut self, s: String) -> StrId {
250276
let ascii = s.is_ascii();

‎rust/crates/psychoscript/src/test262.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ fn diagnostic(kind: DiagnosticKind, message: String) -> Diagnostic {
5858
fn run_here(code: &str, timeout_ms: u64) -> Run {
5959
let probe = 0u8;
6060
DONE.with(|d| *d.borrow_mut() = None);
61-
let mut atoms = Strings::new();
61+
let mut atoms = Strings::fresh();
6262
let program = match compiler::compile(code, &mut atoms) {
6363
Ok(p) => p,
6464
Err(e) => {

‎rust/crates/psychoscript/src/vm.rs‎

Lines changed: 42 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,7 @@ pub enum Job {
172172
},
173173
}
174174

175+
#[derive(Clone)]
175176
pub struct Names {
176177
pub length: Atom,
177178
pub name: Atom,
@@ -197,7 +198,7 @@ pub struct Names {
197198
pub buffer: Atom,
198199
}
199200

200-
#[derive(Default)]
201+
#[derive(Clone, Default)]
201202
pub struct Realm {
202203
pub object_proto: Id,
203204
pub function_proto: Id,
@@ -359,7 +360,29 @@ pub struct Vm {
359360
}
360361

361362
impl Vm {
363+
/// A VM with the fresh runtime's built-ins in it. One whose strings start as the image's (`Strings::fresh`, which
364+
/// every compile starts from) copies the image, made once for the process; any other is set up from scratch by
365+
/// `setup`, as the image itself is.
362366
pub fn new(host: crate::host::RunHost, limits: Limits, atoms: Strings) -> Self {
367+
let image = crate::builtins::image();
368+
if !image.seeds(&atoms) {
369+
return Self::new_scratch(host, limits, atoms);
370+
}
371+
let mut vm = Self::bare(
372+
host,
373+
limits,
374+
atoms,
375+
image.names.clone(),
376+
image.char_strs.clone(),
377+
);
378+
vm.heap = image.heap.clone_base();
379+
vm.realm = image.realm.clone();
380+
vm.global_map = image.global_map.clone();
381+
vm
382+
}
383+
384+
/// A VM with no built-ins yet, its names interned here.
385+
pub(crate) fn new_scratch(host: crate::host::RunHost, limits: Limits, atoms: Strings) -> Self {
363386
let mut atoms = atoms;
364387
let names = Names {
365388
length: atoms.intern_static("length"),
@@ -385,18 +408,32 @@ impl Vm {
385408
byte_offset: atoms.intern_static("byteOffset"),
386409
buffer: atoms.intern_static("buffer"),
387410
};
388-
let char_strs = (0u8..128)
389-
.map(|c| atoms.alloc((c as char).to_string()))
411+
// Static text, as the built-in names are: a copy of the image's strings then allocates none of them.
412+
const ASCII: &str = "\0\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f";
413+
let char_strs = (0..128)
414+
.map(|c| atoms.alloc_static(&ASCII[c..c + 1]))
390415
.collect();
416+
Self::bare(host, limits, atoms, names, char_strs)
417+
}
418+
419+
fn bare(
420+
host: crate::host::RunHost,
421+
limits: Limits,
422+
atoms: Strings,
423+
names: Names,
424+
char_strs: Vec<StrId>,
425+
) -> Self {
391426
let seed = crate::time::SystemTime::now()
392427
.duration_since(crate::time::UNIX_EPOCH)
393428
.map(|d| d.as_nanos() as u64)
394429
.unwrap_or(0x9e3779b97f4a7c15);
395430
Vm {
396-
heap: Heap::with_capacity(1024),
431+
// Room for what a fresh runtime makes (about 290 objects) and a small program's own: a waiting run keeps
432+
// this, so it is not sized for a large one, which grows it.
433+
heap: Heap::with_capacity(320),
397434
cells: Vec::new(),
398435
atoms,
399-
stack: Vec::with_capacity(1024),
436+
stack: Vec::with_capacity(128),
400437
frames: Vec::with_capacity(64),
401438
spare_frames: Vec::new(),
402439
handlers: Vec::new(),

0 commit comments

Comments
 (0)