wardite 1.2.0 → 1.2.2

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 (49) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +12 -11
  3. data/benchmark/README.md +13 -5
  4. data/benchmark/call_cost_worker.rb +1 -1
  5. data/benchmark/compare.rb +2 -2
  6. data/benchmark/compare_engines.rb +1 -1
  7. data/benchmark/compare_mir_generation_builds.rb +66 -0
  8. data/benchmark/engine_phases.rb +1 -1
  9. data/benchmark/generate_mir_generation_fixtures.rb +44 -0
  10. data/benchmark/investigate_calls.rb +1 -1
  11. data/benchmark/measure_mir_generation.rb +52 -0
  12. data/benchmark/mir_copy_worker.rb +29 -0
  13. data/benchmark/mir_generation_worker.rb +50 -0
  14. data/benchmark/optimization_worker.rb +1 -1
  15. data/benchmark/prepare_mir_generation_profile.rb +80 -0
  16. data/benchmark/profile_inline_snapshots.rb +63 -0
  17. data/benchmark/profile_mir_generation_allocations.rb +73 -0
  18. data/benchmark/results/mir-generation-adr0014.json +1779 -0
  19. data/benchmark/results/mir-generation-adr0015.json +3132 -0
  20. data/benchmark/results/mir-generation-allocations.json +236 -0
  21. data/benchmark/results/mir-generation-coarse.json +909 -0
  22. data/benchmark/results/mir-generation-control.json +463 -0
  23. data/benchmark/results/mir-generation-detail.json +387 -0
  24. data/benchmark/results/mir-generation-scaling.json +2945 -0
  25. data/benchmark/validate_m4.rb +1 -1
  26. data/docs/adr/0014-efflorescence-mir-build-validation-and-decoding.md +136 -0
  27. data/docs/adr/0015-efflorescence-selective-inline-snapshots.md +150 -0
  28. data/docs/adr/0016-efflorescence-generation-tagged-copy-propagation.md +163 -0
  29. data/docs/efflorescence-ja.md +5 -6
  30. data/docs/efflorescence-mir-build-validation-and-decoding-results.md +93 -0
  31. data/docs/efflorescence-mir-generation-implementation.md +77 -0
  32. data/docs/efflorescence-mir-generation-performance.md +184 -0
  33. data/docs/efflorescence-selective-inline-snapshots-results.md +92 -0
  34. data/docs/efflorescence.md +8 -7
  35. data/lib/wardite/cli/cli.rb +7 -4
  36. data/lib/wardite/efflorescence/ir.rb +119 -37
  37. data/lib/wardite/efflorescence/optimizer.rb +65 -15
  38. data/lib/wardite/efflorescence/register_validation.rb +162 -32
  39. data/lib/wardite/instruction.rb +42 -1
  40. data/lib/wardite/leb128.rb +2 -5
  41. data/lib/wardite/load.rb +152 -74
  42. data/lib/wardite/version.rb +1 -1
  43. data/lib/wardite.rb +1 -1
  44. data/sig/generated/wardite/efflorescence/ir.rbs +29 -1
  45. data/sig/generated/wardite/efflorescence/optimizer.rbs +27 -3
  46. data/sig/generated/wardite/efflorescence/register_validation.rbs +45 -4
  47. data/sig/generated/wardite/instruction.rbs +23 -0
  48. data/sig/generated/wardite/load.rbs +61 -8
  49. metadata +23 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 3b374367cbbab2b2e5f937c73cff6c53df9c62f4c62653d294b28c683b015e59
4
- data.tar.gz: b72512938d20ffdbdbb9537867fa0c631ab6455b51aae271d97f947bcca3126d
3
+ metadata.gz: 3b9acbd0ed033b8f0c6da77501ec5fb8a5840133ab15cb2a1ac031aba04eb20d
4
+ data.tar.gz: 9820acbfc819c417edecc0fdbdea3cd5f35cec8965dd6b12bf45917a68c63707
5
5
  SHA512:
6
- metadata.gz: 1af12383881dc3bac104e53bce974eccdcaef83cb4029b64395c75db05ffc8dc2d4a22030c97ae80a56e100cbe5e13fe56c6cf5e50439d5418c7f8f44448d262
7
- data.tar.gz: 36e9b39213cde17b08235b9036f860a280f8bcc266a029b48c3f2d060387ec9fbe27101e14e3a0dd64e1f38cb5d9348711fe698209025ac3366676967a5a8eb1
6
+ metadata.gz: 87567e5c58345ee263a6eecf8fc9fc2a76f136898d0a2a59a0010c1ea488c4e2e5c9a2c97d9a218dc03bdaf2696907c3db46fa1806f5815b58ce2ef8cc7e60c8
7
+ data.tar.gz: 0da3f82b16f3aa28ab74df0eb3ed16dfb46c1bea780de9f55b7e434bdd1e3c964f10e752fd0cad81def9f83212b9afa07962ca695ca38422174c99264e417ec4
data/README.md CHANGED
@@ -60,18 +60,19 @@ $ wardite examples/test.wasm
60
60
  #=> Test!
