wardite 1.2.2 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +11 -11
  3. data/Rakefile +0 -177
  4. data/benchmark/README.md +10 -36
  5. data/benchmark/call_cost_worker.rb +3 -2
  6. data/benchmark/compare.rb +1 -2
  7. data/benchmark/compare_linear_memory_loads.py +144 -0
  8. data/benchmark/i32_memory.wat +5 -1
  9. data/benchmark/investigate_calls.rb +4 -4
  10. data/benchmark/linear_memory_loads.wat +52 -0
  11. data/benchmark/optimization_worker.rb +3 -2
  12. data/benchmark/patches/adr0017-spinel-signed64.patch +190 -0
  13. data/benchmark/patches/adr0017-wardite-split-load64.patch +70 -0
  14. data/benchmark/results/adr0019-startup.json +1687 -0
  15. data/benchmark/results/adr0020-i64.json +2034 -0
  16. data/benchmark/results/adr0021-optimizer.json +5798 -0
  17. data/benchmark/results/adr0022-lazy-mir.json +3057 -0
  18. data/benchmark/results/crc8-stream-repeat.csv +89 -0
  19. data/benchmark/results/crc8-stream.csv +89 -0
  20. data/benchmark/results/linear-memory-loads-a2aa05227.csv +793 -0
  21. data/benchmark/results/linear-memory-loads-stage-b.csv +353 -0
  22. data/benchmark/results/linear-memory-loads.csv +1057 -0
  23. data/benchmark/results/real-workloads-baseline-2026-11-18.json +1741 -0
  24. data/benchmark/results/stack-vm-removal.json +334 -0
  25. data/benchmark/validate_m4.rb +0 -2
  26. data/docs/adr/0017-efflorescence-linear-memory-loads.md +90 -0
  27. data/docs/adr/0018-efflorescence-real-workload-measurement.md +126 -0
  28. data/docs/adr/0019-efflorescence-startup-quick-wins.md +85 -0
  29. data/docs/adr/0020-efflorescence-inline-i64-bit-operations.md +89 -0
  30. data/docs/adr/0021-efflorescence-optimize-real-functions.md +133 -0
  31. data/docs/adr/0022-efflorescence-lazy-function-build.md +111 -0
  32. data/docs/adr/0023-efflorescence-byte-sequences-and-copy-coalescing.md +56 -0
  33. data/docs/efflorescence-ja.md +3 -5
  34. data/docs/efflorescence-linear-memory-loads.md +134 -0
  35. data/docs/efflorescence-m6.md +1 -1
  36. data/docs/efflorescence-mir2-cache.md +7 -0
  37. data/docs/efflorescence-real-workloads.md +312 -0
  38. data/docs/efflorescence-spinel-linear-memory.md +2 -2
  39. data/docs/efflorescence.md +3 -5
  40. data/docs/stack-vm-removal.md +49 -0
  41. data/lib/wardite/cli/cli.rb +24 -24
  42. data/lib/wardite/efflorescence/byte_sequences.rb +80 -0
  43. data/lib/wardite/efflorescence/function_preparer.rb +64 -0
  44. data/lib/wardite/efflorescence/i64_arithmetic.rb +31 -0
  45. data/lib/wardite/efflorescence/inspection.rb +44 -12
  46. data/lib/wardite/efflorescence/ir.rb +33 -10
  47. data/lib/wardite/efflorescence/mir_cache.rb +10 -1
  48. data/lib/wardite/efflorescence/optimizer.rb +151 -42
  49. data/lib/wardite/efflorescence/store_access.rb +17 -0
  50. data/lib/wardite/efflorescence/translation_source.rb +50 -0
  51. data/lib/wardite/efflorescence/translator.rb +43 -13
  52. data/lib/wardite/efflorescence/vm.rb +116 -48
  53. data/lib/wardite/efflorescence.rb +3 -0
  54. data/lib/wardite/load.rb +46 -62
  55. data/lib/wardite/version.rb +1 -1
  56. data/lib/wardite.rb +21 -757
  57. data/scripts/build_spinel_zig.rb +1 -1
  58. data/sig/generated/wardite/cli/cli.rbs +4 -2
  59. data/sig/generated/wardite/efflorescence/byte_sequences.rbs +33 -0
  60. data/sig/generated/wardite/efflorescence/function_preparer.rbs +25 -0
  61. data/sig/generated/wardite/efflorescence/i64_arithmetic.rbs +19 -0
  62. data/sig/generated/wardite/efflorescence/inspection.rbs +8 -0
  63. data/sig/generated/wardite/efflorescence/ir.rbs +18 -2
  64. data/sig/generated/wardite/efflorescence/optimizer.rbs +41 -3
  65. data/sig/generated/wardite/efflorescence/store_access.rbs +5 -0
  66. data/sig/generated/wardite/efflorescence/translation_source.rbs +34 -0
  67. data/sig/generated/wardite/efflorescence/translator.rbs +11 -1
  68. data/sig/generated/wardite/efflorescence/vm.rbs +19 -9
  69. data/sig/generated/wardite/load.rbs +18 -18
  70. data/sig/generated/wardite.rbs +4 -155
  71. metadata +32 -17
  72. data/benchmark/compare_engines.rb +0 -119
  73. data/benchmark/engine_phases.rb +0 -30
  74. data/lib/wardite/alu_f32.generated.rb +0 -261
  75. data/lib/wardite/alu_f64.generated.rb +0 -261
  76. data/lib/wardite/alu_i32.generated.rb +0 -510
  77. data/lib/wardite/alu_i64.generated.rb +0 -572
  78. data/lib/wardite/convert.generated.rb +0 -340
  79. data/scripts/gen_alu.rb +0 -864
  80. data/scripts/gen_conv.rb +0 -86
  81. data/scripts/templates/alu_module.rb.tmpl +0 -20
  82. data/scripts/templates/conv_module.rb.tmpl +0 -20
  83. data/sig/generated/wardite/alu_f32.generated.rbs +0 -12
  84. data/sig/generated/wardite/alu_f64.generated.rbs +0 -12
  85. data/sig/generated/wardite/alu_i32.generated.rbs +0 -12
  86. data/sig/generated/wardite/alu_i64.generated.rbs +0 -12
  87. data/sig/generated/wardite/convert.generated.rbs +0 -12
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 3b9acbd0ed033b8f0c6da77501ec5fb8a5840133ab15cb2a1ac031aba04eb20d
4
- data.tar.gz: 9820acbfc819c417edecc0fdbdea3cd5f35cec8965dd6b12bf45917a68c63707
3
+ metadata.gz: cde3cd88bacf2adcff035f6f6f121fcee660a365c91c70143c33158ea8476017
4
+ data.tar.gz: 2607ed31f7be4aaf8f987305e037e9921fc23d2232beef6841199e802272bbe2
5
5
  SHA512:
