wardite 0.9.0 → 1.0.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.
- checksums.yaml +4 -4
- data/LICENSE +191 -0
- data/Makefile +14 -0
- data/README.md +80 -1
- data/Rakefile +5 -0
- data/benchmark/README.md +500 -0
- data/benchmark/build_call_profile.rb +42 -0
- data/benchmark/call_cost_worker.rb +27 -0
- data/benchmark/compare.rb +93 -0
- data/benchmark/compare_call_types.rb +212 -0
- data/benchmark/compare_dispatch.rb +123 -0
- data/benchmark/compare_engines.rb +119 -0
- data/benchmark/compare_optimizations.rb +139 -0
- data/benchmark/engine_phases.rb +30 -0
- data/benchmark/figures/README.md +35 -0
- data/benchmark/figures/plot_spinel_comparison.py +137 -0
- data/benchmark/figures/spinel_new_vm_candlestick.png +0 -0
- data/benchmark/figures/spinel_new_vm_candlestick.svg +7615 -0
- data/benchmark/figures/spinel_new_vm_summary.csv +9 -0
- data/benchmark/figures/spinel_new_vm_summary.json +82 -0
- data/benchmark/float_m5.wat +42 -0
- data/benchmark/i32_call_arities.wat +89 -0
- data/benchmark/i32_calls.wat +174 -0
- data/benchmark/i32_memory.wat +58 -0
- data/benchmark/i32_mix.wat +80 -0
- data/benchmark/i64_m4.wat +55 -0
- data/benchmark/investigate_calls.rb +231 -0
- data/benchmark/investigate_generated_guards.rb +218 -0
- data/benchmark/m3_call_worker.rb +38 -0
- data/benchmark/measure_m1.rb +51 -0
- data/benchmark/measure_m2.rb +55 -0
- data/benchmark/measure_m3_calls.rb +89 -0
- data/benchmark/measure_m4.rb +134 -0
- data/benchmark/measure_m5_boundary.rb +41 -0
- data/benchmark/measure_wasi_write.rb +75 -0
- data/benchmark/optimization_worker.rb +23 -0
- data/benchmark/results/call_arities_exploratory_2026-11-04.json +4320 -0
- data/benchmark/results/call_arities_spinel_2026-11-04.json +1200 -0
- data/benchmark/results/call_cost_spinel_2026-11-04.json +2392 -0
- data/benchmark/results/call_protocol_exploratory_2026-11-04.json +3947 -0
- data/benchmark/results/call_protocol_profile_2026-11-04.json +383 -0
- data/benchmark/results/call_protocol_ruby_2026-11-04.json +1213 -0
- data/benchmark/results/call_protocol_spinel_2026-11-04.json +913 -0
- data/benchmark/results/call_types_ruby_2026-11-04.json +1212 -0
- data/benchmark/results/call_types_spinel_2026-11-04.json +923 -0
- data/benchmark/results/efflorescence-m1-cruby.json +799 -0
- data/benchmark/results/efflorescence-m1-spinel.json +799 -0
- data/benchmark/results/efflorescence-m2-bulk-loop.json +820 -0
- data/benchmark/results/efflorescence-m2-i32-cruby.json +799 -0
- data/benchmark/results/efflorescence-m2-i32-spinel.json +799 -0
- data/benchmark/results/efflorescence-m2-memory.json +408 -0
- data/benchmark/results/generated_guards_exploratory_2026-11-04.json +1225 -0
- data/benchmark/results/generated_guards_profile_2026-11-04.json +592 -0
- data/benchmark/results/generated_guards_spinel_2026-11-04.json +1650 -0
- data/benchmark/results/generated_guards_validation_2026-11-04.json +256 -0
- data/benchmark/results/inlining_engines_2026-11-04.json +241 -0
- data/benchmark/results/inlining_ruby_2026-11-04.json +1213 -0
- data/benchmark/results/inlining_spinel_2026-11-04.json +893 -0
- data/benchmark/results/operand_decode_exploratory_2026-11-04.json +1319 -0
- data/benchmark/results/operand_decode_ruby_2026-11-04.json +1213 -0
- data/benchmark/results/operand_decode_spinel_2026-11-04.json +924 -0
- data/benchmark/results/selective_reset_spinel_2026-11-04.json +454 -0
- data/benchmark/results/selective_reset_spinel_2026-11-04_exploratory.json +2679 -0
- data/benchmark/results/spinel_fetch_root_patch_2026-11-04.json +4523 -0
- data/benchmark/results/while_final_compiler_comparison_2026-11-04.json +324 -0
- data/benchmark/results/while_patched_external_2026-11-04.json +220 -0
- data/benchmark/results/while_user_unpatched_2026-11-04.json +230 -0
- data/benchmark/summarize_call_profile.py +54 -0
- data/benchmark/validate_m1_eh.rb +34 -0
- data/benchmark/validate_m2.rb +119 -0
- data/benchmark/validate_m3.rb +44 -0
- data/benchmark/validate_m4.rb +95 -0
- data/benchmark/validate_m5.rb +108 -0
- data/docs/adr/0001-efflorescence-m1-control-and-eh.md +319 -0
- data/docs/adr/0002-efflorescence-m2-memory-and-globals.md +185 -0
- data/docs/adr/0003-efflorescence-m3-host-and-indirect-calls.md +228 -0
- data/docs/adr/0004-efflorescence-m4-i64.md +202 -0
- data/docs/adr/0005-efflorescence-m5-floating-point.md +127 -0
- data/docs/adr/0006-efflorescence-m6-coverage-parity.md +101 -0
- data/docs/efflorescence-call-arities.md +115 -0
- data/docs/efflorescence-call-investigation.md +155 -0
- data/docs/efflorescence-call-transfer.md +128 -0
- data/docs/efflorescence-call-types.md +102 -0
- data/docs/efflorescence-coverage-ja.md +351 -0
- data/docs/efflorescence-generated-c-guards.md +405 -0
- data/docs/efflorescence-inlining.md +165 -0
- data/docs/efflorescence-ja.md +155 -0
- data/docs/efflorescence-m1.md +160 -0
- data/docs/efflorescence-m2.md +233 -0
- data/docs/efflorescence-m3.md +131 -0
- data/docs/efflorescence-m4.md +88 -0
- data/docs/efflorescence-m5.md +82 -0
- data/docs/efflorescence-m6.md +95 -0
- data/docs/efflorescence-operand-decoding.md +105 -0
- data/docs/efflorescence-phase2-ja.md +225 -0
- data/docs/efflorescence-phase2.md +240 -0
- data/docs/efflorescence-register-initialization.md +75 -0
- data/docs/efflorescence.md +144 -0
- data/docs/spinel-string-aset-inplace-proposal.md +200 -0
- data/lib/wardite/alu_f32.generated.rb +1 -0
- data/lib/wardite/alu_f64.generated.rb +1 -0
- data/lib/wardite/alu_i32.generated.rb +14 -9
- data/lib/wardite/alu_i64.generated.rb +18 -20
- data/lib/wardite/cli/cli.rb +61 -28
- data/lib/wardite/const.rb +1 -0
- data/lib/wardite/efflorescence/float_arithmetic.rb +216 -0
- data/lib/wardite/efflorescence/i64_arithmetic.rb +257 -0
- data/lib/wardite/efflorescence/inspection.rb +165 -0
- data/lib/wardite/efflorescence/ir.rb +1151 -0
- data/lib/wardite/efflorescence/optimizer.rb +580 -0
- data/lib/wardite/efflorescence/register_validation.rb +290 -0
- data/lib/wardite/efflorescence/store_access.rb +271 -0
- data/lib/wardite/efflorescence/translator.rb +859 -0
- data/lib/wardite/efflorescence/vm.rb +1006 -0
- data/lib/wardite/efflorescence/wasi.rb +108 -0
- data/lib/wardite/efflorescence.rb +11 -0
- data/lib/wardite/errors.rb +20 -0
- data/lib/wardite/float_bits.rb +46 -0
- data/lib/wardite/instruction.rb +35 -4
- data/lib/wardite/leb128.rb +33 -12
- data/lib/wardite/load.rb +203 -138
- data/lib/wardite/value.rb +169 -175
- data/lib/wardite/version.rb +1 -1
- data/lib/wardite/wasi/consts.rb +1 -0
- data/lib/wardite/wasm_module.rb +6 -3
- data/lib/wardite.rb +184 -70
- data/rbs_collection.lock.yaml +36 -96
- data/scripts/gen_alu.rb +66 -10
- data/sig/generated/wardite/cli/cli.rbs +8 -6
- data/sig/generated/wardite/const.rbs +2 -0
- data/sig/generated/wardite/efflorescence/float_arithmetic.rbs +65 -0
- data/sig/generated/wardite/efflorescence/i64_arithmetic.rbs +99 -0
- data/sig/generated/wardite/efflorescence/inspection.rbs +64 -0
- data/sig/generated/wardite/efflorescence/ir.rbs +881 -0
- data/sig/generated/wardite/efflorescence/optimizer.rbs +189 -0
- data/sig/generated/wardite/efflorescence/register_validation.rbs +76 -0
- data/sig/generated/wardite/efflorescence/store_access.rbs +134 -0
- data/sig/generated/wardite/efflorescence/translator.rbs +214 -0
- data/sig/generated/wardite/efflorescence/vm.rbs +179 -0
- data/sig/generated/wardite/efflorescence/wasi.rbs +47 -0
- data/sig/generated/wardite/errors.rbs +12 -0
- data/sig/generated/wardite/float_bits.rbs +30 -0
- data/sig/generated/wardite/instruction.rbs +22 -1
- data/sig/generated/wardite/leb128.rbs +3 -1
- data/sig/generated/wardite/load.rbs +29 -4
- data/sig/generated/wardite/value.rbs +70 -11
- data/sig/generated/wardite/wasi/consts.rbs +2 -0
- data/sig/generated/wardite.rbs +49 -12
- data/sig/vernier.rbs +2 -2
- data/spinel/README.md +30 -0
- data/spinel/bin/wardite.rb +6 -0
- data/spinel/spin.toml +7 -0
- metadata +126 -3
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
# Efflorescence VM (Phase 1)
|
|
2
|
+
|
|
3
|
+
[日本語](efflorescence-ja.md)
|
|
4
|
+
|
|
5
|
+
Current coverage includes [M1 i32, structured control and new EH](efflorescence-m1.md),
|
|
6
|
+
[M2 memory and globals](efflorescence-m2.md), [M3 host and indirect calls](efflorescence-m3.md),
|
|
7
|
+
[M4 i64](efflorescence-m4.md), and [M5 floating point](efflorescence-m5.md).
|
|
8
|
+
[M6](efflorescence-m6.md) verifies the M0 coverage baseline and the additional EH opcodes.
|
|
9
|
+
The Phase 1 limitations below are historical.
|
|
10
|
+
|
|
11
|
+
This document records Phase 1 (`67fbfae`). Current Efflorescence enables the
|
|
12
|
+
[Phase 2 optimizations](efflorescence-phase2.md) by default; `--mir-disable all`
|
|
13
|
+
selects unoptimized MIR lowered to the same flat bytecode executor. Wardite's default is still the stack VM.
|
|
14
|
+
|
|
15
|
+
Efflorescence is Wardite's opt-in, pure Ruby register interpreter. The default
|
|
16
|
+
remains `Wardite::Runtime`, the stack interpreter. Both engines share the binary
|
|
17
|
+
loader, decoded Wasm instructions, store and exports; execution is independent.
|
|
18
|
+
|
|
19
|
+
```sh
|
|
20
|
+
wasm-tools parse benchmark/i32_mix.wat -o build/i32_mix.wasm
|
|
21
|
+
ruby -Ilib exe/wardite --new-engine --no-wasi --invoke inline_mix build/i32_mix.wasm 100000 123
|
|
22
|
+
ruby -Ilib exe/wardite --new-engine --no-wasi --invoke call_mix build/i32_mix.wasm 100000 123
|
|
23
|
+
# Both: return value: I32(-424175775)
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
The equivalent Ruby API is:
|
|
27
|
+
|
|
28
|
+
```ruby
|
|
29
|
+
require "wardite"
|
|
30
|
+
instance = Wardite.new(path: "build/i32_mix.wasm", enable_wasi: false, engine: :efflorescence)
|
|
31
|
+
instance.runtime.call("call_mix", [100000, 123]) # Wardite::I32, same as Runtime
|
|
32
|
+
instance.runtime.call_unboxed("call_mix", [100000, 123]) # 3870791521 (Integer)
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Spinel uses the same sources (`make spinel`). Invoke exported functions through
|
|
36
|
+
`runtime.call` or the CLI: Spinel currently does not dispatch undefined methods
|
|
37
|
+
through Ruby's `method_missing` (including the existing VM's convenience API).
|
|
38
|
+
No Spinel-specific runtime API or global integer-overflow option is needed.
|
|
39
|
+
|
|
40
|
+
## MIR and execution
|
|
41
|
+
|
|
42
|
+
All new implementation classes live under `Wardite::Efflorescence`:
|
|
43
|
+
|
|
44
|
+
| Class | Responsibility |
|
|
45
|
+
| --- | --- |
|
|
46
|
+
| `IR` | Module's translated functions, indexed by Wasm function index |
|
|
47
|
+
| `Function` | Index, parameter/result types, local count, register count, initial register values, instructions |
|
|
48
|
+
| `Instruction` / `Opcode` | Integer operands and integer opcode constants |
|
|
49
|
+
| `Translator` / `Translator::Control` | Abstract operand stack, structured labels, snapshots, result joins and PC fixups |
|
|
50
|
+
| `Frame` | Function, Integer register array, return destination and saved PC |
|
|
51
|
+
| `VM` | Export checks, Ruby boundary conversion, independent dispatch and explicit call frames |
|
|
52
|
+
|
|
53
|
+
`Instruction` wraps an `Array<Integer>`. The wrapper gives Spinel a typed operand
|
|
54
|
+
accessor even when it represents the outer instruction table as a generic array.
|
|
55
|
+
Instructions are allocated during translation, never during dispatch.
|
|
56
|
+
|
|
57
|
+
| MIR form | Meaning |
|
|
58
|
+
| --- | --- |
|
|
59
|
+
| `[COPY, dst, src]` | Copy register |
|
|
60
|
+
| `[I32_ADD/SUB/MUL/XOR/SHL/SHR_U, dst, lhs, rhs]` | Wasm binary operation |
|
|
61
|
+
| `[I32_EQZ, dst, src]` | Zero test |
|
|
62
|
+
| `[BR, pc]`, `[BR_IF, condition, pc]` | Absolute MIR target |
|
|
63
|
+
| `[CALL, dst, function_index, *argument_registers]` | Internal call (`dst = -1` for void) |
|
|
64
|
+
| `[RETURN, src]` | Return (`src = -1` for void) |
|
|
65
|
+
| `[TRAP]` | Wasm `unreachable` |
|
|
66
|
+
|
|
67
|
+
Locals occupy the first registers. `local.get` pushes a source in the translator,
|
|
68
|
+
without emitting a runtime instruction. Before overwriting a local that remains
|
|
69
|
+
on the abstract stack, the translator copies its old value to a temporary and
|
|
70
|
+
rewrites those sources. At block/loop entry, live local sources are snapshotted
|
|
71
|
+
before the branch target, preserving stack prefixes across edges and backedges.
|
|
72
|
+
`local.tee` uses the same mechanism. Constants are deduplicated into immutable
|
|
73
|
+
initial register slots; `i32.const` emits no runtime instruction.
|
|
74
|
+
|
|
75
|
+
Each arithmetic result has a temporary slot. Result-bearing blocks/functions
|
|
76
|
+
have join slots; incoming branches and normal completion copy into those slots.
|
|
77
|
+
Loop branches target the header and carry no arguments; block branches target
|
|
78
|
+
the end and carry their result. Unconditional transfers make the rest of that
|
|
79
|
+
control region unreachable. There are no runtime Wasm labels or operand stack.
|
|
80
|
+
|
|
81
|
+
Registers always contain unsigned `0..0xffffffff` Ruby Integers. Add/subtract
|
|
82
|
+
wrap, shift counts use their low five bits, and multiply uses 16-bit limbs to
|
|
83
|
+
avoid overflowing Spinel's signed native word before masking the result. Internal
|
|
84
|
+
calls copy Integers between independent frames. Only `VM#call` boxes the final
|
|
85
|
+
Ruby-facing result; `call_unboxed` does not. Calls use an explicit frame array,
|
|
86
|
+
so guest recursion does not consume Ruby's method call stack.
|
|
87
|
+
|
|
88
|
+
No optimization pass is required to execute this MIR. Future passes can operate
|
|
89
|
+
on each Function between translation and execution. Conservative COPYs and
|
|
90
|
+
temporary registers are intentionally retained for Phase 1.
|
|
91
|
+
|
|
92
|
+
## Scope and validation
|
|
93
|
+
|
|
94
|
+
Supported: i32 parameters/results/locals/constants, get/set/tee, add/sub/mul/xor,
|
|
95
|
+
shl/shr_u/eqz, block/loop/br/br_if/end, call/return, nop/drop/unreachable and
|
|
96
|
+
function exports. Blocks and loops can have zero or one i32 result; loop
|
|
97
|
+
parameters and type-index block signatures are unsupported.
|
|
98
|
+
|
|
99
|
+
Imports/host functions, WASI calls, memory/global/table instructions, if/else,
|
|
100
|
+
other numeric operations, multi-value signatures and advanced Wasm proposals
|
|
101
|
+
raise `UnsupportedFeature`. Every defined function is translated eagerly, so an
|
|
102
|
+
unsupported instruction is rejected even in dead code or an unexported function.
|
|
103
|
+
There is no fallback to `Wardite::Runtime`. The shared loader's existing binary
|
|
104
|
+
decoding and validation limitations still apply.
|
|
105
|
+
|
|
106
|
+
```sh
|
|
107
|
+
bundle exec rake test
|
|
108
|
+
bundle exec rake check
|
|
109
|
+
make spinel-test RUBY="bundle exec ruby"
|
|
110
|
+
ruby benchmark/compare_engines.rb 100000 123
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
Tests compile the **entire unchanged** `benchmark/i32_mix.wat` using the existing
|
|
114
|
+
`wasm-tools parse` flow. No prebuilt fixture or reduced workload is substituted.
|
|
115
|
+
All eight specified input pairs run against both exports, both engines and an
|
|
116
|
+
independent modulo-based reference on CRuby and Spinel. Additional tests cover
|
|
117
|
+
snapshots, result branches, loop prefixes, recursion, void calls, normalization,
|
|
118
|
+
shift counts, unsigned products, unsupported features and CLI selection. A
|
|
119
|
+
TracePoint regression checks that 1,000 internal calls allocate just one I32 at
|
|
120
|
+
the Ruby return boundary and never execute a `Wardite::Runtime` method.
|
|
121
|
+
|
|
122
|
+
Verified on 2026-11-03 with CRuby 4.0.9 and Spinel `2026.10.25+1967`
|
|
123
|
+
(`6e7fc1355`, default integer overflow checks): **75 tests, 1,106 assertions,
|
|
124
|
+
zero failures/errors/omissions**, with `WARDITE_SPINEL_BIN` enabled for the full
|
|
125
|
+
suite. `bundle exec rake check` also passed. Both exports on both engines and
|
|
126
|
+
both runtimes produced these unsigned results:
|
|
127
|
+
|
|
128
|
+
| Rounds | Seed | Checksum |
|
|
129
|
+
| ---: | ---: | ---: |
|
|
130
|
+
| 0 | 0 | 0 |
|
|
131
|
+
| 0 | 123 | 123 |
|
|
132
|
+
| 1 | 0 | 186080479 |
|
|
133
|
+
| 1 | 123 | 434058398 |
|
|
134
|
+
| 10 | 123 | 483678737 |
|
|
135
|
+
| 1000 | 123 | 1949289519 |
|
|
136
|
+
| 1000 | 4294967295 | 1895198137 |
|
|
137
|
+
| 100000 | 123 | 3870791521 |
|
|
138
|
+
|
|
139
|
+
[Recorded performance comparison](../benchmark/README.md#phase-1-sample-2026-11-03).
|
|
140
|
+
|
|
141
|
+
Next steps: reduce COPYs and temporary count in independent passes, specialize
|
|
142
|
+
immediates, improve instruction-table representation for Spinel, reuse frames,
|
|
143
|
+
and extend supported Wasm operations/control constructs. Performance is not a
|
|
144
|
+
Phase 1 acceptance criterion.
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
# Spinel: 同じ長さの `s[from, n] = v` をその場で書き換える提案
|
|
2
|
+
|
|
3
|
+
## 概要
|
|
4
|
+
|
|
5
|
+
Spinel では、mutable な String(`sp_String` handle)への `s[from, n] = v` が、
|
|
6
|
+
転送長に関係なく、1 回ごとに文字列全体を約 4 回コピーする。
|
|
7
|
+
binary の handle に同じ byte 長の値を書く場合に限り、`memmove` でその場で書き換える
|
|
8
|
+
fast path を runtime と codegen に足すことを提案する。
|
|
9
|
+
それ以外の場合は、今の splice の経路にそのまま任せる。
|
|
10
|
+
|
|
11
|
+
- 対象 revision:`matz/spinel` master `93c70470d`。行番号はこの revision のもの。
|
|
12
|
+
測定は `6f1a2c259`(2026-11-04)で行った。該当箇所の実装はこの 2 つの revision で変わっていない。
|
|
13
|
+
- きっかけ:Wardite(Wasm runtime)の `memory.copy` / `memory.fill` / `memory.init`。
|
|
14
|
+
Wardite 側は getbyte/setbyte ループに置き換えて回避した(udzura/wardite#24)。
|
|
15
|
+
Spinel 側を直せば、範囲代入を使う Ruby コード全般が速くなる。
|
|
16
|
+
|
|
17
|
+
## 現状
|
|
18
|
+
|
|
19
|
+
### 生成 C
|
|
20
|
+
|
|
21
|
+
local 変数が handle を持つ場合(`data = memory.data; data[dst, n] = bytes`)、
|
|
22
|
+
文の位置では次の C が出る(Wardite の `StoreAccess#copy`)。
|
|
23
|
+
|
|
24
|
+
```c
|
|
25
|
+
{ sp_String *_t6 = SP_STR_HDL(lv_data);
|
|
26
|
+
if (sp_String_is_frozen(_t6)) sp_raise_frozen_str(_t6->data);
|
|
27
|
+
const char *lv__sb6 = sp_str_concat(sp_String_cstr(_t6), ""); /* (1) 全体を shadow に複製 */
|
|
28
|
+
SP_GC_ROOT(lv__sb6);
|
|
29
|
+
{ sp_int _t7 = dst; sp_int _t8 = n; const char *_v7 = val;
|
|
30
|
+
sp_str_check_mutable(lv__sb6);
|
|
31
|
+
lv__sb6 = sp_str_splice_at(lv__sb6, _t7, _t8, _v7, 0); } /* (2) head/tail + 2 回の連結 */
|
|
32
|
+
sp_String_set_bin(_t6, lv__sb6); /* (3) 全体を handle に書き戻す */
|
|
33
|
+
}
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
- (1) は `emit_sb_shim_swap`(`src/codegen_stmt.c:23899`)が出す。
|
|
37
|
+
呼び出し元は `str_mutate_shared_arms`(`src/codegen_stmt.c:24962`)で、
|
|
38
|
+
local・ivar・reader の receiver を shadow `lv__sb<N>` に読み替える。
|
|
39
|
+
そのうえで文の emitter を走らせ直し、最後に handle へ書き戻す。
|
|
40
|
+
式の位置でも同じ形のものが `src/codegen_call_recv.c` の `sb_iv_expr_shim`(:751)、
|
|
41
|
+
`sb_reader_expr_shim`(:789)、`sb_route_expr_shim`(:822)と、local 用の分岐(:5400 付近)にある。
|
|
42
|
+
- (2) の arm は `str_mutate_reassign_arms` の `s[start, len] = v` の分岐(`src/codegen_stmt.c:24405`)。
|
|
43
|
+
shadow は「assignable」として扱われるので、`lv__sb = sp_str_splice_at(lv__sb, ...)` になる。
|
|
44
|
+
- `sp_str_splice_at`(`lib/sp_cold.c:1416`)は `sp_str_sub_range` で head と tail を切り出し、
|
|
45
|
+
`sp_str_concat` を 2 回呼んで新しい文字列を作る。
|
|
46
|
+
- `sp_String_set_bin`(`lib/sp_string.h:185`)は `len = 0` にしたあと、全体を append し直す。
|
|
47
|
+
|
|
48
|
+
文字列の byte 長を N とすると、1 回あたり約 4N の memcpy と 4〜5 回の割当(N 規模)が起きる。
|
|
49
|
+
binary String の長さは header から O(1) で取れるので、長さの計算はコストにならない。
|
|
50
|
+
|
|
51
|
+
### 測定(`6f1a2c259`、`-O2`、Apple clang 21、arm64 macOS)
|
|
52
|
+
|
|
53
|
+
128 byte の前方重複 copy(`data[2112, 128] = data.byteslice(2048, 128).dup`)を
|
|
54
|
+
20,000 回行ったときの 1 回あたりの時間(µs)。
|
|
55
|
+
|
|
56
|
+
| 文字列の長さ | `s[i, n] = v` | `bytesplice` | setbyte ループ | CRuby 4.0.9 の `s[i, n] = v` |
|
|
57
|
+
|---|---:|---:|---:|---:|
|
|
58
|
+
| 64 KiB | 80.8 | 4.4 | 0.28 | 0.23 |
|
|
59
|
+
| 128 KiB | 158.7 | — | 0.28 | 0.16 |
|
|
60
|
+
| 1 MiB | 1,275.0 | 48.1 | 0.29 | 0.14 |
|
|
61
|
+
|
|
62
|
+
時間は文字列の長さに比例する。CRuby はその場で書き換えるので、長さに関係なく一定である。
|
|
63
|
+
|
|
64
|
+
### 前例:`sp_String_setbyte`
|
|
65
|
+
|
|
66
|
+
`String#setbyte` には、すでに同じ問題の修正がある(`lib/spinel_rt.h:45`、テスト `test/setbyte_handle_in_place.rb`)。
|
|
67
|
+
handle が自分の payload を持つ(marker `0xfd`)ときは `d[j] = v` だけを行い、hash と lcache を無効にする。
|
|
68
|
+
alias はどれも同じ handle を見るので、その書き込みが見える。
|
|
69
|
+
この提案は、その考え方を範囲代入に広げるものである。
|
|
70
|
+
|
|
71
|
+
## 提案
|
|
72
|
+
|
|
73
|
+
### 1. runtime:`sp_String_aset_range`
|
|
74
|
+
|
|
75
|
+
`lib/sp_string.h` の `sp_String_set_bin_enc` の近くに置く。
|
|
76
|
+
下のコードは設計を示すためのもので、まだコンパイルしていない。実装するときにそのまま使えるとは限らない。
|
|
77
|
+
`SP_ONE_STRING` は生成コードで常に定義されるが、`sp_String_setbyte` に合わせて、置く場所の条件はそろえる。
|
|
78
|
+
|
|
79
|
+
```c
|
|
80
|
+
/* s[from, n] = val on a handle. A same-length write of binary bytes into a
|
|
81
|
+
binary payload the handle owns is a memmove in place, so every alias sees it
|
|
82
|
+
and nothing the size of the String is copied (as sp_String_setbyte does for
|
|
83
|
+
one byte). Anything else -- a resize, a text receiver or value, an index out
|
|
84
|
+
of range, a payload the handle does not own -- takes the splice, which also
|
|
85
|
+
raises what CRuby raises. */
|
|
86
|
+
static inline void sp_String_aset_range(sp_String *s, sp_int from, sp_int n, const char *val) {
|
|
87
|
+
if (SP_UNLIKELY(!s)) sp_nil_recv("[]=");
|
|
88
|
+
if (sp_String_is_frozen(s)) { sp_raise_frozen_str(s->data); return; }
|
|
89
|
+
char *d = s->data;
|
|
90
|
+
sp_int len = s->len, at = from < 0 ? from + len : from;
|
|
91
|
+
if (SP_LIKELY(val && s->binary && sp_str_is_binary(val) &&
|
|
92
|
+
((const unsigned char *)d)[-1] == 0xfd &&
|
|
93
|
+
n >= 0 && at >= 0 && n <= len - at &&
|
|
94
|
+
(sp_int)sp_str_byte_len(val) == n)) {
|
|
95
|
+
memmove(d + at, val, (size_t)n); /* val may be a view of this payload */
|
|
96
|
+
sp_fd_publish(s); /* hash, 7-bit flag, lcache; len is unchanged */
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
sp_String_set_bin(s, sp_str_splice_at(sp_String_cstr(s), from, n, val, 0));
|
|
100
|
+
}
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
fast path に入る条件と、その理由:
|
|
104
|
+
|
|
105
|
+
| 条件 | 理由 |
|
|
106
|
+
|---|---|
|
|
107
|
+
| `s->binary && sp_str_is_binary(val)` | CRuby の結果も binary のままで、encoding が変わらない。ASCII だけの binary に UTF-8 を書くと UTF-8 になり、binary でない値を混ぜると `Encoding::CompatibilityError` になることがある。binary 同士なら文字 index と byte index が一致する。 |
|
|
108
|
+
| marker `0xfd` | handle が payload を持っている。literal や共有 payload を書き換えない(`sp_String_setbyte` と同じ判定)。 |
|
|
109
|
+
| `0 <= at`、`n >= 0`、`n <= len - at` | 例外や切り詰めが起きない範囲に限る。範囲外は fallback に任せ、IndexError と RangeError の文言を今と同じにする。 |
|
|
110
|
+
| `byte_len(val) == n` | 長さが変わらないので、`sp_fd_grow` も `len` の更新も要らない。 |
|
|
111
|
+
|
|
112
|
+
- `memmove` を使うのは、`val` が同じ payload の view でもよいようにするため。
|
|
113
|
+
たとえば `s[a, n] = s[b, n]` で、`s[b, n]` が copy を返さない経路から来る場合がある。
|
|
114
|
+
- fast path は割当をしないので、GC root を新たに足す必要はない。
|
|
115
|
+
- fallback は、今の `sp_String_set_bin(_t, sp_str_splice_at(...))`(`src/codegen_stmt.c:24400`)と同じ動きにする。
|
|
116
|
+
|
|
117
|
+
### 2. codegen:handle に対する 3 引数の `[]=` を直接の形にする
|
|
118
|
+
|
|
119
|
+
`[]=`、`argc == 3`、`argv[0]` が `TY_INT` か boxed(今の分岐の条件と同じ)、
|
|
120
|
+
receiver が `TY_STRING` の handle のときは、shadow の shim を使わずに次の形を出す。
|
|
121
|
+
|
|
122
|
+
```c
|
|
123
|
+
{ sp_String *_tH = SP_STR_HDL(<handle の参照>); SP_GC_ROOT(_tH); if (!_tH) sp_nil_recv("[]=");
|
|
124
|
+
sp_int _ts = <start>; sp_int _tl = <len>; /* 今と同じく、値より先に評価する */
|
|
125
|
+
<emit_str_splice_value(c, recv, argv[2], 0, _ts, b) の前処理>
|
|
126
|
+
sp_String_aset_range(_tH, _ts, _tl, <val>); }
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
直す場所:
|
|
130
|
+
|
|
131
|
+
1. `src/codegen_stmt.c:24390` の element read 用の分岐(`!assignable && sp_streq(name, "[]=") && argc == 3`)。
|
|
132
|
+
最後の `sp_String_set_bin(_t%d, sp_str_splice_at(sp_String_cstr(_t%d), ...))` を
|
|
133
|
+
`sp_String_aset_range(_t%d, _t%d, _t%d, %s)` に置き換える。これがいちばん小さい変更で、形の見本になる。
|
|
134
|
+
2. `str_mutate_shared_arms`(`src/codegen_stmt.c:24962`)の入口。
|
|
135
|
+
上の条件に合うときは、shim(`emit_sb_shim_swap`)を組む前に 1 と同じ直接の形を出して `1` を返す。
|
|
136
|
+
handle の参照には、各分岐が shim に渡しているもの(local の `srefL`、reader の `srefR`、ivar の `srefI`)を使う。
|
|
137
|
+
Wardite の `data[dst, n] = bytes`(local)は、この経路を通っている。
|
|
138
|
+
3. 式の位置(`src/codegen_call_recv.c` の :5400 付近の local 分岐と、`sb_*_expr_shim`)。
|
|
139
|
+
`[]=` の値は `val` なので、`({ ...; sp_String_aset_range(...); <val>; })` の形にする。
|
|
140
|
+
文の位置だけを先に直してもよい(Wardite の例では、メソッドの最後の式が値の位置で出ていた)。
|
|
141
|
+
|
|
142
|
+
まず 1 と 2 だけを入れ、`-c` の出力に `lv__sb<N> = sp_str_concat(sp_String_cstr(` が出なくなることを確かめる。
|
|
143
|
+
3 は、生成 C を見て残っている経路があれば足す。
|
|
144
|
+
|
|
145
|
+
### 3. 任意:長さが変わる場合と `bytesplice`
|
|
146
|
+
|
|
147
|
+
- 長さが変わる splice も、`sp_fd_grow` と tail の `memmove` で O(len - at) にできる。
|
|
148
|
+
ただし encoding の扱いが増えるので、別の PR にする。
|
|
149
|
+
- Spinel の `bytesplice` も O(N) だった(1 MiB で 48µs)。
|
|
150
|
+
同じ helper の byte 版(char boundary の検査は既存のものを使う)で速くなるが、この提案の範囲には含めない。
|
|
151
|
+
|
|
152
|
+
## テスト
|
|
153
|
+
|
|
154
|
+
`test/` に、`setbyte_handle_in_place.rb` と同じ形のテストを足す。
|
|
155
|
+
名前は `string_aset_range_handle_in_place.rb` などとし、`.expected` は CRuby 4.0 で
|
|
156
|
+
`--enable-frozen-string-literal` を付けて作る。
|
|
157
|
+
header には `# spinel: share` と `# spinel: gc-stress` を付ける(`CONTRIBUTING.md` の規約による)。
|
|
158
|
+
|
|
159
|
+
確かめること:
|
|
160
|
+
|
|
161
|
+
- alias と reader 経由で書き込みが見えること。
|
|
162
|
+
- local の alias(`a = s; s[2, 3] = "xyz".b; p a`)
|
|
163
|
+
- `attr_reader` の receiver(`h.buf[0, 2] = ...`)
|
|
164
|
+
- ivar の receiver
|
|
165
|
+
- 結果の bytes と encoding が CRuby と一致すること。
|
|
166
|
+
- binary に binary を書く場合(fast path)
|
|
167
|
+
- ASCII だけの binary に UTF-8 を書く場合(fallback で UTF-8 になる)
|
|
168
|
+
- UTF-8 の receiver に binary の ASCII を書く場合
|
|
169
|
+
- 重なる範囲を両方向にコピーしても正しいこと(`s[2, 4] = s.byteslice(0, 4)` と `s[0, 4] = s.byteslice(2, 4)`)。
|
|
170
|
+
- 境界の扱いが CRuby と同じこと。
|
|
171
|
+
- 負の start、`at == len` で n が 0、`at > len` の IndexError、負の n の IndexError
|
|
172
|
+
- `n > len - at` のときの切り詰め(fallback の経路)
|
|
173
|
+
- frozen な receiver の FrozenError
|
|
174
|
+
- NUL を含む binary の長さが正しいこと(`"\0".b * 16`)。
|
|
175
|
+
- 書いたあとに `hash` と `==` が新しい内容を反映すること(`sp_fd_publish` の hash の無効化)。
|
|
176
|
+
- 7-bit と分かっている text に、同じ長さの高位 byte を書いたあとも、`length` が正しいこと
|
|
177
|
+
(この場合は fallback を通るが、退行しないことを確かめる)。
|
|
178
|
+
|
|
179
|
+
性能:
|
|
180
|
+
|
|
181
|
+
- 上の表のマイクロベンチ(`s[2112, 128] = s.byteslice(2048, 128).dup` を 64 KiB と 1 MiB で回す)で、
|
|
182
|
+
1 回あたりの時間が文字列の長さに依存しなくなること。
|
|
183
|
+
- `CONTRIBUTING.md` の review 条件に従い、optcarrot の checksum(59662)と、
|
|
184
|
+
生成 C が変わる場合の callgrind の数値、scale-test の比が 0.05 を超えて上がらないことを確かめる。
|
|
185
|
+
- `make gate` を通す。
|
|
186
|
+
|
|
187
|
+
## 完了の条件
|
|
188
|
+
|
|
189
|
+
- 次のコードを `-O2` でコンパイルした C で、`sp_str_splice_at` と shadow の `sp_str_concat(sp_String_cstr(...), "")` が呼ばれないこと。
|
|
190
|
+
|
|
191
|
+
```ruby
|
|
192
|
+
data = "\0".b * 65536
|
|
193
|
+
data[2112, 128] = data.byteslice(2048, 128).dup
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
- 上のマイクロベンチで、64 KiB と 1 MiB の 1 回あたりの時間がどちらも 1µs 未満であること。
|
|
197
|
+
- 新しいテストの `.expected` が CRuby と一致し、`make gate` が通ること。
|
|
198
|
+
- Wardite の udzura/wardite#24 を元の範囲代入に戻しても、`benchmark/measure_m2.rb` の
|
|
199
|
+
Spinel の copy_fill が 2ms 未満になること(置き換え前は 168ms、setbyte 版は 1.08ms)。
|
|
200
|
+
これは任意の確認で、Wardite 側をどうするかは別に判断する。
|
|
@@ -295,7 +295,7 @@ module Wardite
|
|
|
295
295
|
finish = target.memsize
|
|
296
296
|
count = 0
|
|
297
297
|
while count < finish
|
|
298
|
-
if
|
|
298
|
+
if target.value[count].zero?
|
|
299
299
|
count += 1
|
|
300
300
|
else
|
|
301
301
|
break
|
|
@@ -312,7 +312,7 @@ module Wardite
|
|
|
312
312
|
digits = target.memsize
|
|
313
313
|
count = 0
|
|
314
314
|
digits.times do |i|
|
|
315
|
-
if
|
|
315
|
+
if target.value[i].nonzero?
|
|
316
316
|
count += 1
|
|
317
317
|
end
|
|
318
318
|
end
|
|
@@ -340,7 +340,7 @@ module Wardite
|
|
|
340
340
|
if !right.is_a?(I32) || !left.is_a?(I32)
|
|
341
341
|
raise EvalError, "maybe empty or invalid stack"
|
|
342
342
|
end
|
|
343
|
-
runtime.stack.push(
|
|
343
|
+
runtime.stack.push(left.multiply(right))
|
|
344
344
|
|
|
345
345
|
|
|
346
346
|
when :i32_div_s
|
|
@@ -348,12 +348,17 @@ module Wardite
|
|
|
348
348
|
if !right.is_a?(I32) || !left.is_a?(I32)
|
|
349
349
|
raise EvalError, "maybe empty or invalid stack"
|
|
350
350
|
end
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
351
|
+
dividend = left.value_s
|
|
352
|
+
divisor = right.value_s
|
|
353
|
+
signed_min = -(1 << (left.memsize - 2)) * 2
|
|
354
|
+
if dividend == signed_min && divisor == -1
|
|
354
355
|
raise IntegerOverflow, "integer overflow"
|
|
355
356
|
end
|
|
356
|
-
|
|
357
|
+
iresult = dividend / divisor
|
|
358
|
+
# Ruby rounds integer division down; Wasm truncates toward zero.
|
|
359
|
+
if (dividend < 0) != (divisor < 0) && dividend % divisor != 0
|
|
360
|
+
iresult += 1
|
|
361
|
+
end
|
|
357
362
|
runtime.stack.push(I32(iresult))
|
|
358
363
|
|
|
359
364
|
|
|
@@ -447,8 +452,8 @@ module Wardite
|
|
|
447
452
|
end
|
|
448
453
|
k = (right.value % right.memsize)
|
|
449
454
|
rotated = left.value << k
|
|
450
|
-
rest = left.value
|
|
451
|
-
value = rotated |
|
|
455
|
+
rest = left.value >> (right.memsize - k)
|
|
456
|
+
value = rotated | rest
|
|
452
457
|
runtime.stack.push(I32(value))
|
|
453
458
|
|
|
454
459
|
|
|
@@ -352,7 +352,7 @@ module Wardite
|
|
|
352
352
|
finish = target.memsize
|
|
353
353
|
count = 0
|
|
354
354
|
while count < finish
|
|
355
|
-
if
|
|
355
|
+
if target.value[count].zero?
|
|
356
356
|
count += 1
|
|
357
357
|
else
|
|
358
358
|
break
|
|
@@ -369,7 +369,7 @@ module Wardite
|
|
|
369
369
|
digits = target.memsize
|
|
370
370
|
count = 0
|
|
371
371
|
digits.times do |i|
|
|
372
|
-
if
|
|
372
|
+
if target.value[i].nonzero?
|
|
373
373
|
count += 1
|
|
374
374
|
end
|
|
375
375
|
end
|
|
@@ -381,7 +381,7 @@ module Wardite
|
|
|
381
381
|
if !right.is_a?(I64) || !left.is_a?(I64)
|
|
382
382
|
raise EvalError, "maybe empty or invalid stack"
|
|
383
383
|
end
|
|
384
|
-
runtime.stack.push(
|
|
384
|
+
runtime.stack.push(left.add(right))
|
|
385
385
|
|
|
386
386
|
|
|
387
387
|
when :i64_sub
|
|
@@ -397,7 +397,7 @@ module Wardite
|
|
|
397
397
|
if !right.is_a?(I64) || !left.is_a?(I64)
|
|
398
398
|
raise EvalError, "maybe empty or invalid stack"
|
|
399
399
|
end
|
|
400
|
-
runtime.stack.push(
|
|
400
|
+
runtime.stack.push(left.multiply(right))
|
|
401
401
|
|
|
402
402
|
|
|
403
403
|
when :i64_div_s
|
|
@@ -405,12 +405,17 @@ module Wardite
|
|
|
405
405
|
if !right.is_a?(I64) || !left.is_a?(I64)
|
|
406
406
|
raise EvalError, "maybe empty or invalid stack"
|
|
407
407
|
end
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
408
|
+
dividend = left.value_s
|
|
409
|
+
divisor = right.value_s
|
|
410
|
+
signed_min = -(1 << (left.memsize - 2)) * 2
|
|
411
|
+
if dividend == signed_min && divisor == -1
|
|
411
412
|
raise IntegerOverflow, "integer overflow"
|
|
412
413
|
end
|
|
413
|
-
|
|
414
|
+
iresult = dividend / divisor
|
|
415
|
+
# Ruby rounds integer division down; Wasm truncates toward zero.
|
|
416
|
+
if (dividend < 0) != (divisor < 0) && dividend % divisor != 0
|
|
417
|
+
iresult += 1
|
|
418
|
+
end
|
|
414
419
|
runtime.stack.push(I64(iresult))
|
|
415
420
|
|
|
416
421
|
|
|
@@ -473,10 +478,7 @@ module Wardite
|
|
|
473
478
|
if !right.is_a?(I64) || !left.is_a?(I64)
|
|
474
479
|
raise EvalError, "maybe empty or invalid stack"
|
|
475
480
|
end
|
|
476
|
-
|
|
477
|
-
value %= 1 << right.memsize
|
|
478
|
-
|
|
479
|
-
runtime.stack.push(I64(value))
|
|
481
|
+
runtime.stack.push(left.shift_left(right.value % 64))
|
|
480
482
|
|
|
481
483
|
|
|
482
484
|
when :i64_shr_s
|
|
@@ -502,10 +504,8 @@ module Wardite
|
|
|
502
504
|
if !right.is_a?(I64) || !left.is_a?(I64)
|
|
503
505
|
raise EvalError, "maybe empty or invalid stack"
|
|
504
506
|
end
|
|
505
|
-
k =
|
|
506
|
-
|
|
507
|
-
rest = left.value & (I64::I64_MAX << (right.memsize - k))
|
|
508
|
-
value = rotated | (rest >> (right.memsize - k))
|
|
507
|
+
k = right.value % 64
|
|
508
|
+
value = left.shift_left(k).value | (left.value >> (64 - k))
|
|
509
509
|
runtime.stack.push(I64(value))
|
|
510
510
|
|
|
511
511
|
|
|
@@ -514,10 +514,8 @@ module Wardite
|
|
|
514
514
|
if !right.is_a?(I64) || !left.is_a?(I64)
|
|
515
515
|
raise EvalError, "maybe empty or invalid stack"
|
|
516
516
|
end
|
|
517
|
-
k =
|
|
518
|
-
|
|
519
|
-
rest = left.value & (I64::I64_MAX >> (right.memsize - k))
|
|
520
|
-
value = rotated | (rest << (right.memsize - k))
|
|
517
|
+
k = right.value % 64
|
|
518
|
+
value = (left.value >> k) | left.shift_left((64 - k) % 64).value
|
|
521
519
|
runtime.stack.push(I64(value))
|
|
522
520
|
|
|
523
521
|
|