61
61
  ```
62
62
 
63
- ### Efflorescence register VM (experimental)
63
+ ### Efflorescence register VM
64
64
 
65
- Use `--new-engine` to select the MIR-based register engine. The stack VM is the
66
- default. The same option is available in Spinel builds.
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.
67
68
 
68
69
  ```sh
69
- wardite --new-engine --no-wasi --invoke add test/add.wasm 100 200
70
+ wardite --no-wasi --invoke add test/add.wasm 100 200
70
71
  # return value: I32(300)
71
72
  ```
72
73
 
73
- In Ruby, pass `engine: :efflorescence` to `Wardite.new` or
74
- `BinaryLoader.load_from_buffer`. Unsupported instructions raise an explicit
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
75
76
  exception. See the [design, supported subset and tests](docs/efflorescence.md)
76
77
  and [engine comparison benchmark](benchmark/README.md).
77
78
 
@@ -82,11 +83,11 @@ Use `--mir-disable NAME` to compare
82
83
  individual features, `--mir-dump` to inspect MIR and `--mir-profile` for counters.
83
84
  See [Phase 2](docs/efflorescence-phase2.md) ([日本語](docs/efflorescence-phase2-ja.md)).
84
85
 
85
- On CRuby and Spinel, pass `--mir-cache DIR` with `--new-engine` to reuse lowered
86
+ On CRuby and Spinel, pass `--mir-cache DIR` to reuse lowered
86
87
  MIR across processes. Use a local directory you control. Each run still decodes
87
88
  the Wasm, links imports, and initializes a fresh instance. `--mir-dump` and
88
- `--mir-profile` build MIR normally. Ruby callers can pass `mir_cache: dir` with
89
- `engine: :efflorescence`. CRuby and Spinel use different cache keys.
89
+ `--mir-profile` build MIR normally. Ruby callers can pass `mir_cache: dir`.
90
+ CRuby and Spinel use different cache keys.
90
91
 
91
92
  The default `--mir-cache-verify checksum` checks the payload size and samples
92
93
  blocks. Use `--mir-cache-verify sha256` or Ruby's `mir_cache_verify: :sha256`
@@ -99,7 +100,7 @@ can go undetected in checksum mode, including changes that leave the MIR
99
100
  structurally valid.
100
101
  [MIR2 cache measurements](docs/efflorescence-mir2-cache.md)
101
102
 
102
- For WASI commands, `--snapshot DIR` (with `--new-engine --mir-cache DIR`) saves
103
+ For WASI commands, `--snapshot DIR` (with `--mir-cache DIR`) saves
103
104
  the guest state just before its first WASI call that reads files or writes output,
104
105
  and later runs with the same Wasm, arguments, environment, preopens and stdio
105
106
  kinds resume from there. Clock values and random bytes read before that point
@@ -159,7 +160,7 @@ $ make spinel-test
159
160
 
160
161
  The executable enables the shared WASI Preview 1 host by default. Use
161
162
  `--no-wasi` to disable it. To boot a Ruby 4.0.9 WASI binary, run
162
- `build/wardite --new-engine -- "$ruby_wasm" --disable-gems -e 'puts 6*7'`.
163
+ `build/wardite -- "$ruby_wasm" --disable-gems -e 'puts 6*7'`.
163
164
  See the [ruby.wasm verification record](docs/efflorescence-ruby-wasm-phase1.md)
164
165
  for the build and file-loading commands. Vernier profiling is available in the
165
166
  CRuby build. Ruby's dynamic export helpers (`instance.add(...)` and
data/benchmark/README.md CHANGED
@@ -6,6 +6,14 @@ 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
+ ## MIR generation before caching
10
+
11
+ [MIR生成性能調査(日本語)](../docs/efflorescence-mir-generation-performance.md)
12
+ separates Wasm decoding, translation, optimization, register validation, and
13
+ lowering on CRuby and Spinel. It includes a reproducible timer-instrumented
14
+ source-copy build, raw measurements, allocation profiling, and i32 scaling
15
+ fixtures. See the report for commands and measurement boundaries.
16
+
9
17
  ## M2 memory and global validation
10
18
 
11
19
  ```sh
@@ -176,7 +184,7 @@ The report `build/benchmark/optimizations.json` contains raw samples, phase and
176
184
  whole-process means, CRuby execution allocations and per-opcode counters.
177
185
  Time measurement does not enable MIR counters. Both phase and CLI measurements
178
186
  include the same Ruby-facing boxed return boundary. Spinel allocations are `n/a`.
179
- The shared phase loader creates the default runtime, then the selected MIR VM is
187
+ The shared phase loader creates the stack VM, then the selected MIR VM is
180
188
  constructed in the MIR phase; the fixture has no start function. Phase timing
181
189
  uses a separate executable, whose Spinel inference can differ from the CLI.
182
190
  `SPINEL` and `SPINELFLAGS` choose the compiler/flags (default `-O2`).