6
- metadata.gz: 87567e5c58345ee263a6eecf8fc9fc2a76f136898d0a2a59a0010c1ea488c4e2e5c9a2c97d9a218dc03bdaf2696907c3db46fa1806f5815b58ce2ef8cc7e60c8
7
- data.tar.gz: 0da3f82b16f3aa28ab74df0eb3ed16dfb46c1bea780de9f55b7e434bdd1e3c964f10e752fd0cad81def9f83212b9afa07962ca695ca38422174c99264e417ec4
6
+ metadata.gz: 13bf5c13fd1dc00d9a91f7d21be4555b1a3d8c866b6c7ce4342261d544f8ff61b8653d81bb69ccb1ca5fef935b7354013d9078af2e904ad777b2da0b17eb6295
7
+ data.tar.gz: 30dc7c59ce9ff019c1f9c00af914aa46da0769e8cfc365554d3015f73ab4bd6deba3d3400cd48d33b2ffc319c0b9ade068cd611c2d8b11f856a66fa6ce5eb05c
data/README.md CHANGED
@@ -62,19 +62,17 @@ $ wardite examples/test.wasm
62
62
 
63
63
  ### Efflorescence register VM
64
64
 
65
- The CLI and Ruby API default to the MIR-based Efflorescence register VM. The
66
- CRuby and Spinel CLIs still accept `--new-engine` for compatibility. Use
67
- `--stack-engine` to select the legacy stack VM.
65
+ The CLI and Ruby API use the MIR-based Efflorescence register VM. The
66
+ CRuby and Spinel CLIs still accept `--new-engine` for compatibility.
68
67
 
69
68
  ```sh
70
69
  wardite --no-wasi --invoke add test/add.wasm 100 200
71
70
  # return value: I32(300)
72
71
  ```
73
72
 
74
- To select the legacy stack VM in Ruby, pass `engine: :stack` to `Wardite.new` or
75
- `BinaryLoader.load_from_buffer`. Efflorescence reports unsupported instructions with an explicit
73
+ Ruby callers can omit the `engine:` keyword or pass `:efflorescence`. Efflorescence reports unsupported instructions with an explicit
76
74
  exception. See the [design, supported subset and tests](docs/efflorescence.md)
77
- and [engine comparison benchmark](benchmark/README.md).
75
+ and [benchmarks](benchmark/README.md).
78
76
 
79
77
  Efflorescence now includes independent COPY/immediate/branch/fusion passes,
80
78
  flat integer bytecode and frame reuse. Execution always uses flat bytecode,
@@ -83,8 +81,10 @@ Use `--mir-disable NAME` to compare
83
81
  individual features, `--mir-dump` to inspect MIR and `--mir-profile` for counters.
84
82
  See [Phase 2](docs/efflorescence-phase2.md) ([日本語](docs/efflorescence-phase2-ja.md)).
85
83
 
