Files
R8Forge/asm/mul.r8asm
T
dsh 185b4bf24a The multiplier, 3729 characters, by repeated addition
clb_mul  MC MUL PL PH MCA S Ci T F NR    (PH:PL) = MC * MUL
    10 cells, 3729 characters, 64 sampled cases, 255*255 = 0xFE01 included

For scale: fibonacci is 8761 characters and does not multiply.  The tape length
does not depend on MUL at all, because the loop body appears once.

The algorithm is repeated addition, not shift-and-add:

    (PH:PL) = 0
    while MUL != 0:  (PH:PL) += MC ; MUL -= 1

which is the same lever as clb_add_ip: length is the metric, steps are not.  Worst
case is about a million steps against the five million limit and that is fine.

The 16 bit accumulate uses clb_add_nc for the low byte because it is the one that
reports a carry out; clb_add_ip does not, so it cannot do that step.  clb_add_nc
eats its operands, so each round copies the multiplicand first.  The carry then
goes into the high byte with clb_add_ip, which costs nothing extra since it is
0 or 1.

Worth recording what this did to my own plan: I had said the multiplier needed
"cross byte shifts" and "conditional accumulate" first, and sketched a
shift-and-add design around them.  Repeated addition needs neither -- the shift
disappears entirely.  The primitive that actually mattered was the one I called
missing two messages earlier: an add that keeps the addend alive, which is what
pushed out clb_add_ip and clb_nonzero.  Look at the objective function before
copying the shape of a hardware multiplier.

byte_op_test is seventeen operations, still 1.4 s, with test_mul sampled over
8 multipliers x 8 multiplicands.
2026-11-07 09:56:03 +08:00

57 lines
1.3 KiB
Plaintext

%include "asm/add_ip.r8asm"
%include "asm/raw_add_nc.r8asm"
; 8 位乘法:MC * MUL -> (PH:PL),16 位积。
;
; 算法是**重复加法**,不是移位-加法:
;
; 积 = 0
; while MUL != 0: (PH:PL) += MC ; MUL -= 1
;
; 为什么敢这么写 —— 和 clb_add_ip 同一个理由:**这里只有纸带长度是目标,运行步数不是**。
; 循环体在纸带里只出现一次,所以长度不随 MUL 变化;代价是运行 O(MUL)(255 时约 100 万步,
; 上限 500 万)。
;
; 16 位累加靠 clb_add_nc 的进位输出:低字节相加拿到进位,再用 clb_add_ip 把这一位加进高字节。
; clb_add_nc 会把两个操作数吃掉,所以每轮先把被乘数复印一份(clb_add_ip 是原地加法,但它
; 不输出进位,所以这一步只能用会吃操作数的那条)。
; Macro clb_mul
; %1: Cell MC
; %2: Cell MUL
; %3: Cell PL
; %4: Cell PH
; %5: Cell MCA
; %6: Cell S
; %7: Cell Ci
; %8: Cell T
; %9: Cell F
; %10: Cell NR
;
; (PH:PL) = MC * MUL。MC 保持原样,MUL 结束为 0。
%macro clb_mul 10
.anchor before_clb_mul
erase %3
erase %4
clb_nonzero %2 %10 %8
.tp %10
biz
.tp %1
copy %5 %8
.tp %7
set_0
clb_add_nc %3 %5 %6 %7
.tp %6
copy %3 %8
clb_add_ip %4 %7 %8 %9
clb_dec_ip %2 %8
clb_nonzero %2 %10 %8
.tp %10
rnz
.tp before_clb_mul
%endmacro