@@ -315,11 +323,11 @@ Results include whole CLI process time and separate load, MIR translation and
315
323
  execution times from `engine_phases.rb`, compiled unchanged by Spinel. Phase
316
324
  timings come from a separate process per sample, with one call per process;
317
325
  they include frame setup and the final Ruby-facing result box. The loader phase
318
- creates the shared instance with the default runtime; the fixture has no start
326
+ creates the shared instance with the stack VM; the fixture has no start
319
327
  function, so it executes no guest instructions. For Efflorescence, the next
320
328
  phase constructs the selected VM from that instance (including a second, empty
321
329
  Runtime setup for stack samples). End-to-end samples use the real
322
- CLI with `--new-engine` and therefore include normal engine selection, startup,
330
+ CLI and include engine selection, startup,
323
331
  load, translation, execution and output. Warmups are separate processes, so YJIT
324
332
  compiles anew for each sample. Native compilation is outside measurement.
325
333
  Phase values are diagnostic and do not sum to the CLI time: they use a separate
@@ -401,8 +409,8 @@ YJIT support is required only when its runner is enabled.
401
409
 
402
410
  | Engine | Execution configurations |
403
411
  | --- | --- |
404
- | Old VM (`Wardite::Runtime`) | CRuby (YJIT disabled), CRuby + YJIT, Spinel |
405
- | New VM (`Wardite::Efflorescence::VM`) | CRuby (YJIT disabled), CRuby + YJIT, Spinel; `--new-engine`, default optimizations |
412
+ | Old VM (`Wardite::Runtime`) | CRuby (YJIT disabled), CRuby + YJIT, Spinel; `--stack-engine` |
413
+ | New VM (`Wardite::Efflorescence::VM`) | CRuby (YJIT disabled), CRuby + YJIT, Spinel; default engine and optimizations |
406
414
  | iwasm / WAMR | Explicit interpreter mode (`--interp`) |
407
415
  | Wasmtime (Pulley) | `--target pulley64 -C cache=n` |
408
416
  | Wasmtime | Native compilation, `-C cache=n` |
@@ -13,7 +13,7 @@ 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)
16
+ Wardite::BinaryLoader.load_from_buffer(file, enable_wasi: false, engine: :stack)
17
17
  end
18
18
  loaded = Process.clock_gettime(Process::CLOCK_MONOTONIC)
19
19
  vm = Wardite::Efflorescence::VM.new(instance, disabled_optimizations: disabled, profile: profile)
data/benchmark/compare.rb CHANGED
@@ -37,8 +37,8 @@ wardite_runners = {
37
37
  }
38
38
  runners = {}
39
39
  wardite_runners.each do |runtime, command|
40
- # runners["Old VM / #{runtime}"] = [:wardite, command]
41
- runners["New VM / #{runtime}"] = [:wardite, command + ["--new-engine"]]
40
+ # runners["Old VM / #{runtime}"] = [:wardite, command + ["--stack-engine"]]
41
+ runners["New VM / #{runtime}"] = [:wardite, command]
42
42
  end
43
43
  runners["iwasm (WAMR interpreter)"] = [:iwasm, ["iwasm", "--interp"]]
44
44
  runners["Wasmtime (Pulley)"] = [:wasmtime, ["wasmtime", "run", "--target", "pulley64", "-C", "cache=n"]]
@@ -44,7 +44,7 @@ runtimes["CRuby + YJIT"] = [RbConfig.ruby, "--yjit", "-Ilib"] if yjit.success?
44
44
  def cli_command(runner, engine, export, wasm, rounds, seed)
45
45
  command = runner.dup
46
46
  command << "exe/wardite" unless runner.first == "./build/wardite"
47
- command << "--new-engine" if engine == "efflorescence"
47
+ command << "--stack-engine" if engine == "stack"
48
48
  command + ["--no-wasi", "--invoke", export, "--", wasm, rounds.to_s, seed.to_s]
49
49
  end
50
50
 