86
- On CRuby and Spinel, pass `--mir-cache DIR` to reuse lowered
87
- MIR across processes. Use a local directory you control. Each run still decodes
84
+ On CRuby and Spinel, the default is to validate the whole module at load time
85
+ and prepare MIR on the first call to each function. For repeated runs, pass
86
+ `--mir-cache DIR`: the first run prepares all functions and writes the cache,
87
+ and later runs restore only the functions they call. Use a local directory you control. Each run still decodes
88
88
  the Wasm, links imports, and initializes a fresh instance. `--mir-dump` and
89
89
  `--mir-profile` build MIR normally. Ruby callers can pass `mir_cache: dir`.
90
90
  CRuby and Spinel use different cache keys.
@@ -93,8 +93,8 @@ The default `--mir-cache-verify checksum` checks the payload size and samples
93
93
  blocks. Use `--mir-cache-verify sha256` or Ruby's `mir_cache_verify: :sha256`
94
94
  to check the whole payload. Both modes use the same cache file. By default,
95
95
  each function is restored and structurally checked before its first execution.
96
- Use `--mir-cache-eager` or Ruby's `mir_cache_eager: true` to check every
97
- function at load time. If a lazy check fails, Wardite stops and reports the
96
+ Use `--mir-eager` (also spelled `--mir-cache-eager`) or Ruby's
97
+ `mir_cache_eager: true` to prepare or restore every function at load time. If a lazy check fails, Wardite stops and reports the
98
98
  cache path. Delete that file and rerun. Corruption outside the sampled blocks
99
99
  can go undetected in checksum mode, including changes that leave the MIR
100
100
  structurally valid.
@@ -170,7 +170,7 @@ CRuby build. Ruby's dynamic export helpers (`instance.add(...)` and
170
170
  The build leaves inline RBS and Spinel's default integer overflow checks enabled.
171
171
  Wasm integer operations bound their intermediate values, so
172
172
  `--int-overflow=promote` is not required.
173
- CI builds Spinel from the upstream commit `58ee6361`, which includes the
173
+ CI builds Spinel from the upstream commit `a2aa05227`, which includes the
174
174
  required `IO::Buffer` changes.
175
175
  See the [build instructions and host memory API](docs/efflorescence-spinel-linear-memory.md).
176
176
  Override `SPINEL`, `SPINELFLAGS`, `BUILD_DIR`, or `RUBY` when needed.
data/Rakefile CHANGED
@@ -50,182 +50,5 @@ task :basic_benchmark do
50
50
  sh "hyperfine --warmup 3 'bundle exec wardite --yjit --no-wasi --invoke detailed_arithmetic_loop examples/i32_bench.wasm'"
51
51
  end
52
52
 
53
- desc "Generate codes"
54
- task :generate do
55
- require_relative "scripts/gen_alu"
56
- require_relative "scripts/gen_conv"
57
- libdir = File.expand_path("../lib", __FILE__)
58
-
59
- GenAlu.execute(libdir + "/wardite/alu_i32.generated.rb", prefix: "i32", defined_ops: [
60
- :load,
61
- :load8_s,
62
- :load8_u,
63
- :load16_s,
64
- :load16_u,
65
- :store,
66
- :store8,
67
- :store16,
68
- :const,
69
- :eqz,
70
- :eq,
71
- :ne,
72
- :lts,
73
- :ltu,
74
- :gts,
75
- :gtu,
76
- :les,
77
- :leu,
78
- :ges,
79
- :geu,
80
- :clz,
81
- :ctz,
82
- :popcnt,
83
- :add,
84
- :sub,
85
- :mul,
86
- :div_s,
87
- :div_u,
88
- :rem_s,
89
- :rem_u,
90
- :and,
91
- :or,
92
- :xor,
93
- :shl,
94
- :shr_s,
95
- :shr_u,
96
- :rotl,
97
- :rotr,
98
- ])
99
- GenAlu.execute(libdir + "/wardite/alu_i64.generated.rb", prefix: "i64", defined_ops: [
100
- :load,
101
- :load8_s,
102
- :load8_u,
103
- :load16_s,
104
- :load16_u,
105
- :load32_s,
106
- :load32_u,
107
- :store,
108
- :store8,
109
- :store16,
110
- :store32,
111
- :const,
112
- :eqz,
113
- :eq,
114
- :ne,
115
- :lts,
116
- :ltu,
117
- :gts,
118
- :gtu,
119
- :les,
120
- :leu,
121
- :ges,
122
- :geu,
123
- :clz,
124
- :ctz,
125
- :popcnt,
126
- :add,
127
- :sub,
128
- :mul,
129
- :div_s,
130
- :div_u,
131
- :rem_s,
132
- :rem_u,
133
- :and,
134
- :or,
135
- :xor,
136
- :shl,
137
- :shr_s,
138
- :shr_u,
139
- :rotl,
140
- :rotr,
141
- ])
142
- GenAlu.execute(libdir + "/wardite/alu_f32.generated.rb", prefix: "f32", defined_ops: [
143
- :load,
144
- :store,
145
- :const__f,
146
- :eqz,
147
- :eq,
148
- :ne,
149
- :lt,
150
- :gt,
151
- :le,
152
- :ge,
153
- :abs,
154
- :neg,
155
- :ceil,
156
- :floor,
157
- :trunc,
158
- :nearest,
159
- :sqrt,
160
- :add,
161
- :sub,
162
- :mul,
163
- :div,
164
- :min,
165
- :max,
166
- :copysign,
167
- ])
168
- GenAlu.execute(libdir + "/wardite/alu_f64.generated.rb", prefix: "f64", defined_ops: [
169
- :load,
170
- :store,
171
- :const__f,
172
- :eqz,
173
- :eq,
174
- :ne,
175
- :lt,
176
- :gt,
177
- :le,
178
- :ge,
179
- :abs,
180
- :neg,
181
- :ceil,
182
- :floor,
183
- :trunc,
184
- :nearest,
185
- :sqrt,
186
- :add,
187
- :sub,
188
- :mul,
189
- :div,
190
- :min,
191
- :max,
192
- :copysign,
193
- ])
194
-
195
- GenConv.execute(libdir + "/wardite/convert.generated.rb", defined_ops: {
196
- i32: {
197
- wrap: [:i64],
198
- trunc_s: [:f32, :f64],
199
- trunc_u: [:f32, :f64],
200
- reinterpret: [:f32],
201
- extendN_s: [:i8, :i16],
202
- trunc_sat_s: [:f32, :f64],
203
- trunc_sat_u: [:f32, :f64],
204
- },
205
- i64: {
206
- extend_s: [:i32, :i64],
207
- extend_u: [:i32, :i64],
208
- trunc_s: [:f32, :f64],
209
- trunc_u: [:f32, :f64],
210
- reinterpret: [:f64],
211
- extendN_s: [:i8, :i16, :i32],
212
- trunc_sat_s: [:f32, :f64],
213
- trunc_sat_u: [:f32, :f64],
214
- },
215
- f32: {
216
- convert_s: [:i32, :i64],
217
- convert_u: [:i32, :i64],
218
- demote: [:f64],
219
- reinterpret: [:i32],
220
- },
221
- f64: {
222
- convert_s: [:i32, :i64],
223
- convert_u: [:i32, :i64],
224
- promote: [:f32],
225
- reinterpret: [:i64],
226
- },
227
- })
228
- end
229
-
230
53
  task default: %i[test check]
