Appendix E: Bit-Manipulation Assembly Examples

Part III Linux boot: optional Vol. I (Unprivileged) pp. 664–666 · ~2 min read

Non-normative optimization examples showing how Zbb’s orc.b and count instructions turn byte-at-a-time string loops into word-at-a-time ones.

strlen — NUL detection with orc.b

orc.b collapses each byte to 0xFF (any bit set) or 0x00 (the byte was NUL). So a word with no NUL byte becomes all-ones; negate the orc.b result and apply ctz (or clz, depending on endianness) to get the number of bytes before the first NUL:

    # aligned word loop (after handling the unaligned head)
    ld    a1, (a0)          # 8 bytes of the string
    orc.b a2, a1            # 0xFF per nonzero byte, 0x00 per NUL
    not   a2, a2            # NUL bytes -> 0xFF, others -> 0x00
    bnez  a2, found         # any NUL in this word?
    addi  a0, a0, 8
    j     loop
found:
    ctz   a2, a2            # bit index of first NUL; >>3 = byte offset

Eight bytes per iteration instead of eight loads-and-branches — and the full example handles the unaligned head so the hot loop stays aligned.

strcmp — difference detection

XOR two words (equal bytes → 0, differing bytes → nonzero), then orc.b + ctz locates the first differing byte; a parallel NUL check handles string ends. Only when a difference or NUL is flagged does the code fall back to a byte-precise comparison for the return value — turning the O(n) byte loop into O(n/8).

Hardware Designer Notes

For the hardware designer, these examples justify the Zbb mandate in RVA23: string processing is a huge fraction of real workloads, and orc.b + ctz make it 8× denser. If your orc.b and ctz aren’t single-cycle, these hot loops stall — verify them together. The final appendix is the extension rationale.

Minimal Linux-boot hart MUST

  • Nothing new — these validate orc.b/ctz/clz behavior already specified; they are the software the Zbb hardware accelerates

MAY simplify / trap-and-emulate

  • Use strlen/strcmp as Zbb microbenchmarks: they should run ~8× the byte-loop throughput once orc.b + ctz are single-cycle

Check yourself — bitmanip examples

1.How does the orc.b + ctz idiom find a string's length a word at a time?

2.The strcmp example XORs two words then applies orc.b. What does that combination find?

2 questions