Loop Unrolling

The benefits of unrolling loops are:

The potential costs of unrolling loops are:

Assembly/Compiler Coding Rule 12. (H impact, M generality)

Unroll small loops until the overhead of the branch and the induction variable accounts, generally, for less than about 10% of the execution time of the loop.

Assembly/Compiler Coding Rule 13. (H impact, M generality)

Avoid unrolling loops excessively, as this may thrash the TC.

Assembly/Compiler Coding Rule 14. (M impact, M generality) Unroll loops that are frequently executed and that have a predictable number of iterations to reduce the number of iterations to 16 or fewer, unless this increases code size so that the working set no longer fits in the trace cache. If the loop body contains more than one conditional branch, then unroll so that the number of iterations is 16/(# conditional branches).

Loop Unrolling Example

The following loop unrolling example shows how unrolling enables other optimizations:

Before unrolling:

do i=1,100

if (i mod 2 == 0) then a(i) = x

else a(i) = y

enddo

After unrolling

do i=1,100,2

a(i) = y

a(i+1) = x

enddo

In this example, a loop that executes 100 times assigns x to every even-numbered element and y to every odd-numbered element. By unrolling the loop you can make both assignments each iteration, removing one branch in the loop body.