Techniquecore
Strength reduction
Also called reduction in strength.
Replaces costly operations by cheaper ones, such as a multiply by an induction variable in a loop by an add each iteration.
Strength reduction replaces an operation by a cheaper one that gives the same result. In one instruction, a multiply by 8 becomes a shift by 3. In a loop, the important case, a product i * k of an induction variable i, which the loop changes by the same amount each time, and a value k that the loop does not change, becomes a new variable t. The loop keeps t equal to i * k with one add each time it changes i. The multiply goes away. Often i is then used only to test for the end of the loop, and linear function test replacement rewrites that test in terms of t, so that i dies.
In plain words
Some operations cost more than others: a multiply costs more than an add, and a divide costs much more. If a loop counts 0, 1, 2, 3 and multiplies the count by 7 each time, the products are 0, 7, 14, 21. The compiler can keep a second counter that starts at 0 and goes up by 7 each time, and drop the multiply. In the same way, a multiply by 8 can become a shift, which is cheaper. The new form must give the same answer for every input. A divide by 8 is not the same as a shift for negative numbers, so that change needs extra work.
When it applies
Local strength reduction. Inside one instruction, the rewrite is an identity of the target arithmetic. On integers, and on two's complement integers that wrap, x * 2^s equals x << s, and x * 2 equals x + x. A multiply by another constant can become a few shifts and adds, and a division by a constant can become a multiply by a precomputed constant and a shift, as Granlund and Montgomery show. The identity must hold for every value of the operand, including negative ones, see the pitfalls. Peephole optimization and instruction selection do most of these rewrites.
Loop strength reduction. Take a natural loop with a preheader : a block that runs once on each entry of the loop and jumps to the header, as defined in loop-invariant code motion. A value is invariant in if it is a constant or a name that no instruction of defines and that is not address-taken. The rewrite applies to an instruction : x = i * k in when:
- (C1) A basic induction variable.
iis not address-taken, and every instruction of that definesihas the formi = i + cori = i - c, with invariant in . Different definitions may use different . - (C2) An invariant factor.
kis invariant in .
The same rewrite works for x = k * i, and with an add in place of the product for x = i + k. A name j defined only by such reduced forms is a derived induction variable, and a product of j with an invariant can be reduced in turn. Induction variable analysis finds these families.
The template
The rewrite. Pick fresh names t and, for each definition i = i + c in , a name d. At the end of , before its jump, add t = i * k and d = c * k. Right after each i = i + c in , add t = t + d, and right after each i = i - c, add t = t - d. Replace by the copy x = t. Copy propagation then replaces the uses of x by t, and constant folding simplifies d = 1 * k and t = 0 * k.
Linear function test replacement. If after the rewrite i is read only by its own updates and by an exit test c = i < n with n invariant, and k is known to be positive, replace the test by c = t < m, with m = n * k added at the end of . For , holds exactly when . For the comparison turns around. Then i is read only by its updates, and dead code elimination removes it.
Legality. (C1) and (C2) are found by a scan of the definitions in , or on SSA form as a strongly connected component of the graph of definitions, as in operator strength reduction. The test replacement also needs the sign of k, and on machine integers it needs n * k and every value of t to fit without wrapping.
Profit. The cost model is the cost of the instructions executed, with a multiply more costly than an add. The rewrite removes one multiply per execution of and adds one add per execution of each update of i, plus two multiplies per entry of the loop. It pays when runs about as often as the updates. If sits behind a test that rarely holds, or the loop body runs zero times, the adds and the preheader multiplies can cost more than the multiplies saved. The new name t also stays live through the whole loop, which adds register pressure. On machines where a multiply costs about as much as an add, the gain is small, and the main benefit is that addresses base + i * w become pointers that move by w.
Proof that behavior stays the same. Let be the program with the preheader and let be the result. The two programs have the same blocks and the same terminators. has extra instructions that write only the fresh names t and d, and is a copy instead of a product. None of these can trap. Run both on the same input, block by block. Every name of has the same value in both runs, and the memory is the same, at every matched point, except perhaps x right after . We show that x also agrees, so this holds everywhere and the runs have the same outcome.
Consider one visit of the loop, from an arrival at until the run leaves . Inside it, no instruction writes k or any , by (C1) and (C2): they are not defined in , and a store or a call cannot write a name that is not address-taken. So k and each keep the values they have at the end of . Claim: in , at every point of the visit outside the gap between an update of i and the add that follows it, and for each d.
- At the end of ,
t = i * kandd = c * khave just run. ichanges only at an updatei = i + c, which the addt = t + dfollows at once. After both, . The same holds fori = i - cwith a minus. This identity holds on the integers and on integers modulo , so it holds for wrapping machine arithmetic too.- No other instruction writes
t,d,i,kor .
At , which is outside every gap, x = t therefore writes , the same value that x = i * k writes in . Outside the visits, t and d are never read. So the two runs agree on every name of and on the memory at every matched point, take the same branches, and end the same way.
For the test replacement: at the test, and by the same argument, and for , exactly when , as long as no product wraps. So c gets the same value. Removing the dead i is then a case of dead code elimination.
Classic examples
A product in a loop. The parameters are k and n. The block entry is the only way into the loop and ends with jump h, so it serves as the preheader.
entry:
i = 0
s = 0
jump h
h:
c = i < n
br c body done
body:
x = i * k
s = s + x
i = i + 1
jump h
done:
ret s
i is defined in the loop only by i = i + 1, and k is a parameter that the loop does not change. The rewrite adds t = i * k and d = 1 * k to entry, adds t = t + d after i = i + 1, and turns x = i * k into x = t. After constant folding and copy propagation, d is k:
entry:
i = 0
s = 0
t = i * k
jump h
h:
c = i < n
br c body done
body:
x = t
s = s + x
i = i + 1
t = t + k
jump h
done:
ret s
For , both return . The multiply in the loop is gone.
Test replacement. Let the factor be the constant 4. i is now read only by i = i + 1 and the test i < n. Since , the test becomes t < m with m = n * 4, and i dies:
entry:
s = 0
t = 0
m = n * 4
jump h
h:
c = t < m
br c body done
body:
s = s + t
t = t + 4
jump h
done:
ret s
For it returns , as the loop with x = i * 4 does. On 64-bit integers, n * 4 wraps when , and the new test is wrong, so a compiler must know that this cannot happen, for example because bounds the index of an array.
Array addresses. The most common case in practice. In for (i = 0; i < n; i++) s += a[i]; with 8-byte elements, the address of a[i] is a + i * 8. Strength reduction gives a pointer q that starts at a and moves by 8, and test replacement compares q with a + n * 8.
A local rewrite. y = x * 8 becomes y = x << 3, and y = x * 9 becomes y = (x << 3) + x. Both are identities for all integers, and also for wrapping integers.
Variations
- On SSA form. Operator strength reduction by Cooper, Simpson and Vick finds the induction variables as strongly connected components of the SSA graph, reduces each candidate as it visits the components, and does the test replacement. It gets results equal to those of the earlier algorithm of Allen, Cocke and Kennedy with a simpler method.
- Polynomials. A product of two induction variables, such as
i * i, is a polynomial in the iteration number. Its finite differences are again induction variables: . Chains of recurrences describe this and reduce a polynomial of degree to adds per iteration. - Division by invariants. A division by a constant, or by a value that the loop does not change, can be replaced by a multiply by a precomputed inverse and a shift. The magic constant comes from Granlund and Montgomery, and signed division needs a fix for negative dividends.
- With partial redundancy elimination. Strength reduction can be done inside SSAPRE, which treats the product at each iteration as partly redundant with the product of the iteration before.
- Induction variable elimination. After the test replacement, a basic induction variable that is read only by its own updates is dead. Removing it saves a register and an add per iteration.
Pitfalls
- Signed division by a shift. The toy IR, C and Java round integer division toward zero, but an arithmetic shift rounds down. For ,
x / 8is 0 whilex >> 3is . The correct sequence adds 7 to negative dividends before the shift. In the same wayx % 8is notx & 7for negativex: is in these languages, but is 7. - Wrapping in the test replacement.
i < nandi * k < n * kagree only if neither product wraps. A compiler that cannot rule out wrapping must keep the old test. - The sign of the factor. For the test turns around, and for it says nothing about
i. Test replacement with an unknownkneeds a runtime test or must be skipped. - Floating point. Replacing
x = i * hwith repeatedt = t + hchanges the rounding, and the error grows with the number of iterations. Compilers do not reduce floating-point products unless the programmer allows inexact math. - Rarely executed products. If the product sits in a branch that rarely runs, the new add runs on every update of
iand can cost more than it saves. - Pointers past the end. A reduced pointer and the test bound
a + n * 8may point past the end of an array. In C, forming a pointer more than one past the end is undefined, so the compiler that makes such pointers must make sure the target machine does not care.
Exercises
- In the first example, why is
t = i * kin the preheader and not simplyt = 0? Answer. The rewrite does not assume the start value ofi. Herei = 0reaches the preheader, so constant folding turnst = i * kintot = 0afterward. - The loop holds
i = i + 2in one branch andi = i + 3in the other. Canx = i * kbe reduced? Answer. Yes. (C1) allows several updates with different invariant steps. Addd2 = 2 * kandd3 = 3 * kto the preheader, and the matching add after each update. - Why must
knot be address-taken? Answer. A store through a pointer tok, or a call that gets such a pointer, could changekinside the loop without naming it. Then would no longer hold. - Give the rewrite for
x = i + k. Answer.t = i + kin the preheader,t = t + cafter eachi = i + c, andx = tin place of . The invariant is . - For which does the test-replaced loop of the second example give a different result from the original on 64-bit wrapping integers? Answer. When
n * 4wraps, that is for or . For large positive ,mbecomes negative or small and the new loop stops too early.
References
- Frances E. Allen, John Cocke and Ken Kennedy, Reduction of operator strength, in Steven S. Muchnick and Neil D. Jones (eds.), Program Flow Analysis, Theory and Applications, Prentice-Hall, 1981, pp. 79-101, the reduction of products of induction variables and region constants in strongly connected regions, and linear function test replacement
- John Cocke and Ken Kennedy, An algorithm for reduction of operator strength, Communications of the ACM 20(11), 1977, 850-856, the algorithm with a table of temporaries indexed by the reduced expression, and the extension to linear function test replacement
- Keith D. Cooper, L. Taylor Simpson and Christopher A. Vick, Operator strength reduction, ACM Transactions on Programming Languages and Systems 23(5), 2001, 603-625, the formulation on SSA form, with induction variables found as strongly connected components
- Alfred V. Aho, Monica S. Lam, Ravi Sethi and Jeffrey D. Ullman, Compilers, Principles, Techniques, and Tools, second edition, Addison-Wesley, 2007, Section 9.1.8 (Induction Variables and Reduction in Strength)
- Torbjörn Granlund and Peter L. Montgomery, Division by invariant integers using multiplication, Proceedings of the ACM SIGPLAN 1994 Conference on Programming Language Design and Implementation (PLDI), 1994, 61-72, the replacement of a division by a constant or by a loop-invariant divisor with a multiplication and shifts, for unsigned and signed operands
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 FGNWMJ Edit this page History Report an error Markdown