wardite 1.1.0 → 1.2.1

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 (57) hide show
  1. checksums.yaml +4 -4
  2. data/Makefile +9 -1
  3. data/README.md +36 -4
  4. data/benchmark/README.md +8 -0
  5. data/benchmark/compare_mir_generation_builds.rb +66 -0
  6. data/benchmark/count_ruby_wasm_functions.rb +37 -0
  7. data/benchmark/generate_mir_generation_fixtures.rb +44 -0
  8. data/benchmark/measure_mir_cache_restore.rb +59 -0
  9. data/benchmark/measure_mir_generation.rb +52 -0
  10. data/benchmark/mir_copy_worker.rb +29 -0
  11. data/benchmark/mir_generation_worker.rb +50 -0
  12. data/benchmark/prepare_mir_generation_profile.rb +80 -0
  13. data/benchmark/profile_inline_snapshots.rb +63 -0
  14. data/benchmark/profile_mir_generation_allocations.rb +73 -0
  15. data/benchmark/results/efflorescence-mir2-function-restore.json +480 -0
  16. data/benchmark/results/mir-generation-adr0014.json +1779 -0
  17. data/benchmark/results/mir-generation-adr0015.json +3132 -0
  18. data/benchmark/results/mir-generation-allocations.json +236 -0
  19. data/benchmark/results/mir-generation-coarse.json +909 -0
  20. data/benchmark/results/mir-generation-control.json +463 -0
  21. data/benchmark/results/mir-generation-detail.json +387 -0
  22. data/benchmark/results/mir-generation-scaling.json +2945 -0
  23. data/docs/adr/0009-efflorescence-mir2-cache-integrity-modes.md +1 -1
  24. data/docs/adr/0010-efflorescence-mir2-cache-function-restore.md +1 -1
  25. data/docs/adr/0014-efflorescence-mir-build-validation-and-decoding.md +136 -0
  26. data/docs/adr/0015-efflorescence-selective-inline-snapshots.md +150 -0
  27. data/docs/adr/0016-efflorescence-generation-tagged-copy-propagation.md +163 -0
  28. data/docs/efflorescence-mir-build-validation-and-decoding-results.md +93 -0
  29. data/docs/efflorescence-mir-generation-implementation.md +77 -0
  30. data/docs/efflorescence-mir-generation-performance.md +184 -0
  31. data/docs/efflorescence-mir2-cache.md +31 -2
  32. data/docs/efflorescence-selective-inline-snapshots-results.md +92 -0
  33. data/docs/efflorescence-spinel-linear-memory.md +6 -4
  34. data/lib/wardite/cli/cli.rb +3 -1
  35. data/lib/wardite/efflorescence/ir.rb +131 -40
  36. data/lib/wardite/efflorescence/mir_cache.rb +165 -73
  37. data/lib/wardite/efflorescence/optimizer.rb +65 -15
  38. data/lib/wardite/efflorescence/register_validation.rb +162 -32
  39. data/lib/wardite/efflorescence/snapshot.rb +5 -2
  40. data/lib/wardite/efflorescence/vm.rb +4 -3
  41. data/lib/wardite/instruction.rb +42 -1
  42. data/lib/wardite/leb128.rb +2 -5
  43. data/lib/wardite/load.rb +154 -75
  44. data/lib/wardite/version.rb +1 -1
  45. data/lib/wardite.rb +1 -1
  46. data/scripts/build_spinel_zig.rb +121 -0
  47. data/sig/generated/wardite/efflorescence/ir.rbs +34 -3
  48. data/sig/generated/wardite/efflorescence/mir_cache.rbs +41 -14
  49. data/sig/generated/wardite/efflorescence/optimizer.rbs +27 -3
  50. data/sig/generated/wardite/efflorescence/register_validation.rbs +45 -4
  51. data/sig/generated/wardite/efflorescence/snapshot.rbs +2 -1
  52. data/sig/generated/wardite/instruction.rbs +23 -0
  53. data/sig/generated/wardite/load.rbs +63 -9
  54. data/sig/io_buffer.rbs +7 -0
  55. metadata +28 -3
  56. data/spinel/patches/0001-io-buffer-string-view.patch +0 -699
  57. data/spinel/patches/0002-io-buffer-allocation-error.patch +0 -47
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: e8542bfea8c7d257afcc7c5d9fa9f97dc816f18d462eadbee9ea6f2298c8f0f8
4
- data.tar.gz: 4dd3f1a5661c85295c1c38d07c424bfd5d1e979b6a8fa5d5efeb30a920696c85
3
+ metadata.gz: 60361b89872ee557e6965a87ad06a1fe478c839c7491da1cbe38fb3ca9ae6911
4
+ data.tar.gz: 7a858b3af7e6d17bd87ed35620adc2d43fc62e8fefb2a4cddc7343024200218f
5
5
  SHA512:
