Assembly Language & Procedure Calls

loops in assembly

A loop is doing the same thing many times: sum every number in a list, draw every pixel in a row. High-level languages give you for and while keywords, but the machine has no such words. A loop in assembly is built by hand out of two simpler pieces you already have: a label marking the top of the repeated block, and a conditional branch at the bottom that jumps back to that label as long as you are not yet done. Round and round it goes until the condition fails.

Walk through a count-down loop that runs ten times. Put 10 into a counter register. Label the top, say loop:. Do the body of work. Subtract one from the counter. Then a conditional branch: if the counter is still greater than zero, branch back to loop; otherwise fall through to whatever comes next. Each trip checks the condition and either repeats or exits. A for loop over an array is the same idea with an index that you increment and a bound you compare against; array indexing inside the body uses the index to compute an address (base plus index times element size).

Loops matter because they are where programs spend most of their time, so they are the first place to look when tuning performance. Seeing the loop in assembly makes the real cost visible: how many instructions run per iteration, whether the loop variable lives in a register or gets reloaded from memory each time, and how the back-edge branch behaves. The branch at the bottom of a hot loop is almost always taken, which a branch predictor learns quickly, so loops are usually predicted well except on the final exit.

Summing an array of n words at base s0 into a0: li a0, 0 # sum = 0 li t0, 0 # i = 0 loop: bge t0, a1, done # if i >= n, exit slli t1, t0, 2 # t1 = i * 4 (word = 4 bytes) add t1, s0, t1 # address of element i lw t2, 0(t1) # load element add a0, a0, t2 # sum += element addi t0, t0, 1 # i++ j loop done:

A for loop: a label at the top, an exit branch, a body, an increment, and a jump back to the top.

Array indexing needs the element size: a 4-byte word at index i lives at base + i*4, not base + i. Forgetting to scale the index is a classic off-by-bytes bug.

Also called
assembly loops迴圈