LOGBOOK

HELP

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.

The compiled GCD as six basic blocks: the entry block branches to .L1 if a equals b, the loop top .L2 branches to the if or else block, both loop back to .L2 while a differs from b and otherwise reach .L1

* 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:

  1. The while condition 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 .L2 instead of first jumping to a separate test.
  2. The if (a > b) is written as its opposite: bgeu a3, a2 jumps to the else block when b >= a. Inside the loop a != b always holds, so b >= a means b > a.
  3. The labels .L1, .L2, .L4 mark basic blocks, straight-line runs of code that are entered only at the top. The .L prefix makes them local to the file, so they never become symbols.
  4. return a costs nothing: a has lived in a2, the result register, all along.

Go deeper:

From Quiz: SIOT / Xtensa LX6 Registers, Calls and Branches in Assembly | Updated: Nov 27, 2026