6
- metadata.gz: 440f1234f039438fd744c46bbac0fc9280e7324863130dee3930474a20ace221d35c6e6437d2dec2e2d7c8568738d664982c84bcfe76440c12a9021c4cf07f5a
7
- data.tar.gz: dc114ee14a8412a674e724942a7ad6d8eaaad5af9debeeef2ef9a43dd5ee6322bd5e5ed32a87a75b02801f55081d15e0d6f2c1be262ea25783756234f7e85112
6
+ metadata.gz: 1755d6cf49df46dc1745056dfe1c134eaf573d23e22e943ae49aabe096219f4197d8b85458c5ba46183bdd6f06bee4fe457511565f1b893efb1385387c4a5452
7
+ data.tar.gz: 63a013a543b1d253c5191acf4a8469edeeaa5e44326a9fd2f947f92c307f7f2907d5d52b9c211010526735372f2f298d9a596365458306e96bb5100c52bfd0b6
data/Makefile CHANGED
@@ -2,8 +2,13 @@ SPINEL ?= spinel
2
2
  SPINELFLAGS ?= -O2
3
3
  RUBY ?= ruby
4
4
  BUILD_DIR ?= build
5
+ ZIG ?= zig
6
+ ZIG_GLIBC ?= 2.28
7
+ ZIG_MACOS ?= 13.0
8
+ ZIG_JOBS ?= 8
9
+ ZIG_TARGETS ?= aarch64-macos x86_64-linux aarch64-linux
5
10
 
6
- .PHONY: spinel spinel-test
11
+ .PHONY: spinel spinel-test spinel-zig
7
12
 
8
13
  # Keep inline RBS and the compiler's default integer overflow checks enabled.
9
14
  spinel:
@@ -12,3 +17,6 @@ spinel:
12
17
 
13
18
  spinel-test: spinel
14
19
  WARDITE_SPINEL_BIN="$(abspath $(BUILD_DIR)/wardite)" $(RUBY) -Ilib:test -e 'Dir["test/e2e/spinel*_test.rb"].each { |path| require_relative path }'
20
+
21
+ spinel-zig:
22
+ ZIG="$(ZIG)" $(RUBY) scripts/build_spinel_zig.rb "$(MAKE)" "$(BUILD_DIR)" "$(ZIG_GLIBC)" "$(ZIG_MACOS)" "$(ZIG_JOBS)" "$(SPINELFLAGS)" $(ZIG_TARGETS)
data/README.md CHANGED
@@ -90,9 +90,13 @@ the Wasm, links imports, and initializes a fresh instance. `--mir-dump` and
90
90
 
91
91
  The default `--mir-cache-verify checksum` checks the payload size and samples
92
92
  blocks. Use `--mir-cache-verify sha256` or Ruby's `mir_cache_verify: :sha256`
