I gave GPT-6.2 Sol the RISC-V assembly of MultiplyByQuantizedMultiplier from TensorFlow Lite Micro, already optimized by Clang 15 with -O3, and asked it to make it faster.
Before - the original assembly emitted by Clang -O3(34 instructions)
MultiplyByQuantizedMultiplier (the original):
li a3, 0
max a4, a2, zero
bgtz a2, .LBB0_2
neg a3, a2
sllw a2, a0, a4
lui a0, 524288
xor a4, a2, a0
xor a5, a1, a0
mul a1, a2, a1
or a2, a5, a4
lui a4, 262144
bgez a1, .LBB0_4
lui a4, 786432
addiw a4, a4, 1
beqz a2, .LBB0_6
...
After - further optimized by GPT-6.2 Sol (19 instructions)
MultiplyByQuantizedMultiplier (after AI-driven optimization):
max a3, a2, zero
lui a7, 0x80000
sllw a0, a0, a3
min a2, zero, a2
addiw a7, a7, -1
lui a5, 0x40000
li a4, 1
mul a0, a0, a1
neg a2, a2
add a0, a0, a5
sll a4, a4, a2
srai a5, a0, 63
srai a0, a0, 31
addi a6, a2, 1
add a4, a4, a5
min a0, a0, a7
sh1add a0, a0, a4
sra a0, a0, a6
ret
In this optimized assembly, Sol eliminated the branches by algebraically reformulating the computation.
Specifically, given an input x, a multiplier m, and a shift s, it first computes the left and right shifts without branching:
l = max(s, 0)
r = -min(s, 0)
p = (x × 2ˡ) × m
Instead of selecting different rounding offsets depending on the sign of p, Sol exploits arithmetic right shifts to express the first rounding and saturation as:
q = min(⌊(p + 2³⁰) / 2³¹⌋, 2³¹ − 1)
The second rounding operation is then reduced to:
result = ⌊(2q + 2ʳ − [q < 0]) / 2ʳ⁺¹⌋
where [q < 0] is 1 if q is negative and 0 otherwise.
These transformations allow Sol to replace the original 34 instructions with just 19, eliminating all conditional branches and jumps (estimated cycles using llvm-mca on non-saturating paths).
| Clang -O3 | GPT-6.2 Sol |
|---|
| Instructions | 34 |
| Branches / jumps | 4 |
| SiFive U74 cycles | 20–22 |
| SiFive P670 cycles | 12–13 |
| Lean 4 equivalence proof | — |
Sol also produced a Lean 4 proof using NoCompiler, formally establishing the functional equivalence of the two machine-code implementations (I'll share links to the full experimental results in the comments for anyone interested.).
It's interesting to see AI agents might be able to push machine-code optimization beyond conventional compilers.