From b962c345c8b51c0c3f16241eb84cf6a8170124e0 Mon Sep 17 00:00:00 2001 From: dsh Date: Sat, 7 Nov 2026 17:55:39 +0800 Subject: [PATCH] clb_digits: derive the digit count from _CELL_SIZE The round count was spelled out as four 1s in the counter; it is a function of the cell width (L = floor(W*log10(2)) + 1, integer approximated as W*30103/100000 + 1, which gives 3/4/5/10 for 8/11/16/32 bits), and r8asm evaluates that inside %rep, so the counter now builds itself: %rep _CELL_SIZE * 30103 / 100000 rol set_1 %endrep What is still spelled out is the shift chain (three copies with distinct offsets), because each step names a different cell and r8asm has no %if, no indexed %rep and no recursion -- it cannot emit L-1 different instruction groups. So the macro is correct for _CELL_SIZE == 11 only, and the comment now says so loudly: a 16 bit cell needs one more step and one more cell, otherwise the result is silently wrong. Making it generic needs an indexed %for in the assembler (or a ten cell region with a fixed nine step chain, which works at any width but costs three thousand characters and six cells). All eleven values still correct at 11 bits, 13743 characters with the driver. --- asm/digits.r8asm | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/asm/digits.r8asm b/asm/digits.r8asm index bce755d..ed3ec67 100644 --- a/asm/digits.r8asm +++ b/asm/digits.r8asm @@ -17,8 +17,15 @@ ; 第 4 轮: 挪(三位 -> 高位) ; REG+0 = 千位 ; ; 挪的顺序必须**从高到低**(REG+2 -> REG+3、REG+1 -> REG+2、REG+0 -> REG+1), +; 否则先把低位搬上去会盖掉还没搬的高位。这样最后 REG+0..3 正好是千、百、十、个, ; 也就是"高位在前"的字符串,不用倒序、不用 4 个分支。 ; +; **约束:挪位链是 L-1 = 3 步,写死的。** 轮数(上面 K 的个数)会跟着位宽自动算, +; 但挪位链不行 —— 每一步要写*不同*的地址(REG+1、REG+2、REG+3),而 r8asm 没有 +; `%if`、`%rep` 也没有循环变量,没法"按 L 生成 L-1 段不同的代码"。所以本宏 +; **只在 `_CELL_SIZE == 11`(L=4)下正确**;位宽改 16 时要加一步 `REG+3 -> REG+4` +; (并多给一格),否则静默出错。彻底的解法是给汇编器加一个带下标的 `%for`。 +; ; (第一版是 4 个分支 + one-hot flag 分派,只跑对了第一支 —— 甩掉分派之后不仅 ; 正确,还少了两层嵌套和 4 个 cell。) ; @@ -41,15 +48,17 @@ %macro clb_digits 3 .anchor before_clb_digits -; ---- K = 4 个连续的 1(第 0..3 位),给 loop 用 +; ---- K = L 个连续的 1(第 0..L-1 位),给 loop 用 +; +; L = 十进制位数 = floor(_CELL_SIZE * log10(2)) + 1,用 30103/100000 做整数近似: +; 11 位 -> 4、16 位 -> 5、8 位 -> 3、32 位 -> 10,和 2^W-1 的真实位数一致。 +; **轮数因此自动跟着位宽走**,不用手改。 .tp %3+6 set_1 -rol -set_1 -rol -set_1 -rol -set_1 +%rep _CELL_SIZE * 30103 / 100000 + rol + set_1 +%endrep ; ---- 四位,一轮一位 loop %3+6