93
- to check the whole payload. Both modes use the same cache file and check MIR
94
- structure. Corruption outside the sampled blocks can go undetected in checksum
95
- mode, including changes that leave the MIR structurally valid.
93
+ to check the whole payload. Both modes use the same cache file. By default,
94
+ each function is restored and structurally checked before its first execution.
95
+ Use `--mir-cache-eager` or Ruby's `mir_cache_eager: true` to check every
96
+ function at load time. If a lazy check fails, Wardite stops and reports the
97
+ cache path. Delete that file and rerun. Corruption outside the sampled blocks
98
+ can go undetected in checksum mode, including changes that leave the MIR
99
+ structurally valid.
96
100
  [MIR2 cache measurements](docs/efflorescence-mir2-cache.md)
97
101
 
98
102
  For WASI commands, `--snapshot DIR` (with `--new-engine --mir-cache DIR`) saves
@@ -165,10 +169,38 @@ CRuby build. Ruby's dynamic export helpers (`instance.add(...)` and
165
169
  The build leaves inline RBS and Spinel's default integer overflow checks enabled.
166
170
  Wasm integer operations bound their intermediate values, so
167
171
  `--int-overflow=promote` is not required.
168
- The pinned Spinel build applies the IO::Buffer patches under `spinel/patches`.
172
+ CI builds Spinel from the upstream commit `58ee6361`, which includes the
173
+ required `IO::Buffer` changes.
169
174
  See the [build instructions and host memory API](docs/efflorescence-spinel-linear-memory.md).
170
175
  Override `SPINEL`, `SPINELFLAGS`, `BUILD_DIR`, or `RUBY` when needed.
171
176
 
177
+ #### Cross-compile from macOS with Zig
178
+
179
+ With Zig 0.17.1, Ruby, and the Xcode Command Line Tools installed, run:
180
+
181
+ ```sh
182
+ make spinel-zig
183
+ ```
184
+
185
+ The first build downloads and builds the same Spinel revision used in CI.
186
+ It builds the Spinel runtime and native StringIO code for each target and
187
+ uses Zig to compile and link the resulting Wardite executables.
188
+
189
+ | Target | Executable |
190
+ | --- | --- |
191
+ | macOS arm64 | `build/spinel-zig/aarch64-macos.13.0/wardite` |
192
+ | Linux x86_64 | `build/spinel-zig/x86_64-linux-gnu.2.28/wardite` |
193
+ | Linux arm64 | `build/spinel-zig/aarch64-linux-gnu.2.28/wardite` |
194
+
195
+ Linux builds dynamically link the target system's glibc. The default glibc
196
+ baseline is 2.28 and the macOS deployment target is 13.0. Set `ZIG_GLIBC`
197
+ or `ZIG_MACOS` to change those values. Use `ZIG` to select the compiler,
198
+ `ZIG_JOBS` to set parallelism, or `ZIG_TARGETS` to build a subset:
199
+
200
+ ```sh
201
+ make spinel-zig ZIG=/opt/homebrew/bin/zig ZIG_TARGETS=x86_64-linux
202
+ ```
203
+
172
204
  ## Contributing
173
205
 
