Loop interchange
In
For example, in the code fragment:
for j from 0 to 20 for i from 0 to 10 a[i,j] = i + j
loop interchange would result in:
for i from 0 to 10 for j from 0 to 20 a[i,j] = i + j
On occasion, such a transformation may create opportunities to further optimize, such as automatic vectorization of the array assignments.
The utility of loop interchange
The major purpose of loop interchange is to take advantage of the
In
Caveat
Loop interchange may lead to worse performance because cache performance is only part of the story. Take the following example:
do i = 1, 10000
do j = 1, 1000
a[i] = a[i] + b[j,i] * c[i]
end do
end do
Loop interchange on this example can improve the cache performance of accessing b(j,i), but it will ruin the reuse of a(i) and c(i) in the inner loop, as it introduces two extra loads (for a(i) and for c(i)) and one extra store (for a(i)) during each iteration. As a result, the overall performance may be degraded after loop interchange.
Safety
It is not always safe to exchange the iteration variables due to dependencies between statements for the order in which they must execute. To determine whether a compiler can safely interchange loops, dependence analysis is required.
See also
- Loop splitting
- Loop skewing
- Loop fission and fusion
- Loop unrolling
References
- ^ "Loop interchange" (PDF). Parallel Programming Guide for HP-UX Systems. HP. August 2003.
Further reading
- LCCN 2001092381.