From ca72e19b0bc552c15da9d3756c46c5280040645d Mon Sep 17 00:00:00 2001 From: dsh Date: Wed, 18 Nov 2026 10:29:53 +0800 Subject: [PATCH] tape_opt: the peephole pass -- 10% off the flagship tape with identical output r8forge_tape_opt rewrites a tape with three run-local rules: > < a maximal run of pointer moves becomes its net displacement + a run becomes (length % _CELL_SIZE), a whole turn is a no-op - a run becomes (length % 2), two flips cancel The nice part is what it does NOT do: it never looks at brackets. '[' and ']' are not in any of the three character classes, so they always end a run, and within a run only the net matters (the pointer moves are pure additions and nothing in between is observable). Keeping every run's net keeps the pointer identical at every surviving character, brackets included, so the pairing that the machine finds by scanning cannot change; and since bracket characters are never added or removed, a run can never be merged across one. No stack, no offset table, one linear pass. Measured, with tape_run's out stream compared before and after (and the reference machine on the flagship's -n stream, same 93 values): asm/test.r8asm 64513 -> 58060 (-6453, 10.0%) examples/calc.r8asm 62585 -> 54863 (-7722, 12.3%) "12 34 + ." identical examples/term.r8asm 3467 -> 3402 ( -65, 1.9%) "hi" identical Step counts unchanged (the removed instructions did nothing). Not yet wired into `r8forge` itself: the pipeline is `r8forge f.r8asm > t.rot8 && r8forge_tape_opt t.rot8 t2.rot8`, and a --opt flag can wrap that later. --- AGENTS.md | 1 + CMakeLists.txt | 3 ++ TODO.md | 2 +- tests/tape_opt.cc | 125 ++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 130 insertions(+), 1 deletion(-) create mode 100644 tests/tape_opt.cc diff --git a/AGENTS.md b/AGENTS.md index a2a06a0..b834b6f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -34,6 +34,7 @@ r8forge asm/test.r8asm # 64513 字符(除 raw_puts_dyn r8forge_byte_op_test # 21 项(divmod 16384 组、digits 2048、undigits 4096) r8forge_examples_test # 18 个 example + asm/test.r8asm,核对头部 `; out`/`; in` r8forge_macro_docs_test # 53 macros in 23 files +r8forge_tape_opt in.rot8 out.rot8 # 纸带窥孔优化:>< 净位移、+ mod W、- mod 2(全家桶 −10%) r8forge_synth_test examples/full_add.r8asm # all eight combinations ok r8forge_derive verify_loop.r8asm -1 0=5 # out 5 0 powershell -File tests\widths.ps1 # 位宽矩阵:每个位宽一套工具链 + 断言(约 20 分钟) diff --git a/CMakeLists.txt b/CMakeLists.txt index 5450877..10c7508 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -48,6 +48,9 @@ add_executable(r8forge_macro_docs_test tests/macro_docs_test.cc) add_executable(r8forge_examples_test tests/examples_test.cc) target_link_libraries(r8forge_examples_test r8forge_core) +# The tape level peephole pass: three run-local rules, no bracket bookkeeping. +add_executable(r8forge_tape_opt tests/tape_opt.cc) + add_executable(r8forge_cost_par tests/cost_par.cc) target_link_libraries(r8forge_cost_par r8forge_core) diff --git a/TODO.md b/TODO.md index 6815f71..355aada 100644 --- a/TODO.md +++ b/TODO.md @@ -22,7 +22,7 @@ ## 工具 -* **`r8forge --opt`:纸带级窥孔优化**(收益面最大):`><`、`<>`、`--`、11 个 `++`、 +* ~~`r8forge --opt`~~ 已实现为 **`r8forge_tape_opt`**(见下),原条目保留说明:`><`、`<>`、`--`、11 个 `++`、 重复清位…… 要能重算跳转偏移。配套 `r8forge_tape_diff`(比较两条纸带的 OUT 流和步数) 证明等价 —— 一次改动全库受益。 * **`--profile`**:统计每段宏/每个 cell 的步数占比和 `.tp` 行走距离,用数据决定下一步优化谁 diff --git a/tests/tape_opt.cc b/tests/tape_opt.cc new file mode 100644 index 0000000..c11c682 --- /dev/null +++ b/tests/tape_opt.cc @@ -0,0 +1,125 @@ +// r8forge_tape_opt -- the tape level peephole pass. +// +// r8forge_tape_opt [out.rot8] +// +// Three run-local rules. None of them needs to know where the brackets are, +// because '[' and ']' are not in any of the three character classes, so they +// always end a run: +// +// > < a maximal run of pointer moves becomes its net displacement +// + a run becomes (length % cell_size): a whole turn is a no-op +// - a run becomes (length % 2): two flips cancel +// +// A run never crosses another character: `> + >` is not `>> +`, the rotation +// would land on a different cell. Preserving the net of every run means the +// data pointer is unchanged at every surviving character (brackets included), +// so the pairing found by scanning at run time cannot change either. +#include "r8forge/geometry.hh" + +#include +#include +#include +#include +#include + +namespace { + +constexpr char kGt = '>'; +constexpr char kLt = '<'; +constexpr char kRor = '+'; +constexpr char kFlb = '-'; + +bool is_ins(char c) { return c != 0 && std::strchr("><+-[].,", c) != nullptr; } + +std::string optimize(const std::string &tape) { + const size_t width = kDefaultCellSize; + const size_t n = tape.size(); + std::string out; + out.reserve(n); + for (size_t i = 0; i < n;) { + const char c = tape[i]; + if (!is_ins(c)) { + i++; // a stray byte (newline, comment) does nothing; drop it + continue; + } + if (c == kGt || c == kLt) { + long net = 0; + while (i < n && (tape[i] == kGt || tape[i] == kLt)) { + net += tape[i] == kGt ? 1 : -1; + i++; + } + const char dir = net >= 0 ? kGt : kLt; + const long count = net >= 0 ? net : -net; + for (long k = 0; k < count; k++) { + out += dir; + } + continue; + } + if (c == kRor) { + size_t run = 0; + while (i < n && tape[i] == kRor) { + run++; + i++; + } + out.append(run % width, kRor); + continue; + } + if (c == kFlb) { + size_t run = 0; + while (i < n && tape[i] == kFlb) { + run++; + i++; + } + out.append(run % 2, kFlb); + continue; + } + out += c; + i++; + } + return out; +} + +} // namespace + +int main(int argc, char **argv) { + if (argc < 2) { + std::fprintf(stderr, "usage: r8forge_tape_opt [out.rot8]\n"); + return 2; + } + std::ifstream in(argv[1], std::ios::binary); + if (!in) { + std::fprintf(stderr, "could not open %s\n", argv[1]); + return 1; + } + const std::string tape((std::istreambuf_iterator(in)), + std::istreambuf_iterator()); + std::string filtered; + filtered.reserve(tape.size()); + for (char c : tape) { + if (is_ins(c)) { + filtered += c; + } + } + if (filtered.empty()) { + std::fprintf(stderr, "no instructions in %s\n", argv[1]); + return 1; + } + const std::string out = optimize(filtered); + if (argc > 2) { + std::ofstream f(argv[2], std::ios::binary); + if (!f) { + std::fprintf(stderr, "could not write %s\n", argv[2]); + return 1; + } + f << out; + } else { + std::fwrite(out.data(), 1, out.size(), stdout); + } + const size_t before = filtered.size(); + const size_t after = out.size(); + std::fprintf(stderr, + "r8forge_tape_opt: %zu -> %zu characters (%ld saved, %.1f%%)\n", + before, after, (long)(before - after), + 100.0 * (double)(before - after) / (double)before); + return 0; +}