@@ -0,0 +1,66 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Usage: ruby benchmark/compare_mir_generation_builds.rb BEFORE=DIR AFTER=DIR ... -- WASM...
4
+ # Build each directory with prepare_mir_generation_profile.rb and the same Spinel -O2.
5
+ require "digest"
6
+ require "json"
7
+ require "open3"
8
+ require "rbconfig"
9
+
10
+ separator = ARGV.index("--") || abort("Separate builds from fixtures with --")
11
+ builds = ARGV.take(separator).to_h do |argument|
12
+ name, directory = argument.split("=", 2)
13
+ abort "Expected NAME=DIR: #{argument}" unless directory && !name.empty?
14
+ [name, File.expand_path(directory)]
15
+ end
16
+ fixtures = ARGV.drop(separator + 1)
17
+ abort "Supply at least two builds and one fixture" unless builds.size >= 2 && !fixtures.empty?
18
+ runs = Integer(ENV.fetch("RUNS", "5"))
19
+ warmups = Integer(ENV.fetch("WARMUPS", "1"))
20
+ abort "Invalid sample counts" unless runs > 0 && warmups >= 0
21
+ runtime = ENV.fetch("RUNTIME", "spinel")
22
+ abort "Unknown runtime: #{runtime}" unless %w[cruby spinel].include?(runtime)
23
+ timer = ENV["RSS"] == "1" ? ["/usr/bin/time", "-l"] : []
24
+ stats_columns = %w[functions instructions optimized_instructions registers max_registers eligible_functions eligible_instructions]
25
+
26
+ report = fixtures.to_h do |fixture|
27
+ checksum = Digest::SHA256.file(fixture).hexdigest
28
+ expected_stats = nil
29
+ samples = []
30
+ (warmups + runs).times do |iteration|
31
+ # Reverse each pair of runs and rotate positions when comparing several stages.
32
+ order = builds.to_a
33
+ order.rotate!(iteration / 2) if order.size > 2
34
+ order.reverse! if iteration.odd?
35
+ order.each do |name, directory|
36
+ command = if runtime == "spinel"
37
+ ["#{directory}/worker"]
38
+ else
39
+ [RbConfig.ruby, "-I#{directory}/lib", "#{directory}/mir_generation_worker.rb"]
40
+ end
41
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
42
+ stdout, stderr, status = Open3.capture3(*timer, *command, fixture, "default")
43
+ elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
44
+ abort "#{command.inspect} failed\n#{stdout}\n#{stderr}" unless status.success?
45
+ rows = stdout.lines.map { |line| line.strip.split(",") }
46
+ stats = rows.select { |column, _, _| stats_columns.include?(column) }.to_h { |column, value| [column, Integer(value)] }
47
+ expected_stats ||= stats
48
+ abort "IR counts differ for #{fixture} in #{name}" unless stats == expected_stats
49
+ phase_rows = rows.reject { |column, _, _| stats_columns.include?(column) }
50
+ seconds = phase_rows.to_h { |column, value, _| [column, Float(value)] }
51
+ calls = phase_rows.to_h { |column, _, count| [column, Integer(count)] }
52
+ rss = stderr[/^\s*(\d+)\s+maximum resident set size$/, 1]
53
+ run = iteration - warmups + 1
54
+ warn "#{File.basename(fixture)} #{name} #{run}: #{seconds.fetch('total').round(5)} s"
55
+ if iteration >= warmups
56
+ samples << {build: name, run: run, process_seconds: elapsed,
57
+ phases_seconds: seconds, calls: calls, peak_rss_bytes: rss && Integer(rss)}
58
+ end
59
+ end
60
+ end
61
+ [fixture, {sha256: checksum, bytes: File.size(fixture), ir_counts: expected_stats, samples: samples}]
62
+ end
63
+
64
+ puts JSON.generate(runtime: runtime, runs: runs, warmups: warmups,
65
+ timing: "cache disabled; total is load_from_buffer; process includes startup and statistics",
66
+ fixtures: report)
@@ -12,7 +12,7 @@ rounds = ARGV.fetch(3).to_i
12
12
  seed = ARGV.fetch(4).to_i
13
13
  started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
14
14
  instance = File.open(wasm, "rb") do |file|
15
- Wardite::BinaryLoader.load_from_buffer(file, enable_wasi: false)
15
+ Wardite::BinaryLoader.load_from_buffer(file, enable_wasi: false, engine: :stack)
16
16
  end
17
17
  loaded = Process.clock_gettime(Process::CLOCK_MONOTONIC)
