Quiz Entry - updated: 2026.11.27
How does the C while/if of Euclid's subtraction GCD turn into Xtensa branches and labels?
The loop test is checked once before the loop (beq to the exit) and again at the bottom of each branch (bne back to the top); the if becomes one bgeu that jumps to the else block. Each .Lx label starts a basic block that a jump can land on.
* Boxes are basic blocks, arrows are the branches between them. *
The C code repeatedly subtracts the smaller number from the larger until both are equal, which is then their greatest common divisor:
uint32_t gcd(uint32_t a, uint32_t b) {
while (a != b) {
if (a > b) a = a - b;
else b = b - a;
}
return a;
}
gcd: entry sp, 32
beq a2, a3, .L1 # a == b already? skip the loop
.L2: bgeu a3, a2, .L4 # b >= a? go to the else part
sub a2, a2, a3 # a = a - b
bne a3, a2, .L2 # still a != b? loop
j .L1 # done
.L4: sub a3, a3, a2 # b = b - a
bne a3, a2, .L2 # still a != b? loop
.L1: retw.n # result a is already in a2
How the pieces map:
- The
whilecondition appears three times. The compiler checks it once on entry, then copies it to the end of both branches, so each branch can jump straight back to.L2instead of first jumping to a separate test. - The
if (a > b)is written as its opposite:bgeu a3, a2jumps to theelseblock whenb >= a. Inside the loopa != balways holds, sob >= ameansb > a. - The labels
.L1,.L2,.L4mark basic blocks, straight-line runs of code that are entered only at the top. The.Lprefix makes them local to the file, so they never become symbols. return acosts nothing:ahas lived ina2, the result register, all along.
Go deeper:
Wikipedia — Euclidean algorithm — the subtraction version and why it terminates.
Wikipedia — Basic block — the unit compilers and disassemblers split code into.