231
54
 
data/benchmark/README.md CHANGED
@@ -6,6 +6,8 @@ enabled in the script. See [Run](#run) for the complete
6
6
  matrix and options. The scripts below provide additional optimization-specific
7
7
  comparisons.
8
8
 
9
+ The [stack VM removal report](../docs/stack-vm-removal.md) compares native build time, binary size, startup and execution on the default engine.
10
+
9
11
  ## MIR generation before caching
10
12
 
11
13
  [MIR生成性能調査(日本語)](../docs/efflorescence-mir-generation-performance.md)
@@ -184,8 +186,8 @@ The report `build/benchmark/optimizations.json` contains raw samples, phase and
184
186
  whole-process means, CRuby execution allocations and per-opcode counters.
185
187
  Time measurement does not enable MIR counters. Both phase and CLI measurements
186
188
  include the same Ruby-facing boxed return boundary. Spinel allocations are `n/a`.
187
- The shared phase loader creates the stack VM, then the selected MIR VM is
188
- constructed in the MIR phase; the fixture has no start function. Phase timing
189
+ The load phase instantiates Efflorescence and translates semantic MIR. The
190
+ next phase prepares all function bodies before timing execution. Phase timing
189
191
  uses a separate executable, whose Spinel inference can differ from the CLI.
190
192
  `SPINEL` and `SPINELFLAGS` choose the compiler/flags (default `-O2`).
191
193
 
@@ -306,36 +308,9 @@ larger apparent gain should not be treated as the stable speedup.
306
308
  Local raw reports are `build/benchmark/dispatch-100k.json` and
307
309
  `build/benchmark/dispatch-million.json` (also the latest `dispatch.json`).
308
310
 
309
- ## Compare the stack and Efflorescence engines
310
-
311
- ```sh
312
- ruby benchmark/compare_engines.rb 100000 123
313
- # Optional sample counts (default: 5 samples after 2 warmups):
314
- RUNS=3 WARMUPS=1 ruby benchmark/compare_engines.rb 100000 123
315
- ```
311
+ ## Historical stack VM comparison
316
312
 
317
- Requires Ruby, Spinel/C toolchain, make and wasm-tools. YJIT is included when
318
- available. The script builds both native entry points, checks **all eight Phase
319
- 1 input cases** on both exports and both engines on every runtime against an
320
- independent reference, then measures the requested input. A mismatch aborts.
321
-
322
- Results include whole CLI process time and separate load, MIR translation and
323
- execution times from `engine_phases.rb`, compiled unchanged by Spinel. Phase
324
- timings come from a separate process per sample, with one call per process;
325
- they include frame setup and the final Ruby-facing result box. The loader phase
326
- creates the shared instance with the stack VM; the fixture has no start
327
- function, so it executes no guest instructions. For Efflorescence, the next
328
- phase constructs the selected VM from that instance (including a second, empty
329
- Runtime setup for stack samples). End-to-end samples use the real
330
- CLI and include engine selection, startup,
331
- load, translation, execution and output. Warmups are separate processes, so YJIT
332
- compiles anew for each sample. Native compilation is outside measurement.
333
- Phase values are diagnostic and do not sum to the CLI time: they use a separate
334
- entry point, which can also change Spinel's whole-program type inference.
335
-
336
- Raw samples and means are saved to `build/benchmark/engines.json`. `SPINEL` and
337
- `SPINELFLAGS` can select the compiler and flags (default `-O2`, with the default
338
- overflow checks enabled). [Engine design and scope](../docs/efflorescence.md).
313
+ The comparison driver and both engines are available at commit `0c806bc`.
339
314
 
340
315
  ### Phase 1 sample (2026-11-03)
341
316
 
@@ -402,20 +377,19 @@ RUNS=3 WARMUPS=1 ruby benchmark/compare.rb 100000 123
402
377
 
403
378
  The script compiles the WAT and the Spinel CLI, computes an independent Ruby
404
379
  reference, and checks all enabled command results before timing. The current
405
- selection is New VM / Spinel, iwasm, Wasmtime (Pulley) and Wasmtime: **8 commands**
406
- across both exports. Uncomment the CRuby/YJIT and Old VM runner definitions in
407
- `compare.rb` to enable the full nine-configuration, **18-command** matrix below.
380
+ selection is Efflorescence / Spinel, iwasm, Wasmtime (Pulley) and Wasmtime: **8 commands**
381
+ across both exports. Uncomment the CRuby/YJIT runner definitions in
382
+ `compare.rb` to enable the full six-configuration, **12-command** matrix below.
408
383
  YJIT support is required only when its runner is enabled.
409
384
 
410
385
  | Engine | Execution configurations |
411
386
  | --- | --- |
412
- | Old VM (`Wardite::Runtime`) | CRuby (YJIT disabled), CRuby + YJIT, Spinel; `--stack-engine` |
413
387
  | New VM (`Wardite::Efflorescence::VM`) | CRuby (YJIT disabled), CRuby + YJIT, Spinel; default engine and optimizations |
414
388
  | iwasm / WAMR | Explicit interpreter mode (`--interp`) |
415
389
  | Wasmtime (Pulley) | `--target pulley64 -C cache=n` |
416
390
  | Wasmtime | Native compilation, `-C cache=n` |
417
391
 
418
- Hyperfine command names distinguish `Old VM` and `New VM`. A mismatch,
392
+ A mismatch,
419
393
  unavailable enabled YJIT or a missing required runtime stops the run.
420
394
  Defaults: 100,000 rounds,
421
395
  seed 123456789, two warmup processes, and five measured processes per command.
@@ -13,10 +13,11 @@ disabled = ARGV.fetch(4, "").split(",").map { |name| name.to_sym }
13
13
  profile = ARGV.fetch(5, "time") == "metrics"
14
14
  started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
15
15
  instance = File.open(wasm, "rb") do |file|
16
- Wardite::BinaryLoader.load_from_buffer(file, enable_wasi: false, engine: :stack)
16
+ Wardite::BinaryLoader.load_from_buffer(file, enable_wasi: false, disabled_optimizations: disabled, mir_profile: profile)
17
17
  end
18
18
  loaded = Process.clock_gettime(Process::CLOCK_MONOTONIC)
19
- vm = Wardite::Efflorescence::VM.new(instance, disabled_optimizations: disabled, profile: profile)
19
+ vm = instance.runtime
20
+ vm.prepare_all
20
21
  translated = Process.clock_gettime(Process::CLOCK_MONOTONIC)
21
22
  result = vm.call_unboxed(export, [rounds, seed]) || raise("missing checksum")
22
23
  finished = Process.clock_gettime(Process::CLOCK_MONOTONIC)
data/benchmark/compare.rb CHANGED
@@ -37,8 +37,7 @@ wardite_runners = {
37
37
  }
38
38
  runners = {}
39
39
  wardite_runners.each do |runtime, command|
40
- # runners["Old VM / #{runtime}"] = [:wardite, command + ["--stack-engine"]]
41
- runners["New VM / #{runtime}"] = [:wardite, command]
40
+ runners["Efflorescence / #{runtime}"] = [:wardite, command]
42
41
  end
43
42
  runners["iwasm (WAMR interpreter)"] = [:iwasm, ["iwasm", "--interp"]]
44
43
  runners["Wasmtime (Pulley)"] = [:wasmtime, ["wasmtime", "run", "--target", "pulley64", "-C", "cache=n"]]
@@ -0,0 +1,144 @@
1
+ #!/usr/bin/env python3
2
+
3
+ import argparse
4
+ import csv
5
+ import os
6
+ from pathlib import Path
7
+ import re
8
+ import subprocess
9
+ import sys
10
+ from tempfile import TemporaryDirectory
11
+ from time import perf_counter_ns
12
+
13
+
14
+ def run(argv, **kwargs):
15
+ return subprocess.run(argv, check=True, capture_output=True, **kwargs)
16
+
17
+
18
+ def measure(binaries, cache_root, writer, case, wasm, args, expected, *,
19
+ rounds, stdin=None, cache=False, timed=False, invoke=None):
20
+ trace_env = dict(os.environ, WARDITE_TRACE="1")
21
+ commands = {}
22
+ for index, (name, binary) in enumerate(binaries):
23
+ cmd = [binary]
24
+ if cache:
25
+ cmd += ["--mir-cache", str(cache_root / str(index))]
26
+ if invoke:
27
+ cmd += ["--no-wasi", "--invoke", invoke]
28
+ commands[name] = cmd + ["--", str(wasm), *map(str, args)]
29
+
30
+ def sample(name, input_file):
31
+ if input_file:
32
+ input_file.seek(0)
33
+ started = perf_counter_ns()
34
+ result = subprocess.run(commands[name], stdin=input_file, stdout=subprocess.DEVNULL,
35
+ stderr=subprocess.PIPE, env=trace_env, check=True)
36
+ elapsed = perf_counter_ns() - started
37
+ trace = result.stderr.decode()
38
+ if cache and "MIR2 cache hit:" not in trace:
39
+ raise ValueError(f"{name} {case} missed MIR2 cache: {trace}")
40
+ if invoke:
41
+ match = re.search(r"return value: I(32|64)\((-?\d+)\)", trace)
42
+ if not match:
43
+ raise ValueError(f"missing return value: {trace}")
44
+ width = int(match[1])
45
+ mask = (1 << width) - 1
46
+ if (int(match[2]) & mask) != (expected & mask):
47
+ raise ValueError(f"{name} {case} returned {match[2]}, expected {expected}")
48
+ load_ms = float(re.search(r"load_from_buffer: ([0-9.eE+-]+)", trace)[1]) * 1000
49
+ transform_ms = ""
50
+ if timed:
51
+ transform_ms = int(re.search(r"base64_transform_ns: (\d+)", trace)[1]) / 1e6
52
+ return elapsed / 1e6, load_ms, elapsed / 1e6 - load_ms, transform_ms
53
+
54
+ names = [name for name, _ in binaries]
55
+ for name in names:
56
+ result = run(commands[name], input=stdin.read_bytes() if stdin else None, env=trace_env)
57
+ if not invoke and result.stdout != expected:
58
+ raise ValueError(f"{name} {case} output differs from the reference")
59
+
60
+ with (stdin or Path(os.devnull)).open("rb") as input_file:
61
+ for index in range(-2, rounds):
62
+ # Alternate the run order within each case after warming each binary twice.
63
+ for name in (names if index % 2 == 0 else reversed(names)):
64
+ values = sample(name, input_file)
65
+ if index >= 0:
66
+ timings = [f"{value:.6f}" if value != "" else "" for value in values]
67
+ writer.writerow((case, name, index + 1, *timings))
68
+
69
+
70
+ def measure_crc8(binaries, root, writer, wasm, rounds):
71
+ for grow in (0, 1):
72
+ params = [256, grow]
73
+ reference = run(["wasmtime", "run", "--invoke", "crc8_stream", wasm, *map(str, params)])
74
+ case = "crc8_grown" if grow else "crc8_owned"
75
+ measure(binaries, root, writer, case, wasm, params, int(reference.stdout),
76
+ rounds=rounds, invoke="crc8_stream")
77
+
78
+
79
+ def main():
80
+ parser = argparse.ArgumentParser(description="Compare Spinel Wardite memory load timings")
81
+ parser.add_argument("benches", type=Path, help="wardite-benches checkout with built examples and fixtures")
82
+ parser.add_argument("timed_base64", type=Path, help="base64_codec.wasm instrumented with base64_transform_ns")
83
+ parser.add_argument("binaries", nargs="+", metavar="NAME=BINARY")
84
+ parser.add_argument("--rounds", type=int, default=11)
85
+ parser.add_argument("--png", action="store_true", help="also benchmark PNG to grayscale PGM")
86
+ parser.add_argument("--crc8", type=Path, help="also benchmark the compiled crc8_stream example")
87
+ args = parser.parse_args()
88
+
89
+ binaries = [entry.split("=", 1) for entry in args.binaries]
90
+ if any(len(entry) != 2 or not all(entry) for entry in binaries):
91
+ parser.error("each binary must be specified as NAME=BINARY")
92
+ if len({name for name, _ in binaries}) != len(binaries):
93
+ parser.error("binary names must be distinct")
94
+ bench = Path(__file__).resolve().parent
95
+ fixtures = args.benches / "build" / "fixtures"
96
+ codec = args.benches / "build/rust/wasm32-wasip1/release/examples/base64_codec.wasm"
97
+ data = fixtures / "data.bin"
98
+ encoded = fixtures / "data.b64"
99
+ writer = csv.writer(sys.stdout, lineterminator="\n")
100
+ writer.writerow(("case", "build", "run", "process_ms", "load_ms", "process_minus_load_ms", "transform_ms"))
101
+
102
+ with TemporaryDirectory(prefix="wardite-linear-loads-") as directory:
103
+ root = Path(directory)
104
+ for wasm, timed in ((codec, False), (args.timed_base64, True)):
105
+ for mode, stdin, output in (("encode", data, encoded), ("decode", encoded, data)):
106
+ expected = output.read_bytes()
107
+ reference = run(["wasmtime", "run", wasm, mode], input=stdin.read_bytes())
108
+ if reference.stdout != expected:
109
+ raise ValueError(f"Wasmtime {mode} output differs from the reference")
110
+ for cache in (False, True):
111
+ case = f"{mode}_{'hit' if cache else 'off'}{'_timed' if timed else ''}"
112
+ measure(binaries, root, writer, case, wasm, [mode], expected,
113
+ rounds=args.rounds, stdin=stdin, cache=cache, timed=timed)
114
+
115
+ if args.png:
116
+ wasm = codec.with_name("png_grayscale.wasm")
117
+ png = fixtures / "rgb.png"
118
+ expected = run(["wasmtime", "run", wasm], input=png.read_bytes()).stdout
119
+ for cache in (False, True):
120
+ case = "png_hit" if cache else "png_off"
121
+ measure(binaries, root, writer, case, wasm, [], expected,
122
+ rounds=args.rounds, stdin=png, cache=cache)
123
+
124
+ if args.crc8:
125
+ measure_crc8(binaries, root, writer, args.crc8, args.rounds)
126
+
127
+ for source, exports in (
128
+ ("linear_memory_loads", ("lookup8", "unaligned64", "mixed_width")),
129
+ ("i32_memory", ("array_scan", "array_scan_grown")),
130
+ ):
131
+ wasm = root / f"{source}.wasm"
132
+ run(["wat2wasm", bench / f"{source}.wat", "-o", wasm])
133
+ for export in exports:
134
+ arguments = ([(400_000, 0), (400_000, 1)] if source == "linear_memory_loads"
135
+ else [(1600, 17)])
136
+ for params in arguments:
137
+ case = f"{export}_{'grown' if params[1] else 'owned'}" if len(arguments) > 1 else export
138
+ reference = run(["wasmtime", "run", "--invoke", export, wasm, *map(str, params)])
139
+ measure(binaries, root, writer, case, wasm, params, int(reference.stdout),
140
+ rounds=args.rounds, invoke=export)
141
+
142
+
143
+ if __name__ == "__main__":
144
+ main()
@@ -4,7 +4,7 @@
4
4
  (data $pattern "0123456789abcdef")
5
5
 
6
6
  ;; Initialize 256 words, then scan each complete array once per round.
7
- (func (export "array_scan") (param $rounds i32) (param $seed i32) (result i32)
7
+ (func $array_scan (export "array_scan") (param $rounds i32) (param $seed i32) (result i32)
8
8
  (local $index i32) (local $sum i32)
9
9
  loop $initialize
10
10
  local.get $index i32.const 2 i32.shl
@@ -24,6 +24,10 @@
24
24
  end end
25
25
  local.get $sum)
26
26
 
27
+ (func (export "array_scan_grown") (param $rounds i32) (param $seed i32) (result i32)
28
+ i32.const 1 memory.grow drop
29
+ local.get $rounds local.get $seed call $array_scan)
30
+
27
31
  ;; Both a complete fill and an overlapping copy run every iteration.
28
32
  (func (export "copy_fill") (param $rounds i32) (param $seed i32) (result i32)
29
33
  (local $index i32) (local $sum i32)
@@ -142,7 +142,7 @@ variants.each do |variant|
142
142
  puts "Built #{variant}"
143
143
  end
144
144
 
145
- # Confirm the current engine, old Stack VM and independent arithmetic agree on
145
+ # Confirm the current engine and independent arithmetic agree on
146
146
  # the controls and i32 boundaries before measuring any variant. Each native
147
147
  # variant is also checked at zero/one/many iterations with negative-bit seeds.
148
148
  validation = [[0, 0], [0, 123], [1, 0xffffffff], [10, 123], [1000, 0xffffffff]]
@@ -150,7 +150,7 @@ validation_worker = "#{output}/validate.rb"
150
150
  File.write(validation_worker, <<~RUBY)
151
151
  require "wardite"
152
152
  wasm, rounds, seed = ARGV
153
- instance = File.open(wasm, "rb") { |file| Wardite::BinaryLoader.load_from_buffer(file, enable_wasi: false, engine: :stack) }
153
+ instance = File.open(wasm, "rb") { |file| Wardite::BinaryLoader.load_from_buffer(file, enable_wasi: false) }
154
154
  #{exports.inspect}.each { |name| puts "\#{name},\#{instance.runtime.call(name, [rounds.to_i, seed.to_i]).value}" }
155
155
  RUBY
156
156
  validation.each do |count, initial|
@@ -158,7 +158,7 @@ validation.each do |count, initial|
158
158
  abort stderr unless status.success?
159
159
  stdout.each_line do |line|
160
160
  name, value = line.strip.split(",")
161
- raise "Old VM mismatch" unless Integer(value) == expected(name, count, initial)
161
+ raise "CRuby mismatch" unless Integer(value) == expected(name, count, initial)
162
162
  end
163
163
  workers.each_value do |worker|
164
164
  exports.each do |name|
@@ -168,7 +168,7 @@ validation.each do |count, initial|
168
168
  end
169
169
  end
170
170
  checksums = exports.to_h { |name| [name, expected(name, rounds, seed)] }
171
- puts "All variants, old VM and reference agree on boundary/control cases."
171
+ puts "All native variants, CRuby and reference agree on boundary/control cases."
172
172
 
173
173
  rows = exports.flat_map do |name|
174
174
  workers.map do |variant, worker|
@@ -0,0 +1,52 @@
1
+ (module
2
+ (memory 1 5)
3
+ (data (i32.const 1) "\ff\dc\80\7f\05\04\f0\02\01\ae\70\e0\50\c0\30\b0")
4
+ (data (i32.const 33) "\19\a0\3d\90\5c\80\6b\70\7a\60\89\50\98\40\a7\30")
5
+
6
+ ;; Grow from one to two pages, leaving one page of reserved capacity in Wardite.
7
+ (func $prepare (param $grow i32)
8
+ local.get $grow
9
+ if i32.const 1 memory.grow drop end)
10
+
11
+ ;; An input byte selects the table entry, as in a codec's decoding loop.
12
+ (func (export "lookup8") (param $rounds i32) (param $grow i32) (result i64)
13
+ (local $sum i64)
14
+ local.get $grow call $prepare
15
+ block $done loop $next
16
+ local.get $rounds i32.eqz br_if $done
17
+ local.get $sum
18
+ local.get $rounds i32.const 15 i32.and i32.load8_u offset=1
19
+ i32.const 15 i32.and i64.load8_u offset=33
20
+ i64.add local.set $sum
21
+ local.get $rounds i32.const 1 i32.sub local.set $rounds
22
+ br $next
23
+ end end
24
+ local.get $sum)
25
+
26
+ (func (export "unaligned64") (param $rounds i32) (param $grow i32) (result i64)
27
+ (local $sum i64)
28
+ local.get $grow call $prepare
29
+ block $done loop $next
30
+ local.get $rounds i32.eqz br_if $done
31
+ local.get $sum
32
+ local.get $rounds i32.const 7 i32.and i64.load offset=1 align=1
33
+ i64.add local.set $sum
34
+ local.get $rounds i32.const 1 i32.sub local.set $rounds
35
+ br $next
36
+ end end
37
+ local.get $sum)
38
+
39
+ (func (export "mixed_width") (param $rounds i32) (param $grow i32) (result i32)
40
+ (local $sum i32)
41
+ local.get $grow call $prepare
42
+ block $done loop $next
43
+ local.get $rounds i32.eqz br_if $done
44
+ local.get $sum
45
+ local.get $rounds i32.const 7 i32.and i32.load offset=1 align=1
46
+ i32.add
47
+ local.get $rounds i32.const 7 i32.and i32.load16_u offset=1 align=1
48
+ i32.add local.set $sum
49
+ local.get $rounds i32.const 1 i32.sub local.set $rounds
50
+ br $next
51
+ end end
52
+ local.get $sum))
@@ -10,10 +10,11 @@ seed = ARGV.fetch(3).to_i
10
10
  disabled = ARGV.fetch(4, "").split(",").map { |name| name.to_sym }
11
11
  started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
12
12
  instance = File.open(wasm, "rb") do |file|
13
- Wardite::BinaryLoader.load_from_buffer(file, enable_wasi: false, engine: :stack)
13
+ Wardite::BinaryLoader.load_from_buffer(file, enable_wasi: false, disabled_optimizations: disabled)
14
14
  end
15
15
  loaded = Process.clock_gettime(Process::CLOCK_MONOTONIC)
16
- vm = Wardite::Efflorescence::VM.new(instance, disabled_optimizations: disabled)
16
+ vm = instance.runtime
17
+ vm.prepare_all
17
18
  translated = Process.clock_gettime(Process::CLOCK_MONOTONIC)
18
19
  before = RUBY_ENGINE == "spinel" ? 0 : GC.stat(:total_allocated_objects)
19
20
  execution_started = Process.clock_gettime(Process::CLOCK_MONOTONIC)