Files
R8Forge/drv/nonzero_byte.r8asm
dsh a6560b72cf In place add, by looping instead of writing a carry chain
clb_dec_ip  A T        A = A - 1                2 cells  106 chars  256/256
    clb_nonzero B F T      F = (B != 0), B intact   3 cells  209 chars  256/256
    clb_add_ip  A B T F    A += B, B is eaten       4 cells  558 chars  2048 sampled

against raw_add (6 cells, 1647) and clb_add_nc plus a copy per round (688 + 364).
Add is the primitive the multiplier needs, so this was the expensive one.

decrement needed no new algorithm: B - 1 = ~(-B), so it is clb_neg_ip then
clb_not_ip, and both are already in place.

The add does not do a per bit carry chain, and it is worth being clear why not:
a full adder's carry is maj(a,b,c), i.e. a pairwise conjunction, and every
conditional test eats the bit it tests, so a hand written ripple needs several
copies of each bit and nested tests -- long and fragile, and it was the reason I
first called this impossible.

What works instead leans on something true of this project: the metric is tape
length, not execution steps.  So

    while B != 0:  A += 1 ; B -= 1

The loop body appears in the tape once, so the length does not depend on B.  The
cost is O(B) runtime, about 300k steps at B = 255 against a 5M limit.  This is a
general lever: anywhere length is what matters, ask whether a loop can replace
generated code.

The one thing that was genuinely awkward is "B != 0", since biz only looks at the
low bit.  clb_nonzero walks the eight bits, moves each into a work cell (which
clears that bit of B), and if it was set, sets F and puts the bit back; B comes
out untouched.  Note set_1, not flb: flb flips, so an even number of set bits
flipped the flag back to zero and 3, 5 and 255 all read as "zero" until I fixed
it.

For the multiplier this means one copy per round (364) to keep the multiplicand,
so about 920 per round, roughly 8k for the whole multiplier instead of 13k.

Tests: byte_op_test is sixteen operations now, 1.5 s.  test_add_ip is sampled
(8 accumulators x 256 addends) because the loop makes exhaustive runs slow.
2026-11-07 09:49:51 +08:00

16 lines
263 B
Plaintext

%include "asm/add_ip.r8asm"
; clb_nonzero 的驱动:F = (B != 0),B 应保持原样。
;
; r8forge_derive drv/nonzero_byte.r8asm -2 0=5
;
; out 依次是 B、F。B 应还是 5,F 应是 1。
.var B 0
.var F 1
.var T 2
clb_nonzero B F T
output B
output F