Loop unrolling


Loop unrolling, also known as loop unwinding, is a loop transformation technique that attempts to optimize a program's execution speed at the expense of its binary size, which is an approach known as space–time tradeoff. The transformation can be undertaken manually by the programmer or by an optimizing compiler.
The goal of loop unwinding is to increase a program's speed by reducing or eliminating instructions that control the loop, such as pointer arithmetic and "end of loop" tests on each iteration; reducing branch penalties; as well as hiding latencies, including the delay in reading data from memory. To eliminate this computational overhead, loops can be re-written as a repeated sequence of similar independent statements.
Loop unrolling is also part of certain formal verification techniques, in particular bounded model checking.

Advantages

The overhead in "tight" loops often consists of instructions to increment a pointer or index to the next element in an array, as well as "end of loop" tests. If an optimizing compiler or assembler is able to pre-calculate offsets to each individually referenced array variable, these can be built into the machine code instructions directly, therefore requiring no additional arithmetic operations at run time.
Optimizing compilers will sometimes perform the unrolling automatically, or upon request.

Disadvantages

Manual loop unrolling involves the programmer analyzing the loop and interpreting the iterations into a sequence of instructions which will reduce the loop overhead. This is in contrast to dynamic unrolling which is accomplished by the compiler.

Simple manual example in C

A procedure in a computer program is to delete 100 items from a collection. This is normally accomplished by means of a for-loop which calls the function delete. If this part of the program is to be optimized, and the overhead of the loop requires significant resources compared to those for the delete function, unwinding can be used to speed it up.
Normal loopAfter loop unrolling


int x;
for


int x;
for

As a result of this modification, the new program has to make only 20 iterations, instead of 100. Afterwards, only 20% of the jumps and conditional branches need to be taken, and represents, over many iterations, a potentially significant decrease in the loop administration overhead. To produce the optimal benefit, no variables should be specified in the unrolled code that require pointer arithmetic. This usually requires "base plus offset" addressing, rather than indexed referencing.
On the other hand, this manual loop unrolling expands the source code size from 3 lines to 7, that have to be produced, checked, and debugged, and the compiler may have to allocate more registers to store variables in the expanded loop iteration. In addition, the loop control variables and number of operations inside the unrolled loop structure have to be chosen carefully so that the result is indeed the same as in the original code. For example, consider the implications if the iteration count were not divisible by 5. The manual amendments required also become somewhat more complicated if the test conditions are variables. See also Duff's device.

Early complexity

In the simple case, the loop control is merely an administrative overhead that arranges the productive statements. The loop itself contributes nothing to the results desired, merely saving the programmer the tedium of replicating the code a hundred times which could have been done by a pre-processor generating the replications, or a text editor. Similarly, if-statements and other flow control statements could be replaced by code replication, except that code bloat can be the result. Computer programs easily track the combinations, but programmers find this repetition boring and make mistakes.
Consider:
Normal loopAfter loop unrolling

for i := 1:8 do
if i mod 2 = 0 then do_even_stuff
else do_odd_stuff;
next i;

do_odd_stuff; do_even_stuff;
do_odd_stuff; do_even_stuff;
do_odd_stuff; do_even_stuff;
do_odd_stuff; do_even_stuff;

But of course, the code performed need not be the invocation of a procedure, and this next example involves the index variable in computation:
Normal loopAfter loop unrolling

x := 1;
For i := 2:9 do
x := x * i;
print i, x;
next i;

x := 1;
x := x * 2; print 2, x;
x := x * 3; print 3, x;
x := x * 4; print 4, x;
... etc.

which, if compiled, might produce a lot of code but further optimization is possible. This example makes reference only to x and x in the loop therefore, given that there is no later reference to the array x developed here, its usages could be replaced by a simple variable. Such a change would however mean a simple variable whose value is changed whereas if staying with the array, the compiler's analysis might note that the array's values are constant, each derived from a previous constant, and therefore carries forward the constant values so that the code becomes
print 2, 2;
print 3, 6;
print 4, 24;
...etc.
In general, the content of a loop might be large, involving intricate array indexing. These cases are probably best left to optimizing compilers to unroll. Replicating innermost loops might allow many possible optimisations yet yield only a small gain unless n is large.

Unrolling WHILE loops

