Techniquecore
Loop interchange
Also called loop permutation.
Swaps two loops of a nest, which can make memory access contiguous or move a parallel loop outward, when dependences allow.
Loop interchange swaps two adjacent loops of a perfect nest, so that for i: for j: S becomes for j: for i: S. The body and the set of iterations stay the same, and only their order changes. The interchange is legal exactly when no dependence would point backward in the new order, that is, when no distance vector has the direction on the two loops with before them. A compiler uses it for two goals. It can put the loop that walks memory with stride 1 innermost, which improves locality, and it can move a loop with no carried dependence inward for vector code or outward for coarse parallel work. A legal interchange is not always a good one: the same swap that helps one nest can make another nest several times slower.
In plain words
Picture a table of numbers that you visit cell by cell, row after row. Interchange means you visit it column after column instead. You still visit every cell once. The question is whether any cell needs a value that another cell computes first. If cell B uses the result of cell A, then A must still come before B in the new order. For a swap of rows and columns, only one shape of need breaks: a cell that uses a cell in the row above and in a column to the right. In the new order that right column is not yet done. When no cell needs such a value, the swap is safe. Then the only question is speed, and the swap can make it better or worse.
When it applies
The nest is perfect: the loops and are adjacent and all statements are inside the inner one. The bounds of loop do not depend on values that the body computes. The dependences of the nest are known as distance vectors , or, when the distance is not constant, as direction vectors over , and .
Theorem. Interchanging loops and maps every dependence to a lexicographically positive vector if and only if no dependence vector has , and . In direction vectors: no vector of the form with the at position .
By Theorem 1 of the legality page, an interchange that keeps every dependence pair in order keeps the meaning of the program. If a vector of the forbidden form exists, the swap runs the sink of a real dependence before its source, and the program reads a value that is not yet written, or writes over one that is not yet read. The example below shows that this changes the result.
The template
INTERCHANGE(nest, loops p and p + 1)- 1
for each dependence vector d of the nest do - 2
if d_1 = ... = d_(p-1) = 0 and d_p > 0 and d_(p+1) < 0 then - 3
return "illegal" ▷ this d becomes negative - 4
swap the headers of loops p and p + 1 - 5
recompute the bounds of the two loops ▷ by Fourier-Motzkin if they depend on each other - 6
return the new nest
The holes are the nest, the pair of loops, and the list of dependence vectors. When a vector has a direction and not a distance, the test of line L2 must treat as "could be , or ": a vector blocks the swap, because one of its instances is .
Proof of the theorem. The swap maps the vector to , which is with the entries and exchanged. A dependence vector is lexicographically positive, so it has a first nonzero entry, at level , and . Four cases:
- . The entries before do not move, so has the same first nonzero entry .
- . The entries and are both , so .
- . Then and , so is the first nonzero entry of .
- . Then . If , then is positive at . If , then is the first nonzero entry. If , then has its first nonzero entry negative, and .
So is negative in exactly one case: and , which is the condition of the theorem.
Bounds. For a rectangular nest, the bounds move with the headers. When the inner bounds depend on the outer index, write the bounds as inequalities and eliminate in the new order with Fourier-Motzkin elimination. For for i = 1 to n: for j = i to n, the inequalities are , , . With outer, eliminating gives , and then :
for j = 1 to n:
for i = 1 to j:
S(i, j)
Profit. The cost model is the number of cache misses, or the number of loop levels that carry no dependence at the place where they are useful. For an array stored row by row, A[i][j] with innermost walks memory with stride 1, and a cache line of elements serves accesses. With innermost, the stride is the row length , and each access touches a new line unless the cache holds a full column of lines.
Classic examples
An illegal swap. The nest
for i = 1 to n:
for j = 1 to n:
A[i][j] = A[i-1][j+1] + 1
has a flow dependence from to , with distance and direction . After the swap, the instance runs in the first column, before has written . With and the start values , the original order gives : it reads . The swapped order reads the old and gives . Nine of the 16 elements of the result differ. The loop skewing page shows how to make this nest interchangeable.
A legal swap with a parallel loop. for i: for j: A[i][j] = A[i-1][j] + A[i][j-1] has distances and . The swap maps them to and , both positive, and the swapped nest gives the same array. For A[i][j] = A[i-1][j] + 1 alone, the only distance is : the loop carries nothing. Kept inside, it is a vector loop. Moved outside, the distance becomes , the outer loop is a DOALL loop, and each thread runs one column.
Matrix multiplication orders. In C[i][j] = C[i][j] + A[i][k] * B[k][j] the only dependences are on C[i][j], with distance in the order . A vector with one nonzero entry stays positive under every permutation, so all six orders of the three loops are legal, and each order keeps the additions into one C[i][j] in increasing , so even the floating-point result is the same. They differ in speed: with the order , the inner loop walks B[k][j] and C[i][j] with stride 1, while the order walks B[k][j] with stride . Blocked matrix multiplication goes further with tiling.
Legal but unprofitable. for i = 0 to 63: for j = 0 to 63: A[i][j] = A[i][j] + 1 has no dependence between different iterations, so the swap is legal. Take a row-major array, lines of 8 elements and a fully associative LRU cache:
| cache size in lines | misses, inner | misses, inner |
|---|---|---|
| 32 | 512 | 4096 |
| 64 | 512 | 512 |
With inner, each line is loaded once: misses. With inner and 32 lines, the 64 rows of one column do not fit, every line is gone before the next column needs it, and every access misses. With 64 lines the column of lines fits and the cost is the same. A compiler must therefore pair the legality test with a cost model, as the Wolf-Lam algorithm does. The same swap applied to s = s + A[j][i] gives the opposite result: 4096 misses become 512.
Variations
- Loop permutation. Any permutation of a nest is legal if every permuted vector is lexicographically positive. Every permutation is a sequence of adjacent swaps, but the intermediate nests need not be legal, so test the final vectors.
- Interchange with reversal. Reversing a loop negates its entry. A forbidden becomes legal for interchange after the inner loop is reversed: swaps to . This is one of the unimodular transformations.
- Skew, then interchange. Skewing adds a multiple of the outer entry to the inner one, so that becomes , and then the swap is legal.
- Imperfect nests. Statements between the two loop headers must first be moved inside, with a guard, or split off with loop distribution.
- Tiling. Strip mining a loop and interchanging the strip loop outward is the basic step of loop tiling.
Pitfalls
- Treating as . A direction vector contains . Ignoring that case allows an illegal swap.
- Scalar temporaries. A scalar
tassigned and used in the body gives dependences in every direction, including , and blocks the swap. Array privatization or the expansion oftinto an array removes them. - Copying the bounds. In a triangular nest, swapping the headers without recomputing the bounds runs a different set of iterations.
- Checking legality only. A legal swap can raise the misses by a factor of 8 or more, as in the table above.
- Reductions in floating point. The test above keeps the order of the dependences. A compiler that also treats a reduction as free of dependences, to allow more orders, changes the order of the additions and the rounding of the result.
Exercises
- A nest has the distances and . Is the interchange legal? Answer. No. becomes .
- A nest has the distances , and . Is the interchange legal, and which loop carries each dependence after it? Answer. Yes. The new vectors are , and ; the outer loop carries and , the inner loop carries .
- Give the bounds after the interchange of
for i = 1 to n: for j = 1 to i. Answer.for j = 1 to n: for i = j to n. - A depth-3 nest has the distance . Which of the two adjacent swaps are legal? Answer. Swapping loops 1 and 2 gives , which is legal. Swapping loops 2 and 3 gives , which is not.
References
- John R. Allen and Ken Kennedy, Automatic loop interchange, Proceedings of the SIGPLAN '84 Symposium on Compiler Construction, ACM, 1984, 233-246, the direction-vector test for interchange, the (<, >) direction as the case that forbids it, and interchange for vector and parallel code
- Randy Allen and Ken Kennedy, Optimizing Compilers for Modern Architectures, a Dependence-Based Approach, Morgan Kaufmann, 2002 (copyright 2001), Section 5.2 (Loop Interchange), the legality theorem in direction vectors and the interchange of loops for vectorization; Chapter 9 (Managing Cache), interchange for stride
- Michael Wolfe, High Performance Compilers for Parallel Computing, Addison-Wesley, 1996, the chapter on loop restructuring, loop interchange of rectangular and triangular nests and the computation of the new bounds
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag ZBVENY Edit this page History Report an error Markdown