18
18
  if engine == "efflorescence"
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "fileutils"
4
+ directory = File.expand_path(ARGV.fetch(0))
5
+ FileUtils.mkdir_p(directory)
6
+ [256, 512, 1024, 2048, 4096, 8192].each do |size|
7
+ path = File.join(directory, "i32-chain-#{size}")
8
+ File.write("#{path}.wat", <<~WAT)
9
+ (module
10
+ (func (export "run") (param i32) (result i32)
11
+ #{'local.get 0 i32.const 1 i32.add local.set 0 ' * size}
12
+ local.get 0))
13
+ WAT
14
+ abort "wasm-tools failed" unless system("wasm-tools", "parse", "#{path}.wat", "-o", "#{path}.wasm")
15
+ end
16
+
17
+ # Scale exception-flow validation while keeping each function small.
18
+ path = File.join(directory, "eh-512")
19
+ File.open("#{path}.wat", "w") do |wat|
20
+ wat.puts "(module (tag $e (param i32)) (func $raise i32.const 42 throw $e)"
21
+ 512.times do |index|
22
+ export = index.zero? ? '(export "run")' : ""
23
+ wat.puts <<~WAT
24
+ (func #{export} (result i32)
25
+ block $done (result i32)
26
+ #{'try_table (catch $e $done) call $raise end ' * 32}
27
+ i32.const 0
28
+ end)
29
+ WAT
30
+ end
31
+ wat.puts ")"
32
+ end
33
+ abort "wasm-tools failed" unless system("wasm-tools", "parse", "#{path}.wat", "-o", "#{path}.wasm")
34
+
35
+ # Many static CALL sites to one eligible leaf exceed the per-caller budget.
36
+ path = File.join(directory, "inline-dense")
37
+ File.write("#{path}.wat", <<~WAT)
38
+ (module
39
+ (func $leaf (param i32) (result i32) local.get 0 i32.const 1 i32.add)
40
+ (func (export "run") (param i32) (result i32)
41
+ #{'local.get 0 call $leaf local.set 0 ' * 256}
42
+ local.get 0))
43
+ WAT
44
+ abort "wasm-tools failed" unless system("wasm-tools", "parse", "#{path}.wat", "-o", "#{path}.wasm")
@@ -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) }
153
+ instance = File.open(wasm, "rb") { |file| Wardite::BinaryLoader.load_from_buffer(file, enable_wasi: false, engine: :stack) }
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|
@@ -0,0 +1,52 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Usage: ruby benchmark/measure_mir_generation.rb BUILD_DIR WASM...
4
+ # BUILD_DIR contains the generated worker.rb and optionally a Spinel `worker`.
5
+ require "json"
6
+ require "open3"
7
+ require "digest"
8
+ require "rbconfig"
9
+
10
+ directory = File.expand_path(ARGV.shift || abort("Missing build directory"))
11
+ abort "Missing Wasm fixtures" if ARGV.empty?
12
+ runs = Integer(ENV.fetch("RUNS", "5"))
13
+ warmups = Integer(ENV.fetch("WARMUPS", "1"))
14
+ abort "Invalid sample counts" unless runs > 0 && warmups >= 0
15
+ commands = {
16
+ "cruby" => [RbConfig.ruby, "-I#{directory}/lib", "#{directory}/mir_generation_worker.rb"],
17
+ "spinel" => ["#{directory}/worker"]
18
+ }
19
+ commands.select! { |runtime, _| ENV.fetch("RUNTIMES", "cruby,spinel").split(",").include?(runtime) }
20
+ variants = ENV.fetch("VARIANTS", "default").split(",")
21
+ abort "Unknown variant" unless (variants - %w[default no-inline]).empty?
22
+ fixtures = ARGV.map { |path| File.expand_path(path) }
23
+ samples = []
24
+ fixtures.each do |fixture|
25
+ expected_stats = {}
26
+ (warmups + runs).times do |iteration|
27
+ commands.to_a.product(variants).rotate(iteration).each do |(runtime, command), variant|
28
+ timer = ENV["RSS"] == "1" ? ["/usr/bin/time", "-l"] : []
29
+ stdout, stderr, status = Open3.capture3(*timer, *command, fixture, variant)
30
+ abort "#{command.inspect}: #{stdout}\n#{stderr}" unless status.success?
31
+ rows = stdout.lines.map { |line| line.strip.split(",") }
32
+ phases = rows.to_h { |name, seconds, count| [name, {value: Float(seconds), calls: Integer(count)}] }
33
+ abort "Missing total" unless phases.key?("total")
34
+ stats = phases.select { |name, _| %w[functions instructions optimized_instructions registers max_registers eligible_functions eligible_instructions].include?(name) }
35
+ expected_stats[variant] ||= stats
36
+ abort "Inconsistent IR counts for #{fixture}" unless stats == expected_stats[variant]
37
+ rss = stderr[/^\s*(\d+)\s+maximum resident set size$/, 1]
38
+ sample = {fixture: fixture, runtime: runtime, variant: variant, run: iteration - warmups + 1,
39
+ phases: phases, peak_rss_bytes: rss && Integer(rss)}
40
+ warn "#{File.basename(fixture)} #{runtime} #{variant} #{sample[:run]}: #{phases['total'][:value].round(4)} s"
41
+ samples << sample if iteration >= warmups
42
+ end
43
+ end
44
+ end
45
+ puts JSON.pretty_generate(
46
+ revision: IO.popen(["git", "rev-parse", "HEAD"], &:read).strip,
47
+ ruby: RUBY_DESCRIPTION, directory: directory, commands: commands,
48
+ runs: runs, warmups: warmups, variants: variants,
49
+ timing: "load_from_buffer only; no cache or export execution; nested detail timers are inclusive",
50
+ fixtures: fixtures.to_h { |path| [path, {bytes: File.size(path), sha256: Digest::SHA256.file(path).hexdigest}] },
51
+ samples: samples
52
+ )
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ # Measure Function#copy with independently controlled register and constant counts.
5
+ require "wardite"
6
+
7
+ registers = ARGV.fetch(0).to_i
8
+ constants = ARGV.fetch(1).to_i
9
+ copies = ARGV.fetch(2).to_i
10
+ raise "invalid copy workload" unless registers >= constants && constants >= 0 && copies > 0
11
+
12
+ source = Wardite::Efflorescence::Function.new(0, [], [], 0)
13
+ register = 0
14
+ while register < registers
15
+ if register < constants
16
+ source.allocate_constant(register)
17
+ else
18
+ source.allocate_register(register)
19
+ end
20
+ register += 1
21
+ end
22
+
23
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
24
+ copies.times do
25
+ copy = source.copy
26
+ raise "register copy differs" unless copy.initial_registers == source.initial_registers &&
27
+ copy.constant_registers == source.constant_registers
28
+ end
29
+ puts Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ # Run from the directory generated by prepare_mir_generation_profile.rb.
5
+ # No cache, snapshot, MIR execution profiling, or exported guest execution.
6
+ require_relative "measurement"
7
+ require "pp"
8
+ # Spinel resolves requires statically; preload method-local dependencies.
9
+ # CRuby needs ValueHelper defined before loading the WASI class.
10
+ require "wardite/value" if RUBY_ENGINE != "spinel"
11
+ require "wardite/wasi"
12
+ require "wardite"
13
+
14
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
15
+ instance = File.open(ARGV.fetch(0), "rb") do |file|
16
+ Wardite::BinaryLoader.load_from_buffer(file, engine: :efflorescence,
17
+ disabled_optimizations: ARGV[1] == "no-inline" ? [:inline] : [])
18
+ end
19
+ elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
20
+ raise "Use a fixture without a start section" if instance.start_section
21
+ puts "total,#{elapsed},1"
22
+ MirGenerationMeasurement::NAMES.each_with_index do |name, index|
23
+ puts "#{name},#{MirGenerationMeasurement::SECONDS[index]},#{MirGenerationMeasurement::COUNTS[index]}"
24
+ end
25
+
26
+ vm = instance.runtime
27
+ raise "Expected MIR VM" unless vm.is_a?(Wardite::Efflorescence::VM)
28
+ instructions = 0
29
+ registers = 0
30
+ eligible = 0
31
+ eligible_instructions = 0
32
+ max_registers = 0
33
+ vm.semantic_ir.functions.each do |function|
34
+ instructions += function.instructions.size
35
+ registers += function.register_count
36
+ max_registers = function.register_count if function.register_count > max_registers
37
+ unless function.uses_i64 || function.uses_float || function.uses_eh || function.uses_store || function.uses_dynamic_calls
38
+ eligible += 1
39
+ eligible_instructions += function.instructions.size
40
+ end
41
+ end
42
+ optimized_instructions = 0
43
+ vm.ir.functions.each { |function| optimized_instructions += function.instructions.size }
44
+ puts "functions,#{vm.ir.functions.size},0"
45
+ puts "instructions,#{instructions},0"
46
+ puts "optimized_instructions,#{optimized_instructions},0"
47
+ puts "registers,#{registers},0"
48
+ puts "max_registers,#{max_registers},0"
49
+ puts "eligible_functions,#{eligible},0"
50
+ puts "eligible_instructions,#{eligible_instructions},0"
@@ -10,7 +10,7 @@ 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)
13
+ Wardite::BinaryLoader.load_from_buffer(file, enable_wasi: false, engine: :stack)
14
14
  end
