Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 38 ยท The Text Format

Control Flow in WebAssembly

Learn structured control flow in WebAssembly text format: if/else, block, loop, br, br_if, br_table, return and unreachable, with factorial, gcd and prime examples.

C, Rust and JavaScript have if, while, for, switch and break. WebAssembly has none of those keywords. It has a smaller set of building blocks that all of them compile into: block, loop, if, and a few branch instructions that jump to an enclosing block. There is no goto to an arbitrary address, which is exactly what makes validation and compilation so fast and safe: every jump lands on a known label at the end or start of a structure.

if, then, else

if pops an i32 condition. If it is non-zero the then part runs, otherwise the else part. When the if produces a value, declare it with (result type), and both branches must leave exactly that on the stack.

WAT
(func (export "abs") (param $x i32) (result i32)
  (if (result i32) (i32.lt_s (local.get $x) (i32.const 0))
    (then (i32.sub (i32.const 0) (local.get $x)))
    (else (local.get $x))))

In the flat form this is if (result i32) ... else ... end. In the binary it becomes the opcode 0x04, a block type, the two instruction lists separated by 0x05 and closed by 0x0b.

block, loop and labels

A block is a region you can jump out of. A loop is a region you can jump back to the start of. Both can be given a label such as $done. The br instruction names a label and jumps there:

  • Branching to a block label continues after the end of that block, like break.
  • Branching to a loop label continues at the start of the loop, like continue.
flowchart TD
    S["block $done"] --> L["loop $again"]
    L --> C{"br_if $done: finished?"}
    C -- "yes: jump to after the block" --> E["after block"]
    C -- "no" --> B["loop body"]
    B --> J["br $again: jump back to loop start"]
    J --> L

Labels are really depth counters in the binary: br 0 means the innermost enclosing structure, br 1 the next one out, and so on. In text, $names hide the numbers, which is a good reason to name your labels.

The canonical while loop in WebAssembly is a block wrapped around a loop:

WAT
(block $done
  (loop $again
    (br_if $done (condition-to-stop))
    ;; ... body ...
    (br $again)))
Instruction Purpose
br $l Jump to label $l unconditionally
br_if $l Pop a condition; jump to $l if non-zero
br_table $a $b $c $default Pop an index; jump to the label at that position, or to the default (the last label) if out of range
return Leave the function now, using the values on the stack
unreachable Trap immediately; marks code that must never run
nop Do nothing

A branch to a block can carry values: if the block has a result type, the branch passes them along, which is how you write "break with a value".

A tour of examples

The module below contains eight functions, assembled by wat2wasm: abs, sign, sum (a loop), factorial (with i64), gcd (Euclid's algorithm), isPrime (an early return inside a loop), and dayType (a br_table switch). The key functions are shown in full below.

Node.js abs, sign, sum, factorial, gcd, isPrime and dayType

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Reading the loop examples

Here is sum in full. It adds 1 + 2 + ... + n:

WAT
(func (export "sum") (param $n i32) (result i32)
  (local $i i32)
  (local $acc i32)
  (local.set $i (i32.const 1))
  (block $done
    (loop $next
      (br_if $done (i32.gt_s (local.get $i) (local.get $n)))     ;; stop when i > n
      (local.set $acc (i32.add (local.get $acc) (local.get $i)))
      (local.set $i (i32.add (local.get $i) (i32.const 1)))
      (br $next)))                                                 ;; go round again
  (local.get $acc))

And dayType, a switch. br_table pops the day number. Index 0 and 6 branch to $weekend, indexes 1 to 5 to $weekday, and anything else uses the last label (the default). Branching to $weekday exits the inner block, so execution continues at return 1; branching to $weekend skips that line.

WAT
(func (export "dayType") (param $day i32) (result i32)
  (block $weekend
    (block $weekday
      (br_table $weekend $weekday $weekday $weekday $weekday $weekday $weekend $weekend
        (local.get $day)))
    (return (i32.const 1)))       ;; reached from $weekday
  (i32.const 0))                  ;; reached from $weekend

The same loop in raw bytes

Labels become depth numbers, which you can see by writing the loop with the byte builder. This sum uses block (0x02), loop (0x03), br_if 1 (leave the block, one level out) and br 0 (repeat the loop). The 0x40 after block and loop means "no result value".

Node.js Block, loop and branch depths in raw bytes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Structured means safe

Because jumps can only go to enclosing labels, the engine knows the shape of the whole function without analysis. Decompilers and compilers like it too: the if, block and loop structure maps almost directly to what C compilers produce. Compilers that start from arbitrary control flow (goto) use an algorithm called relooper (and its modern relatives) to rebuild structured code.

When a loop does not end, check three things: is there a br_if to leave? Does the loop variable change on every pass? And is the branch to the right label? br to a block leaves the loop, br to the loop repeats it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does br to a loop label do?

    A branch to a loop label continues at the loop's beginning. A branch to a block label continues after the block's end.
  2. 2. How is a while loop usually written in Wasm?

    The outer block provides the exit label and the loop provides the repeat label.
  3. 3. In br_table $a $b $c $d, which label is the default?

    The last label in the list is the default, used when the index is out of range.
  4. 4. What does br_if need on the stack?

    br_if pops an i32; it branches if the value is non-zero.
  5. 5. In the binary, what is a label?

    br 0 targets the innermost enclosing block, loop or if; br 1 the next one out.

Summary

  • Control flow is structured: block, loop and if with branches to enclosing labels.
  • br to a block ends it; br to a loop restarts it; br_if is conditional; br_table is a switch.
  • return leaves the function; unreachable traps.
  • Labels are depth numbers in binary and $names in text.
  • if, blocks and branches can carry result values.

Next: Functions, Locals and Calls