Consider a pseudocode WHILE loop similar to the following:
Normal loopAfter loop unrollingUnrolled & "tweaked" loop

WHILE DO
action
ENDWHILE
.
.
.
.
.
.

WHILE DO
action
IF NOT THEN GOTO break
action
IF NOT THEN GOTO break
action
ENDWHILE
LABEL break:
.

IF THEN
REPEAT
action
IF NOT THEN GOTO break
action
IF NOT THEN GOTO break
action
WHILE
LABEL break:

In this case, unrolling is faster because the ENDWHILE will be executed 66% less often.
Even better, the "tweaked" pseudocode example, that may be performed automatically by some optimizing compilers, eliminating unconditional jumps altogether.

Dynamic unrolling

Since the benefits of loop unrolling are frequently dependent on the size of an array—which may often not be known until run time—JIT compilers can determine whether to invoke a "standard" loop sequence or instead generate a sequence of individual instructions for each element. This flexibility is one of the advantages of just-in-time techniques versus static or manual optimization in the context of loop unrolling. In this situation, it is often with relatively small values of n where the savings are still useful—requiring quite small overall increase in program size.
Assembly language programmers are also able to benefit from the technique of dynamic loop unrolling, using a method similar to that used for efficient branch tables. Here, the advantage is greatest where the maximum offset of any referenced field in a particular array is less than the maximum offset that can be specified in a machine instruction.

Assembler example (IBM/360 or Z/Architecture)

This example is for IBM/360 or Z/Architecture assemblers and assumes a field of 100 bytes is to be copied from array FROM to array TO—both having 50 entries with element lengths of 256 bytes each.
  • The return address is in R14.
  • Initialize registers R15, R0, R1, and R2 from data defined at the end of
  • the program starting with label INIT/MAXM1.
LM R15,R2,INIT Set R15 = maximum number of MVC
  • instructions,
  • R0 = number of entries of array,
  • R1 = address of 'FROM' array, and
  • R2 = address of 'TO' array.
  • The loop starts here.
LOOP EQU * Define LOOP label.
  • At this point, R15 will always contain the number 16.
SR R15,R0 Subtract the remaining number of
  • entries in the array from R15.
BNP ALL If R15 is not positive, meaning we
  • have more than 16 remaining entries
  • in the array, jump to do the entire
  • MVC sequence and then repeat.
  • Calculate an offset for unconditional branch to
  • the 'unwound' MVC loop below.
  • If the number of remaining entries in the arrays is zero, R15 will be 16, so
  • all the MVC instructions will be bypassed.
MH R15,=AL2 Multiply R15 by the length of one
  • MVC instruction.
B ALL Jump to ALL+R15, the address of the
  • calculated specific MVC instruction
  • with drop through to the rest of them.
  • MVC instruction 'table'.
  • First entry has maximum allowable offset with single register = hexadecimal F00
  • in this example.
  • All 16 of the following MVC instructions use base-plus-offset
  • addressing and each to/from offset decreases by the length of one array element
  • . This avoids pointer arithmetic being required for each element up to a
  • maximum permissible offset within the instruction of hexadecimal FFF
  • . The instructions are in order of decreasing offset, so the last
  • element in the set is moved first.
ALL MVC 15*256,15*256 Move 100 bytes of 16th entry from
  • array 1 to array 2.
ILEN EQU *-ALL Set ILEN to the length of the previous
  • MVC instruction.
MVC 14*256,14*256 Move 100 bytes of 15th entry.
MVC 13*256,13*256 Move 100 bytes of 14th entry.
MVC 12*256,12*256 Move 100 bytes of 13th entry.
MVC 11*256,11*256 Move 100 bytes of 12th entry.
MVC 10*256,10*256 Move 100 bytes of 11th entry.
MVC 09*256,09*256 Move 100 bytes of 10th entry.
MVC 08*256,08*256 Move 100 bytes of 9th entry.
MVC 07*256,07*256 Move 100 bytes of 8th entry.
MVC 06*256,06*256 Move 100 bytes of 7th entry.
MVC 05*256,05*256 Move 100 bytes of 6th entry.
MVC 04*256,04*256 Move 100 bytes of 5th entry.
MVC 03*256,03*256 Move 100 bytes of 4th entry.
MVC 02*256,02*256 Move 100 bytes of 3rd entry.
MVC 01*256,01*256 Move 100 bytes of 2nd entry.
MVC 00*256,00*256 Move 100 bytes of 1st entry.
S R0,MAXM1 Reduce the number of remaining entries
  • to process.