15
15
  loaded = Process.clock_gettime(Process::CLOCK_MONOTONIC)
16
16
  vm = Wardite::Efflorescence::VM.new(instance, disabled_optimizations: disabled)
@@ -0,0 +1,80 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Insert timers into a disposable source copy (also compilable with Spinel).
4
+ # Usage: ruby benchmark/prepare_mir_generation_profile.rb BUILD_DIR [detail|none]
5
+ require "fileutils"
6
+ require "prism"
7
+
8
+ root = File.expand_path("..", __dir__)
9
+ destination = File.expand_path(ARGV.fetch(0))
10
+ abort "Use a new output directory" if File.exist?(destination)
11
+ detail = ARGV[1] == "detail"
12
+ abort "Unknown instrumentation mode" unless ARGV[1].nil? || %w[detail none].include?(ARGV[1])
13
+ instrument = ARGV[1] != "none"
14
+ targets = {
15
+ "Wardite::BinaryLoader.sections" => "sections",
16
+ "Wardite::CodeSection::CodeBody.check_features" => "features",
17
+ "Wardite::Store.initialize" => "store",
18
+ "Wardite::Efflorescence::Translator.link" => "link",
19
+ "Wardite::Efflorescence::Translator.translate" => "translate",
20
+ "Wardite::Efflorescence::Optimizer.optimize" => "optimize",
21
+ "Wardite::Efflorescence::RegisterValidation.validate" => "validate",
22
+ "Wardite::Efflorescence::Lowerer.compile" => "lower"
23
+ }
24
+ if detail
25
+ targets.merge!({
26
+ "Wardite::BinaryLoader.decode_body" => "code_body",
27
+ "Wardite::Efflorescence::RegisterValidation.validate_plain" => "validate_plain",
28
+ "Wardite::Efflorescence::RegisterValidation.block_reverse_postorder" => "block_reverse_postorder",
29
+ "Wardite::Efflorescence::IR.copy" => "ir_copy",
30
+ "Wardite::Efflorescence::Passes::Inlining.run" => "inline",
31
+ "Wardite::Efflorescence::Passes::CopyPropagation.run" => "copy_pass",
32
+ "Wardite::Efflorescence::Passes::CopyPropagation.propagate" => "propagate",
33
+ "Wardite::Efflorescence::Passes::ImmediateSpecialization.run" => "immediate",
34
+ "Wardite::Efflorescence::Passes::BranchFusion.run" => "branch",
35
+ "Wardite::Efflorescence::Passes::Superinstructions.run" => "superinstruction",
36
+ "Wardite::Efflorescence::Analysis.initialize" => "analysis",
37
+ "Wardite::Efflorescence::FlowGraph.initialize" => "flow_graph",
38
+ "Wardite::Efflorescence::RegisterValidation.validate_types" => "validate_types",
39
+ "Wardite::Efflorescence::RegisterValidation.reverse_postorder" => "reverse_postorder"
40
+ })
41
+ end
42
+ FileUtils.mkdir_p(destination)
43
+ FileUtils.cp_r(File.join(root, "lib"), destination)
44
+ found = []
45
+ Dir[File.join(destination, "lib/**/*.rb")].each do |path|
46
+ next unless instrument
47
+ source = File.binread(path)
48
+ edits = []
49
+ walk = lambda do |node, nesting|
50
+ if node.is_a?(Prism::ClassNode) || node.is_a?(Prism::ModuleNode)
51
+ nesting = [*nesting, node.constant_path.slice]
52
+ elsif node.is_a?(Prism::DefNode)
53
+ key = "#{nesting.join('::')}.#{node.name}"
54
+ if (label = targets[key])
55
+ abort "Already has ensure: #{key}" if node.body.is_a?(Prism::BeginNode) && node.body.ensure_clause
56
+ id = targets.values.index(label)
57
+ body = node.body.is_a?(Prism::BeginNode) ? node.body.statements : node.body
58
+ edits << [body.location.start_offset, "mir_measure_started = Process.clock_gettime(Process::CLOCK_MONOTONIC)\n"]
59
+ edits << [node.end_keyword_loc.start_offset, "ensure\nMirGenerationMeasurement::SECONDS[#{id}] += Process.clock_gettime(Process::CLOCK_MONOTONIC) - mir_measure_started\nMirGenerationMeasurement::COUNTS[#{id}] += 1\n"]
60
+ found << key
61
+ end
62
+ end
63
+ node.compact_child_nodes.each { |child| walk.call(child, nesting) }
64
+ end
65
+ walk.call(Prism.parse(source).value, [])
66
+ edits.sort_by(&:first).reverse_each { |offset, text| source.insert(offset, text) }
67
+ File.binwrite(path, source) unless edits.empty?
68
+ end
69
+ abort "Missing instrumentation: #{targets.keys - found}" if instrument && !(targets.keys - found).empty?
70
+ File.write(File.join(destination, "measurement.rb"), <<~RUBY)
71
+ # frozen_string_literal: true
72
+ # rbs_inline: enabled
73
+ module MirGenerationMeasurement
74
+ NAMES = #{targets.values.inspect}.freeze
75
+ SECONDS = Array.new(#{targets.size}, 0.0) #: Array[Float]
76
+ COUNTS = Array.new(#{targets.size}, 0) #: Array[Integer]
77
+ end
78
+ RUBY
79
+ FileUtils.cp(File.join(root, "benchmark/mir_generation_worker.rb"), destination)
80
+ puts destination
@@ -0,0 +1,63 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Count structural work in one cache-disabled load, separately from timings.
4
+ require "digest"
5
+ require "json"
6
+ require "wardite"
7
+
8
+ wasm = ARGV.fetch(0)
9
+ disabled = ARGV[1] == "no-inline" ? [:inline] : []
10
+ eff = Wardite::Efflorescence
11
+ inlining = eff::Passes::Inlining
12
+ counts = {
13
+ ir_copies: 0, inline_runs: 0, expected: [0, 0, 0], snapshots: [0, 0, 0],
14
+ copied_noncandidates: 0, rewrites: 0, changed_callers: 0
15
+ }
16
+ active = false
17
+
18
+ def count_function(stats, function)
19
+ stats[0] += 1
20
+ stats[1] += function.instructions.size
21
+ stats[2] += function.register_count
22
+ end
23
+
24
+ ir_copies = TracePoint.new(:call) { counts[:ir_copies] += 1 }
25
+ run = TracePoint.new(:call, :return) do |event|
26
+ if event.event == :call
27
+ counts[:inline_runs] += 1
28
+ active = true
29
+ event.binding.local_variable_get(:ir).functions.each do |function|
30
+ count_function(counts[:expected], function) if event.self.send(:eligible?, function)
31
+ end
32
+ else
33
+ active = false
34
+ counts[:changed_callers] += event.return_value.size
35
+ end
36
+ end
37
+
38
+ # eligible? is stateless. Reuse it for the diagnostic without changing any IR.
39
+ predicate = inlining.new
40
+ snapshot = TracePoint.new(:call) do |event|
41
+ if active
42
+ count_function(counts[:snapshots], event.self)
43
+ counts[:copied_noncandidates] += 1 unless predicate.send(:eligible?, event.self)
44
+ end
45
+ end
46
+ rewrites = TracePoint.new(:call) { counts[:rewrites] += 1 if active }
47
+
48
+ traces = {
49
+ ir_copies => eff::IR.instance_method(:copy),
50
+ run => inlining.instance_method(:run),
51
+ snapshot => eff::Function.instance_method(:copy),
52
+ rewrites => eff::Rewrite.instance_method(:initialize)
53
+ }
54
+ begin
55
+ traces.each { |trace, target| trace.enable(target: target) }
56
+ File.open(wasm, "rb") do |file|
57
+ Wardite::BinaryLoader.load_from_buffer(file, engine: :efflorescence, disabled_optimizations: disabled)
58
+ end
59
+ ensure
60
+ traces.each_key(&:disable)
61
+ end
62
+ puts JSON.generate(sha256: Digest::SHA256.file(wasm).hexdigest, disabled: disabled,
63
+ count_order: %w[functions instructions registers], counts: counts)
@@ -0,0 +1,73 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Diagnostic CRuby run; allocations and inclusive times, not native timings.
4
+ require "json"
5
+ require "digest"
6
+ require "wardite"
7
+ require "vernier"
8
+
9
+ module GenerationAllocations
10
+ TOTALS = Hash.new { |hash, key| hash[key] = {seconds: 0.0, objects: 0, calls: 0} }
11
+ FUNCTIONS = []
12
+
13
+ def self.wrap(klass, method, name)
14
+ klass.prepend(Module.new do
15
+ define_method(method) do |*args, **kwargs, &block|
16
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
17
+ allocated = GC.stat(:total_allocated_objects)
18
+ begin
19
+ super(*args, **kwargs, &block)
20
+ ensure
21
+ seconds = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
22
+ objects = GC.stat(:total_allocated_objects) - allocated
23
+ total = TOTALS[name]
24
+ total[:seconds] += seconds
25
+ total[:objects] += objects
26
+ total[:calls] += 1
27
+ if name == :validate
28
+ function = args.first
29
+ FUNCTIONS << {index: function.index, seconds: seconds, objects: objects,
30
+ instructions: function.instructions.size, registers: function.register_count}
31
+ end
32
+ end
33
+ end
34
+ private method if klass.private_method_defined?(method)
35
+ end)
36
+ end
37
+ end
38
+
39
+ eff = Wardite::Efflorescence
40
+ decode_method = Wardite::BinaryLoader.respond_to?(:decode_body) ? :decode_body : :code_body
41
+ revision = ENV.fetch("MIR_GENERATION_REVISION") { IO.popen(["git", "rev-parse", "HEAD"], &:read).strip }
42
+ [
43
+ [Wardite::BinaryLoader.singleton_class, :sections, :sections],
44
+ [Wardite::BinaryLoader.singleton_class, decode_method, :code_body],
45
+
46
+ [Wardite::CodeSection::CodeBody, :check_features, :features],
47
+ [eff::Translator, :translate, :translate],
48
+ [eff::Optimizer, :optimize, :optimize],
49
+ [eff::IR, :copy, :ir_copy],
50
+ [eff::Passes::Inlining, :run, :inline],
51
+
52
+ [eff::RegisterValidation, :validate, :validate],
53
+ [eff::RegisterValidation, :validate_types, :validate_types],
54
+ [eff::Analysis, :initialize, :analysis],
55
+ [eff::FlowGraph, :initialize, :flow_graph],
56
+ [eff::Lowerer, :compile, :lower]
57
+ ].each { |klass, method, name| GenerationAllocations.wrap(klass, method, name) }
58
+ fixture = File.expand_path(ARGV.fetch(0))
59
+ before = GC.stat
60
+ profile = Vernier.profile do
61
+ instance = File.open(fixture, "rb") { |file| Wardite::BinaryLoader.load_from_buffer(file, engine: :efflorescence) }
62
+ raise "Use a fixture without a start section" if instance.start_section
63
+ end
64
+ after = GC.stat
65
+ File.write(ARGV.fetch(1), JSON.pretty_generate(
66
+ ruby: RUBY_DESCRIPTION, vernier: Vernier::VERSION,
67
+ fixture: {path: fixture, sha256: Digest::SHA256.file(fixture).hexdigest},
68
+ revision: revision,
69
+ phases_inclusive: GenerationAllocations::TOTALS,
70
+ gc_delta: before.keys.to_h { |key| [key, after[key] - before[key]] },
71
+ slowest_validation: GenerationAllocations::FUNCTIONS.sort_by { |row| -row[:seconds] }.take(20),
72
+ top_self_samples: Vernier::Output::Top.new(profile).output
73
+ ))