174
206
  Bug reports and pull requests are welcome on GitHub at https://github.com/udzura/wardite.
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
@@ -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)
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Pass Wardite's normal CLI arguments. Run on CRuby outside timing samples.
4
+ require "json"
5
+ require "wardite"
6
+ require "wardite/cli/cli"
7
+
8
+ module FunctionCoverage
9
+ DEFINED = {}
10
+ CALLS = Hash.new(0)
11
+
12
+ def initialize(function, *args)
13
+ @coverage_index = function.index
14
+ DEFINED[@coverage_index] = true
15
+ super
16
+ end
17
+
18
+ def acquire(destination)
19
+ CALLS[@coverage_index] += 1
20
+ super
21
+ end
22
+ end
23
+
24
+ Wardite::Efflorescence::FramePool.prepend(FunctionCoverage)
25
+ at_exit do
26
+ calls = FunctionCoverage::CALLS.values.sort.reverse
27
+ total = calls.sum
28
+ cumulative = 0
29
+ hot = calls.take_while do |count|
30
+ more = cumulative * 10 < total * 9
31
+ cumulative += count
32
+ more
33
+ end
34
+ warn JSON.generate(defined: FunctionCoverage::DEFINED.size, used: calls.size,
35
+ calls: total, functions_for_ninety_percent: hot.size)
36
+ end
37
+ Wardite::Cli::Cli.new(ARGV).run
@@ -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")
@@ -0,0 +1,59 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Usage: ruby benchmark/measure_mir_cache_restore.rb WASM BEFORE_BIN DIRECT_BIN [LAZY_BIN]
4
+ require "digest"
5
+ require "json"
6
+ require "open3"
7
+ require "tmpdir"
8
+
9
+ abort "Usage: ruby #{$PROGRAM_NAME} WASM BEFORE_BIN DIRECT_BIN [LAZY_BIN]" unless (3..4).cover?(ARGV.size)
10
+ wasm, *binaries = ARGV.map { |path| File.expand_path(path) }
11
+ runs = Integer(ENV.fetch("RUNS", "6"))
12
+ warmups = Integer(ENV.fetch("WARMUPS", "1"))
13
+ abort "Invalid run or warmup count" unless runs >= 3 && warmups >= 0
14
+ snapshot = ENV["SNAPSHOT"] == "1"
15
+
16
+ guest = ["--disable-gems", "-e", "puts RUBY_VERSION"]
17
+ expected, status = Open3.capture2("wasmtime", "run", wasm, *guest)
18
+ abort "Wasmtime did not run Ruby 4.0.9" unless status.success? && expected == "4.0.9\n"
19
+
20
+ macos = RUBY_PLATFORM.include?("darwin")
21
+ timer = macos ? ["/usr/bin/time", "-l"] : ["/usr/bin/time", "-f", "%M maximum RSS KiB"]
22
+ rss_pattern = macos ? /^\s*(\d+)\s+maximum resident set size$/ : /^(\d+) maximum RSS KiB$/
23
+ invoke = lambda do |command, *traces|
24
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
25
+ stdout, stderr, status = Open3.capture3({"WARDITE_TRACE" => "1"}, *timer, *command, unsetenv_others: true)
26
+ total = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
27
+ load = stderr[/^load_from_buffer: (\S+)$/, 1]
28
+ rss = stderr[rss_pattern, 1]
29
+ unless status.success? && stdout == expected && load && rss && traces.all? { |trace| stderr.include?(trace) }
30
+ abort "#{command.inspect}\n#{stdout}#{stderr}"
31
+ end
32
+ {load_seconds: Float(load), process_seconds: total, after_load_seconds: total - Float(load),
33
+ peak_rss_bytes: Integer(rss) * (macos ? 1 : 1024)}
34
+ end
35
+
36
+ samples = Dir.mktmpdir("wardite-mir-cache-restore") do |directory|
37
+ commands = %w[before direct lazy].zip(binaries).filter_map do |version, binary|
38
+ next unless binary
39
+ command = [binary, "--new-engine", "--mir-cache", File.join(directory, version)]
40
+ command += ["--snapshot", File.join(directory, "#{version}-snapshot")] if snapshot
41
+ [version, [*command, "--", wasm, *guest]]
42
+ end
43
+ miss = ["MIR2 cache miss:"]
44
+ hit = ["MIR2 cache hit:"]
45
+ if snapshot
46
+ miss << "snapshot saved:"
47
+ hit << "snapshot restored:"
48
+ end
49
+ commands.each { |_, command| invoke.call(command, *miss) }
50
+ (warmups + runs).times.flat_map do |iteration|
51
+ commands.rotate(iteration).filter_map do |version, command|
52
+ sample = invoke.call(command, *hit)
53
+ sample.merge(version: version, run: iteration - warmups + 1) if iteration >= warmups
54
+ end
55
+ end
56
+ end
57
+
58
+ puts JSON.pretty_generate(wasm_sha256: Digest::SHA256.file(wasm).hexdigest, guest_arguments: guest,
59
+ runs: runs, warmups: warmups, snapshot: snapshot, samples: samples)
@@ -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"
@@ -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)