BNPR R14 If no more entries to process, return
  • to address in R14.
AH R1,=AL2 Increment 'FROM' array pointer beyond
  • first set.
AH R2,=AL2 Increment 'TO' array pointer beyond
  • first set.
L R15,MAXM1 Reload the maximum number of MVC
  • instructions per batch into R15
  • .
B LOOP Execute loop again.
  • Static constants and variables.
INIT DS 0A 4 addresses to be
MAXM1 DC A Maximum number of MVC instructions
  • executed per batch.
N DC A Number of actual entries in array.
DC A Address of start of array 1
  • .
DC A Address of start of array 2
  • .
  • Static arrays.
FROM DS 50CL256 Array of 50 entries of 256 bytes each.
TO DS 50CL256 Array of 50 entries of 256 bytes each.

In this example, approximately 202 instructions would be required with a "conventional" loop, whereas the above dynamic code would require only about 89 instructions. If the array had consisted of only two entries, it would still execute in approximately the same time as the original unwound loop. The increase in code size is only about 108 bytes even if there are thousands of entries in the array.
Similar techniques can of course be used where multiple instructions are involved, as long as the combined instruction length is adjusted accordingly. For example, in this same example, if it is required to clear the rest of each array entry to nulls immediately after the 100 byte field copied, an additional clear instruction, XC xx*256+100,xx*256+100, can be added immediately after every MVC in the sequence.
It is, of course, perfectly possible to generate the above code "inline" using a single assembler macro statement, specifying just four or five operands, making the optimization readily accessible.

C example

The following example demonstrates dynamic loop unrolling for a simple program written in C. Unlike the assembler example above, pointer/index arithmetic is still generated by the compiler in this example because a variable is still used to address the array element. Full optimization is only possible if absolute indexes are used in the replacement statements.

  1. include
/* The number of entries processed per loop iteration. */
/* Note that this number is a 'constant constant' reflecting the code below. */
  1. define BUNCHSIZE
int main

Code duplication could be avoided by writing the two parts together as in Duff's device.

C to MIPS assembly language loop unrolling example

The following example will compute a dot product of two 100-entry vectors A and B of type double. Here is the code in C:
double dotProduct = 0;
for

Converting to MIPS assembly language

The following is MIPS assembly code that will compute the dot product of two 100-entry vectors, A and B, before implementing loop unrolling. The code below omits the loop initializations:
Note that the size of one element of the arrays is 8 bytes.
loop3:
l.d $f10, 0 ; $f10 ← A
l.d $f12, 0 ; $f12 ← B
mul.d $f10, $f10, $f12 ; $f10 ← A*B
add.d $f8, $f8, $f10 ; $f8 ← $f8 + A*B
addi $5, $5, 8 ; increment pointer for A by the size
; of a double.
addi $6, $6, 8 ; increment pointer for B by the size
; of a double.
addi $7, $7, -1 ; decrement loop count
test:
bgtz $7, loop3 ; Continue if loop count > 0

Unrolling the Loop in MIPS

The following is the same as above, but with loop unrolling implemented at a factor of 4. Note again that the size of one element of the arrays is 8 bytes; thus the 0, 8, 16, 24 displacements and the 32 displacement on each loop.
loop3:
l.d $f10, 0 ; iteration with displacement 0
l.d $f12, 0
mul.d $f10, $f10, $f12
add.d $f8, $f8, $f10
l.d $f10, 8 ; iteration with displacement 8
l.d $f12, 8
mul.d $f10, $f10, $f12
add.d $f8, $f8, $f10
l.d $f10, 16 ; iteration with displacement 16
l.d $f12, 16
mul.d $f10, $f10, $f12
add.d $f8, $f8, $f10
l.d $f10, 24 ; iteration with displacement 24
l.d $f12, 24
mul.d $f10, $f10, $f12
add.d $f8, $f8, $f10
addi $5, $5, 32
addi $6, $6, 32
addi $7, $7, -4
test:
bgtz $7, loop3 ; Continue loop if $7 > 0