Algorithmadvanced
Operator strength reduction on SSA
Also called Cooper-Simpson-Vick strength reduction.
Finds induction variables as strongly connected components of the SSA graph and rewrites their multiplications into additions.
- Time
- O(b^3 + (n + m)^2) worst
- Space
- O(n + m + b) extra
- Where
- b = the number of blocks; m = the number of instructions that the pass creates; n = the size of the input (instructions and operands)
- Model
- Word RAM
- Properties
- deterministicofflinerecursive
- Evidence
- Proof sketchCode in 1 languages
Operator strength reduction on static single assignment form is the version of strength reduction that Cooper, Simpson and Vick gave in 2001. It finds the induction variables of a procedure as strongly connected components of the SSA graph, the graph from each name to the names its definition reads. A product iv * rc of an induction variable and a value that the loop does not change then becomes a new induction variable, which the loop updates with adds. The algorithm needs no loop tree and no data-flow analysis: one pass of Tarjan's algorithm over the SSA graph does the work. It ends with linear function test replacement, which rewrites the loop test so that the old counter often becomes dead.
In plain words
A loop that counts 0, 1, 2 and so on and multiplies the count by 4 each time does a multiply per trip. The products go up by 4 each time, so a second counter that starts at 0 and adds 4 gives the same numbers without the multiply. To find such counters, the method looks at which values feed which. A counter feeds itself around the loop through adds of fixed amounts, so it forms a closed cycle of values. The method finds each such cycle once, makes a new counter for each product, and points the product at it. When the loop test only compares the old counter with a limit, it compares the new counter with the limit times 4 instead. Then the old counter has no use left and goes away.
The problem
The input is a program of the toy IR of three-address code in strict SSA form. Every name has one definition, phi-functions stand at the tops of blocks, every use is dominated by its definition, no name is address-taken, every block is reachable, and the entry block has no predecessor. The output is a program in strict SSA form with the same outcome on every input, the same return value or the same trap, in which the products of induction variables and region constants are computed by adds.
The SSA graph has a node for each defined name and an edge from a name to each defined name that its definition reads. Let be a strongly connected component of it with more than one member, and let its header be the block of a member that comes first in reverse postorder. A region constant for is an integer, a parameter, or a name whose definition is in a block that strictly dominates . is an induction variable if dominates the blocks of all its members and every member is a phi-function, a copy, , or , with in and a region constant for . A candidate is an instruction , , , or with an induction variable and a region constant for its header.
The algorithm
The table maps a key to the name that holds . It is what makes two products of the same induction variable and constant share one new variable.
OSR(P)- 1
compute the dominator tree and a reverse postorder of the blocks of P - 2
for each SCC N of the SSA graph, in the order Tarjan's algorithm finds them, do - 3
if N has more than one member then ClassifyIV(N) - 4
else if the member n of N is a candidate x = iv op rc then Replace(n, iv, rc) - 5
else mark n as not an induction variable - 6
replace the tests of induction variables (linear function test replacement) - 7
delete the instructions that no effect, branch or return needs ClassifyIV(N)- 8
header <- the block of a member of N that comes first in reverse postorder - 9
if header dominates every member, and every member is a phi, a copy, iv + rc, rc + iv or iv - rc with iv in N and rc a region constant for header, then - 10
mark every member of N as an induction variable with this header - 11
else for each member n of N do - 12
if n is a candidate then Replace(n, iv, rc) else mark n as not an induction variable Replace(n, iv, rc)- 13
result <- Reduce(op, iv, rc) - 14
replace n by x = result and mark x as an induction variable with the header of iv Reduce(op, iv, rc)- 15
if (op, iv, rc) is in the table then return its entry - 16
result <- a new name; add (op, iv, rc) -> result to the table - 17
make a copy of the definition of iv that defines result - 18
for each operand o of the copy do - 19
if o is an induction variable with the header of iv then replace o by Reduce(op, o, rc) - 20
else if op is * or the copy is a phi then replace o by Apply(op, o, rc) - 21
insert the copy right after the definition of iv; mark result as an induction variable with the header of iv - 22
return result Apply(op, o1, o2)- 23
if (op, o1, o2) is in the table then return its entry - 24
if o1 is an induction variable and o2 is a region constant for its header then return Reduce(op, o1, o2) - 25
if op is commutative, o2 is an induction variable and o1 is a region constant for its header then return Reduce(op, o2, o1) - 26
if o1 and o2 are constants then return o1 op o2 - 27
result <- a new name; add (op, o1, o2) -> result to the table - 28
insert result = o1 op o2 at the end of the deeper of the blocks that define o1 and o2 - 29
return result
Tarjan's algorithm emits a component only after every component that it reaches, so the operands of a definition are classified before the definition itself (line L2). A product of an induction variable is then seen after the variable is known, and the new name of line L14 is an induction variable that later candidates can use, so (i * 4) + 5 becomes one new variable.
Line L19 follows the cycle: the copy of i2 = i + 1 for the key (*, i2, 4) reads the copy of i for (*, i, 4). Line L20 scales the other operands. For *, the step 1 becomes . For a phi-function, the start value 0 becomes . For + and - on the step of an add, the step stays the same. Line L28 puts the computations of new region constants where both operands are already known, which is outside the loop.
Line L6 looks at each comparison of an induction variable with a region constant . If has a reduction , the comparison becomes against , and the step repeats with . For + and - this is always valid. For * the pass uses only an integer , and for it swaps the sides of < and <=. Line L7 marks the names that terminators, stores, calls, loads, alloc and operations that may trap read, then the names their definitions read, and deletes the other constants, copies, phi-functions and operations. This removes the old counter when nothing else reads it, even though it reads itself around the loop.
Example
The parameters are k and n, and the program sums i * 4 + 5 for i from 0 to n - 1.
entry:
jump h
h:
i = phi [entry: 0, body: i2]
s = phi [entry: 0, body: s2]
c = i < n
br c body done
body:
x = i * 4
y = x + 5
s2 = s + y
i2 = i + 1
jump h
done:
ret s
Tarjan's algorithm finds the component with header h. Its members are a phi and i + 1, so it is an induction variable. The component is not one, because s2 = s + y adds y, which is defined in the loop. x = i * 4 is a candidate. Reduce copies the phi of i into osr1 = phi [entry: 0, body: osr2] with , and the add into osr2 = osr1 + 4 with , and x becomes x = osr1. Then y = x + 5 is a candidate on the new variable x. Reduce makes osr4 = phi [entry: 5, body: osr5] and osr5 = osr4 + 4, and y becomes a copy of it through osr3.
Line L6 rewrites c = i < n. The reduction (*, i, 4) turns it into osr1 < n * 4, and the reduction (+, osr1, 5) into osr4 < n * 4 + 5. Apply puts osr6 = n * 4 and osr7 = osr6 + 5 at the end of entry. Now i, i2, x, osr1 and osr2 have no needed use, and line L7 deletes them.
entry:
osr6 = n * 4
osr7 = osr6 + 5
jump h
h:
osr4 = phi [entry: 5, body: osr5]
s = phi [entry: 0, body: s2]
c = osr4 < osr7
br c body done
body:
osr3 = osr4
y = osr3
s2 = s + y
osr5 = osr4 + 4
jump h
done:
ret s
For both programs return 27. The loop has no multiply left. The one multiply in entry runs once. The copies osr3 and y stay. In the toy IR, where every instruction costs one step, the new program takes 35 steps against 33, because of the two instructions in entry. After copy propagation and dead code elimination remove the copies, the loop body has two instructions in place of four, and the run takes 29 steps. For it takes 78 steps against 96.
With x = i * -2 in place of x = i * 4 + 5, the test i < n becomes osr3 < osr1 with osr3 = n * -2, because multiplying both sides by a negative number reverses the order. With x = i * k, the test stays, because the sign of k is not known.
Correctness
The full proof is in the proof file. It assumes strict SSA form, unbounded integers, and that no pointer reaches an arithmetic operation.
- The new names are defined in time. A copy of Reduce stands right after the definition of its induction variable. A name of Apply stands at the end of a block that defines one operand and is dominated by the other. A short argument on dominators shows that both come before every point that reads them. So the output is in strict SSA form.
- The new names hold what their keys say. At every read of a name for the key , its value equals for the current values. The proof is by induction on the time of the read. For a copy of Reduce it uses the identities , and . Two facts on dominance show that the operands have not changed since the last definition.
- The rewritten instructions compute the same values. A replaced candidate reads a name that holds . A replaced test compares values that are both shifted by the same amount, or multiplied by the same nonzero integer, with the sides swapped if it is negative.
- The rest is the same. The new instructions cannot trap and define only new names, so the old and the new program visit the same blocks and take the same branches. The deletion removes only instructions that cannot trap and whose names no kept instruction reads.
So the new program returns the same value or traps in the same visit, on every input.
Proof: Operator strength reduction keeps the outcome of every runfull
Setting. is a program of the toy IR in strict SSA form, as the implementation checks: every name has one definition, phi-functions stand at the tops of blocks, every block is reachable, the entry block has no predecessor, no name is address-taken, and every use is dominated by its definition. For a phi operand from a predecessor , the definition must dominate . Integers are unbounded. We also assume that pointers never meet arithmetic: no name that an operation reads, and no name that flows into such a name through copies and phi-functions, ever holds a pointer. is the program that osr returns.
Claim. For every input, the run of visits the same blocks in the same order as the run of , and it ends with the same return value or the same trap, or it runs forever exactly when the run of does.
We write for the program just before the deletion of line L7. It is with three changes: new instructions inserted by lines L21 and L28, each candidate replaced by a copy at line L14, and some comparisons rewritten at line L6. We first show that behaves like , then that the deletion keeps the behavior.
Times and current values. A run is a sequence of steps. The phi-functions at the top of a block form one step: they read all their operands at the end of the predecessor, then assign. Every other instruction is one step. The current value of a name at a step is the value that its most recent earlier execution assigned. A point is a place where a name is read: an instruction, a terminator, or the end of a predecessor block for a phi operand.
Dominance in runs
Lemma 1. Let and be blocks with strictly dominating , and let dominate a block . In a run, if is visited and is visited later, then is visited after that visit of and no later than that visit of .
Proof. Every path from the entry to that passes passes before its first , because dominates . So the part of such a path up to its first does not contain . Join this part to the run from the visit of to the visit of . If that part of the run did not visit , the joined path would go from the entry to without , which is not possible.
Say that an instruction in block comes before a point in block if strictly dominates , or if and stands before in the block. The end of counts as a point after every instruction of .
Lemma 2 (freshness). Let come before a point , and let be an instruction that comes before . In a run, if executes and the run later reaches , then executes in between.
Proof. If and are in the same block, take the visit of that block in which executes. If is in the same visit, stands between and . Otherwise the run leaves the visit through its terminator, so every instruction after in the block executes, included. If is in a block that strictly dominates the block of , Lemma 1 gives a visit of after and no later than the visit of . If that visit is the visit of , stands before in it. Otherwise the run leaves it, so executes.
The usual consequence of strict SSA form follows from Lemma 2 with the first step of the run: every name is defined before it is read. The same holds for once we show it is in strict SSA form.
Where the new instructions stand
Write for the header of an induction variable and for the block that defines . A region constant for is an integer, a parameter, or a name with strictly dominating . Line L9 accepts a component only if dominates all its members. A name that line L14 marks is defined where the candidate was, and the candidate reads an induction variable, so dominates its block too. The same holds for the names of line L21, which stand next to the definition of an induction variable.
Lemma 3. is in strict SSA form, and each new instruction comes before every point that reads its name.
Proof. Names of line L28. is appended to the block of the deeper of the two definitions. Both definitions dominate the point where Apply is called, so they lie on one chain of the dominator tree, and is well defined. The parameters count as defined before the entry, so is the entry if both operands are parameters or integers. Apply is called from three places.
- For a phi operand from a predecessor . The operand is defined in a block that dominates . The region constant is defined in a block that strictly dominates . If is not dominated by , the phi is at itself, because every predecessor of a block other than that dominates is also dominated by . A path from the entry to that avoids the definition of the region constant continues to , so the definition dominates . If dominates , the definition dominates too, because it strictly dominates . So dominates , and the read at the end of comes after .
- For an operand of a copied operation, or for the new side of a comparison at line L6. Both operands are region constants for , so strictly dominates , and the reading point is in a block that dominates.
- A lookup in the table at line L23 returns a name made in one of these two ways, and the new reading point again falls in one of the two cases.
Names of line L21. The copy of the definition of is inserted right after it, or among the phi-functions right after it. Each operand of the copy is one of three things. It can be the result of Reduce for an operand of the definition, which stands right after the definition of and so comes before it. It can be a name of line L28, covered above. Or it can be an operand of the definition of that is kept as it is, which strict SSA form of already covers. Every point that reads reads it instead of or next to , so it comes after the definition of , and stands right after that definition.
The copies of line L14 read at the place of the candidate, which reads . If the candidate is in the block of , it stands after and so after .
The values of the new names
Every name made at lines L16 and L27 has a meaning. For a key in the table, the meaning of its name is . The integers and operands that Apply returns at line L26 and in the simplifications , , and satisfy the same identity on the spot.
Lemma 4. In every run of , at every step that reads a new name with meaning , the current value of equals the current value of combined by with the current value of .
Proof. By strong induction on the step of the read. Let be the step of the last execution of the definition of before . It exists by Lemma 3.
Names of line L28. At the instruction computed from the current values of and . Their definitions come before and comes before the reading point. If one of them ran again between and , Lemma 2 would run again before , against the choice of . So the operands have the same values at and at .
Names of line L21. Here has meaning with one of , and . Write for the value of . The definition of runs in the step just before , or in the same step for a phi. It is a phi, a copy, or an add or subtract with one region constant, because line L9 accepts only these, line L14 makes copies, and line L21 copies such definitions. The definition of is never changed after it is copied: a name with a header is never replaced at line L14, and line L6 changes only comparisons. We show that right after .
- . The copy is where is Reduce or Apply of . Coming from , both read at the end of , a step before , so by induction there, and .
- , a copy of an induction variable with the same header. Then with , and by induction .
- with in the component and a region constant, or the same with the sides swapped. The copy is with by induction. If is , then and . If is or , then and .
- with in the component and a region constant. The same identities give and .
Between and the value of does not change: its definition stands right before and cannot trap, so a new execution of it is followed by a new execution of in the same visit. The value of does not change either: its definition comes before , and Lemma 2 applies as for line L28. So at the identity still holds.
The rewritten instructions
Lemma 5. In every run of , every replaced candidate and every rewritten comparison computes the same value as the original instruction would compute at the same step.
Proof. A candidate became with , and Lemma 4 gives at that step.
A comparison with an induction variable and a region constant is rewritten in rounds. One round uses a reduction of and the name or value of Apply, and Lemma 4 holds for both at the step of the comparison. For equal to or , and agree for every in , , and , because adding the same integer to both sides keeps the order. For equal to , line L6 uses only an integer . For the order is kept. For it is reversed, so holds if and only if , the same for , and the sides are swapped. Equality and inequality do not depend on the sign. With on the left the argument is the same. Each round keeps the value, and is again a region constant for , so by induction on the rounds the final comparison computes the original value.
The same behavior
Lemma 6. behaves like on every input.
Proof. Run both in lock-step. They have the same blocks and the same terminators. By induction on the steps, the original names have the same current values in both. In a block, executes the original instructions in the original order, some of them rewritten, and new instructions in between. A new instruction defines only a new name. It is a phi, a copy, or , or on integers, so it cannot trap: its operands are integers by the assumption on pointers, and every name it reads is defined by Lemma 3. A rewritten instruction computes the same value by Lemma 5. Every other instruction reads the same values. So the branches go the same way, the stores, calls and loads see the same values, and the same trap or return happens at the same visit.
Lemma 7. The deletion at line L7 keeps the behavior.
Proof. Line L7 marks every name that a terminator, a store, a call, a load, an alloc or an operation that may trap reads, and then every name that the definition of a marked name reads. It deletes only constants, copies, phi-functions and operations that cannot trap whose names are not marked. A kept instruction reads only marked names, so their definitions are kept. Run and in lock-step. executes the kept instructions in the same order, and by induction they compute the same values. The deleted ones cannot trap and write no memory. So the branches and the outcome are the same.
Lemmas 6 and 7 together prove the claim. The run of visits the same blocks as the run of , so it ends exactly when the run of ends.
Integers that wrap. The identities of Lemma 4 hold modulo , so the rewrite of candidates is also correct for integers of bits that wrap. Lemma 5 for the order tests and is not: with wrapping, neither adding nor multiplying by keeps the order. A compiler for such integers must prove that no value in the new comparison wraps before it replaces such a test. Tests for equality and inequality through and stay correct, and through they need an odd or a proof that nothing wraps.
Complexity
The input has size , counting instructions and operands, in blocks, and the pass creates instructions. Dominators by the iterative algorithm of Cooper, Harvey and Kennedy take time in the worst case and close to on the graphs of real programs. Tarjan's algorithm takes . Each key enters the table once, so Reduce copies each definition at most once per key, and Apply does constant work besides the table. The implementation finds a definition by a scan of its block, which gives the term. With a map from names to positions, the work after the dominators is close to .
The number of new instructions is not bounded by a constant factor of . Each distinct pair used with an induction variable makes a copy of its whole component, so can grow as the number of candidates times the size of the components. The extra space is the table, the marks and the dominator tree.
Properties
- Sparse. It works on the SSA graph only. It needs dominators but no loop nesting tree and no data-flow sets.
- One pass in a good order. Tarjan's order classifies operands before their users, so chains such as
(i * 4) + 5reduce in one pass, and the results of Replace serve later candidates. - It shares work. The table maps equal keys to one name, as in global value numbering, so
i * 4in two places gives one new variable. - It needs cleanup. It leaves copies, and the old variables die only after test replacement. Copy propagation and dead code elimination finish the job.
- Recursive. Reduce calls itself around the cycle of a component and through Apply. The depth grows with the size of the component and the length of a chain of reductions.
Variants and improvements
- Allen, Cocke and Kennedy. The earlier algorithm works on strongly connected regions of the control flow graph, the loops, and finds induction variables and region constants by data-flow analysis. It handles the same candidates. Cooper, Simpson and Vick report that their SSA version gives the same results and is simpler to implement.
- Wider classes. Chains of recurrences describe polynomial and geometric sequences, so a product of two induction variables can also become adds, with a second order recurrence.
- Address computations. In practice the candidates are mostly array addresses such as
base + i * 8. A pass of loop-invariant code motion first moves invariant parts out of the loop, so they become region constants. - Test replacement with a computed limit. When the multiplier is not a known integer, a compiler can still replace a test of equality if it knows that , or a test of order if it knows the sign of .
When to use it
Use it in a compiler that keeps the program in SSA form and wants the classic loop strength reduction without a loop tree or data-flow sets. It is most useful for array addresses and for loops whose counter is used only in products and in the loop test. Run it after loop-invariant code motion, so that more operands are region constants, and before copy propagation and dead code elimination. Do not use it when the new variables would not fit in registers: each reduction adds a variable that is live around the loop.
Pitfalls
- Wrapping integers. The identities of the rewrite hold modulo , but test replacement with
<or<=does not:osr4 < n * 4 + 5can wrap wheni < ncannot. A compiler for fixed-width integers must prove that the new values do not wrap, or keep the old test. - Region constants defined in the header. A name defined in the header itself changes on each trip. The definition of a region constant must strictly dominate the header.
- Sums of two members.
i2 = i + iis in the component but is not an induction variable of the linear kind. ClassifyIV must check that exactly one operand of each add is in the component. - The sign of the multiplier. Test replacement through
x = i * kwithknot known must not change<. With every product is 0, and for the order reverses. - Traps. A candidate never traps, but
a / idoes wheniis 0. The pass must not touch it, and the cleanup must keep it, as an operation that may trap. - Placement of the new region constants. A product of two region constants that is put in the loop runs on every trip. Line L28 puts it in the deeper of the defining blocks, which dominates the header.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/operator-strength-reduction/. The authors are listed in prov/VGSWKK.jsonl.
"""Operator strength reduction on SSA form (Cooper, Simpson and Vick) for
the toy IR.
osr(prog) takes a program in strict SSA form: every name has one
definition, phi-functions stand at the tops of blocks, every use is
dominated by its definition, no name is address-taken, every block is
reachable and the entry block has no predecessor. It returns a new
program in which every candidate
x = iv * rc, x = rc * iv, x = iv + rc, x = rc + iv, x = iv - rc
is a copy of a new induction variable that the loop updates by adds. iv is
an induction variable: a member of a strongly connected component (SCC) of
the SSA graph made only of phis, copies and adds or subtracts of region
constants. rc is a region constant for the loop: an integer, a parameter,
or a name whose definition lies in a block that strictly dominates the
header of the SCC.
After the reduction the pass rewrites comparisons of an induction variable
with a region constant into comparisons of a reduced one (linear function
test replacement), and deletes the instructions that no effect, branch or
return needs.
The toy IR has unbounded integers, so the identities that the rewrite uses
hold exactly. With fixed-width integers that wrap, the rewrite of the
candidates is still correct, but replacing a test with < or <= needs a
proof that no value in the new test wraps.
"""
import toyir
COMMUTATIVE = ("+", "*")
COMPARE = ("<", "<=", "==", "!=")
def may_trap(ins):
"""True if the operation can trap in the toy IR."""
if ins[0] != "op":
return False
op, b = ins[2], ins[4]
if op in ("/", "%"):
return not (isinstance(b, int) and b != 0)
if op in ("<<", ">>"):
return not (isinstance(b, int) and 0 <= b <= 63)
return False
def _copy_program(prog):
blocks = {}
for label, blk in prog.blocks.items():
instrs = [(ins[0], ins[1], dict(ins[2])) if ins[0] == "phi" else ins for ins in blk.instrs]
blocks[label] = toyir.Block(instrs, blk.term)
return toyir.Program(list(prog.params), blocks)
class Dominators:
"""Immediate dominators by the iterative algorithm of Cooper, Harvey and
Kennedy, with a reverse postorder of the blocks."""
def __init__(self, prog):
order, seen = [], {prog.entry}
stack = [(prog.entry, iter(toyir.succs(prog, prog.entry)))]
while stack:
v, it = stack[-1]
w = next(it, None)
if w is None:
order.append(v)
stack.pop()
elif w not in seen:
seen.add(w)
stack.append((w, iter(toyir.succs(prog, w))))
missing = [b for b in prog.blocks if b not in seen]
if missing:
raise ValueError("block %r is unreachable" % missing[0])
self.rpo = order[::-1]
self.num = {b: i for i, b in enumerate(self.rpo)}
post = {b: i for i, b in enumerate(order)}
preds = toyir.preds(prog)
idom = {prog.entry: prog.entry}
def intersect(a, b):
while a != b:
while post[a] < post[b]:
a = idom[a]
while post[b] < post[a]:
b = idom[b]
return a
changed = True
while changed:
changed = False
for v in self.rpo[1:]:
new = None
for p in preds[v]:
if p in idom:
new = p if new is None else intersect(p, new)
if idom.get(v) != new:
idom[v] = new
changed = True
self.idom = idom
self.depth = {}
for v in self.rpo:
self.depth[v] = 0 if v == prog.entry else self.depth[idom[v]] + 1
def dominates(self, a, b):
"""True if block a dominates block b. None stands for the place
before the entry, where the parameters are defined."""
if a is None:
return True
if b is None:
return False
while self.depth[b] > self.depth[a]:
b = self.idom[b]
return a == b
def check_ssa(prog):
"""Raise ValueError unless prog is in strict SSA form with no
address-taken names. Returns the Dominators and the defining block of
each name (None for a parameter)."""
dom = Dominators(prog)
where = {p: None for p in prog.params}
pos = {}
for label, blk in prog.blocks.items():
seen_other = False
for i, ins in enumerate(blk.instrs):
if ins[0] == "addr":
raise ValueError("SSA names may not be address-taken: %s" % ins[2])
if ins[0] == "phi":
if seen_other:
raise ValueError("phi after a non-phi instruction in %r" % label)
else:
seen_other = True
x = toyir.defs(ins)
if x is None:
continue
if x in where:
raise ValueError("name %r has two definitions" % x)
where[x] = label
pos[x] = i
preds = toyir.preds(prog)
if preds[prog.entry]:
raise ValueError("the entry block has a predecessor")
def check(a, label, i):
if a not in where:
raise ValueError("name %r is never defined" % a)
d = where[a]
if d == label and i is not None and pos[a] >= i:
raise ValueError("use of %r before its definition in %r" % (a, label))
if not dom.dominates(d, label):
raise ValueError("use of %r in %r is not dominated by its definition" % (a, label))
for label, blk in prog.blocks.items():
for i, ins in enumerate(blk.instrs):
if ins[0] == "phi":
if set(ins[2]) != set(preds[label]):
raise ValueError("phi %s does not match the predecessors of %r" % (ins[1], label))
for p, a in ins[2].items():
if isinstance(a, str):
check(a, p, None)
else:
for a in toyir.uses(ins):
check(a, label, i)
for a in toyir.term_uses(blk.term):
check(a, label, None)
return dom, where
def ssa_sccs(prog, where):
"""The SCCs of the SSA graph by Tarjan's algorithm, without recursion.
A node is a defined name, and its edges go to the defined names that its
definition reads. An SCC comes out after every SCC it can reach, so the
operands of a definition are always handled before it."""
defn = {}
for blk in prog.blocks.values():
for ins in blk.instrs:
x = toyir.defs(ins)
if x is not None:
defn[x] = ins
succ = {x: [a for a in toyir.uses(ins) if where.get(a) is not None] for x, ins in defn.items()}
index, low, on, st, out = {}, {}, set(), [], []
counter = 0
for root in defn:
if root in index:
continue
index[root] = low[root] = counter
counter += 1
st.append(root)
on.add(root)
work = [(root, iter(succ[root]))]
while work:
v, it = work[-1]
w = next(it, None)
if w is not None:
if w not in index:
index[w] = low[w] = counter
counter += 1
st.append(w)
on.add(w)
work.append((w, iter(succ[w])))
elif w in on:
low[v] = min(low[v], index[w])
continue
work.pop()
if work:
u = work[-1][0]
low[u] = min(low[u], low[v])
if low[v] == index[v]:
comp = []
while True:
w = st.pop()
on.discard(w)
comp.append(w)
if w == v:
break
out.append(comp)
return out
class OSR:
def __init__(self, prog):
self.dom, self.where = check_ssa(prog)
self.prog = _copy_program(prog)
self.header = {} # name -> header block of its induction variable, or None
self.table = {} # (op, o1, o2) -> name or int
self.red = {} # induction variable -> list of (op, rc, reduced name)
self.used = set(self.where)
self.counter = 0
self.replaced = 0
self.tests = 0
# ----------------------------------------------------------- helpers
def fresh(self):
while True:
self.counter += 1
name = "osr%d" % self.counter
if name not in self.used:
self.used.add(name)
return name
def find(self, x):
label = self.where[x]
for i, ins in enumerate(self.prog.blocks[label].instrs):
if toyir.defs(ins) == x:
return label, i
raise KeyError(x)
def definition(self, x):
label, i = self.find(x)
return self.prog.blocks[label].instrs[i]
def is_iv(self, o):
return isinstance(o, str) and self.header.get(o) is not None
def is_rc(self, o, h):
"""o is a region constant for the loop with header h."""
if isinstance(o, int):
return True
d = self.where[o]
return d is None or (d != h and self.dom.dominates(d, h))
def candidate(self, ins):
if ins[0] != "op" or ins[2] not in ("*", "+", "-"):
return None
op, a, b = ins[2], ins[3], ins[4]
if self.is_iv(a) and self.is_rc(b, self.header[a]):
return op, a, b
if op in COMMUTATIVE and self.is_iv(b) and self.is_rc(a, self.header[b]):
return op, b, a
return None
# ------------------------------------------------------- the algorithm
def run(self):
for comp in ssa_sccs(self.prog, self.where): # @line L2
if len(comp) > 1: # @line L3
self.classify(comp)
else:
n = comp[0]
c = self.candidate(self.definition(n))
if c is not None: # @line L4
self.replace(n, *c)
else:
self.header[n] = None # @line L5
self.replace_tests() # @line L6
self.dead_code() # @line L7
return self.prog
def classify(self, comp):
members = set(comp)
h = min((self.where[n] for n in comp), key=self.dom.num.__getitem__) # @line L8
ok = True
for n in comp:
ins = self.definition(n)
if not self.dom.dominates(h, self.where[n]):
ok = False
elif ins[0] == "phi":
ok = ok and all(o in members or self.is_rc(o, h) for o in ins[2].values())
elif ins[0] == "copy":
ok = ok and ins[2] in members
elif ins[0] == "op" and ins[2] in ("+", "-"):
a, b = ins[3], ins[4]
left = a in members and b not in members and self.is_rc(b, h)
right = ins[2] == "+" and b in members and a not in members and self.is_rc(a, h)
ok = ok and (left or right)
else:
ok = False
if ok: # @line L9
for n in comp:
self.header[n] = h # @line L10
return
for n in comp: # @line L11
self.header[n] = None
for n in comp:
c = self.candidate(self.definition(n))
if c is not None: # @line L12
self.replace(n, *c)
def replace(self, n, op, iv, rc):
result = self.reduce(op, iv, rc) # @line L13
label, i = self.find(n)
self.prog.blocks[label].instrs[i] = ("copy", n, result) # @line L14
self.header[n] = self.header[iv]
self.replaced += 1
def reduce(self, op, iv, rc):
key = (op, iv, rc)
if key in self.table: # @line L15
return self.table[key]
result = self.fresh() # @line L16
self.table[key] = result
h = self.header[iv]
self.header[result] = h
self.red.setdefault(iv, []).append((op, rc, result))
ins = self.definition(iv) # @line L17
is_phi = ins[0] == "phi"
def operand(o): # @line L18
if isinstance(o, str) and self.header.get(o) == h:
return self.reduce(op, o, rc) # @line L19
if op == "*" or is_phi:
return self.apply(op, o, rc) # @line L20
return o
if is_phi:
new = ("phi", result, {p: operand(o) for p, o in ins[2].items()})
elif ins[0] == "copy":
new = ("copy", result, operand(ins[2]))
else:
new = ("op", result, ins[2], operand(ins[3]), operand(ins[4]))
label, i = self.find(iv)
self.prog.blocks[label].instrs.insert(i + 1, new) # @line L21
self.where[result] = label
return result # @line L22
def apply(self, op, o1, o2):
for key in [(op, o1, o2)] + ([(op, o2, o1)] if op in COMMUTATIVE else []):
if key in self.table: # @line L23
return self.table[key]
if self.is_iv(o1) and self.is_rc(o2, self.header[o1]): # @line L24
return self.reduce(op, o1, o2)
if op in COMMUTATIVE and self.is_iv(o2) and self.is_rc(o1, self.header[o2]): # @line L25
return self.reduce(op, o2, o1)
if isinstance(o1, int) and isinstance(o2, int): # @line L26
return toyir._binop(op, o1, o2)
if op == "*" and (o1 == 0 or o2 == 0):
return 0
if (op == "*" and o1 == 1) or (op == "+" and o1 == 0):
return o2
if (op == "*" and o2 == 1) or (op in ("+", "-") and o2 == 0):
return o1
result = self.fresh() # @line L27
self.table[(op, o1, o2)] = result
blocks = [self.where[o] for o in (o1, o2) if isinstance(o, str)]
d = blocks[0]
for b in blocks[1:]:
if self.dom.dominates(d, b):
d = b
elif not self.dom.dominates(b, d):
raise AssertionError("the operands of a region constant are not on one dominator chain")
if d is None:
d = self.prog.entry
self.prog.blocks[d].instrs.append(("op", result, op, o1, o2)) # @line L28
self.where[result] = d
self.header[result] = None
return result # @line L29
# ------------------------------------------ test replacement and cleanup
def replace_tests(self):
"""Linear function test replacement: in x = a cmp b with a an
induction variable and b a region constant for its header, follow
the reductions of a while one keeps the comparison the same."""
for label in list(self.prog.blocks):
instrs = self.prog.blocks[label].instrs
for i in range(len(instrs)):
ins = instrs[i]
if ins[0] != "op" or ins[2] not in COMPARE:
continue
x, cmp, a, b = ins[1], ins[2], ins[3], ins[4]
changed = False
while True:
if self.is_iv(a) and self.is_rc(b, self.header[a]):
iv, other, iv_left = a, b, True
elif self.is_iv(b) and self.is_rc(a, self.header[b]):
iv, other, iv_left = b, a, False
else:
break
step = None
for op, rc, r in self.red.get(iv, []):
if op in ("+", "-"):
step = (op, rc, r, False)
break
if op == "*" and isinstance(rc, int) and rc != 0:
step = (op, rc, r, rc < 0 and cmp in ("<", "<="))
break
if step is None:
break
op, rc, r, swap = step
o = self.apply(op, other, rc)
a, b = (r, o) if iv_left else (o, r)
if swap:
a, b = b, a
changed = True
if changed:
instrs[i] = ("op", x, cmp, a, b)
self.tests += 1
def dead_code(self):
"""Delete the phis, copies, constants and operations that cannot trap
and that nothing needed reads. Marking from the needed statements
also removes dead cycles, such as an induction variable that only
its own update reads."""
def removable(ins):
return ins[0] in ("const", "copy", "phi") or (ins[0] == "op" and not may_trap(ins))
defn = {}
live, work = set(), []
for blk in self.prog.blocks.values():
for ins in blk.instrs:
x = toyir.defs(ins)
if x is not None:
defn[x] = ins
if not removable(ins):
work.extend(toyir.uses(ins))
work.extend(toyir.term_uses(blk.term))
while work:
x = work.pop()
if x in live or x not in defn:
continue
live.add(x)
work.extend(toyir.uses(defn[x]))
for blk in self.prog.blocks.values():
blk.instrs = [ins for ins in blk.instrs if not removable(ins) or ins[1] in live]
def osr(prog, stats=None):
"""Operator strength reduction. Returns a new program. If stats is a
dict, it receives the number of replaced candidates and replaced
tests."""
o = OSR(prog) # @line L1
out = o.run()
if stats is not None:
stats["replaced"] = o.replaced
stats["tests"] = o.tests
return out
toyir.py 602 lines
# SPDX-License-Identifier: MIT
# Shared helper of the compilers and program analysis pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""The toy IR: three-address code in basic blocks.
A program is Program(params, blocks). blocks is a dict from label to
Block(instrs, term), kept in insertion order, and the first label is the
entry. Instructions are tuples:
("const", x, k) x = k
("copy", x, a) x = y
("op", x, op, a, b) x = a op b
("phi", x, {pred: a}) x = phi [pred: a, ...]
("addr", p, x) p = &x
("load", x, p) x = *p
("store", p, a) *p = a
("alloc", p) p = alloc
("call", x, f, args) x = call f(a, b) (args is a list)
Terminators are ("jump", L), ("br", a, L1, L2) and ("ret", a). An operand a
is a str (a name) or an int. The text form of a copy of an int is the text
form of a constant, so parse always gives ("const", x, k) for "x = k".
"""
from dataclasses import dataclass, field
import re
OPS = ("+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "<", "<=", "==", "!=")
@dataclass
class Block:
instrs: list = field(default_factory=list)
term: tuple = ("ret", 0)
@dataclass
class Program:
params: list
blocks: dict
@property
def entry(self):
return next(iter(self.blocks))
class UndefinedName(Exception):
"""A name was read before any definition."""
# ---------------------------------------------------------------- text form
_NAME = r"[A-Za-z_][A-Za-z0-9_.]*"
_INT = r"-?[0-9]+"
def _operand(tok):
if re.fullmatch(_INT, tok):
return int(tok)
if re.fullmatch(_NAME, tok):
return tok
raise ValueError("bad operand: %r" % tok)
def _name(tok):
if not re.fullmatch(_NAME, tok):
raise ValueError("bad name: %r" % tok)
return tok
def _parse_instr(line):
toks = line.split()
if toks[0] == "jump" and len(toks) == 2:
return "term", ("jump", _name(toks[1]))
if toks[0] == "br" and len(toks) == 4:
return "term", ("br", _operand(toks[1]), _name(toks[2]), _name(toks[3]))
if toks[0] == "ret" and len(toks) == 2:
return "term", ("ret", _operand(toks[1]))
lhs, eq, rhs = line.partition("=")
if not eq:
raise ValueError("bad line: %r" % line)
lhs, rhs = lhs.strip(), rhs.strip()
if lhs.startswith("*"):
return "instr", ("store", _name(lhs[1:].strip()), _operand(rhs))
x = _name(lhs)
if rhs.startswith("phi"):
body = rhs[3:].strip()
if not (body.startswith("[") and body.endswith("]")):
raise ValueError("bad phi: %r" % line)
args = {}
inner = body[1:-1].strip()
if inner:
for part in inner.split(","):
pred, colon, a = part.partition(":")
if not colon:
raise ValueError("bad phi: %r" % line)
args[_name(pred.strip())] = _operand(a.strip())
return "instr", ("phi", x, args)
if rhs.startswith("call "):
m = re.fullmatch(r"call\s+(" + _NAME + r")\s*\((.*)\)", rhs)
if not m:
raise ValueError("bad call: %r" % line)
inner = m.group(2).strip()
args = [_operand(a.strip()) for a in inner.split(",")] if inner else []
return "instr", ("call", x, m.group(1), args)
if rhs == "alloc":
return "instr", ("alloc", x)
if rhs.startswith("&"):
return "instr", ("addr", x, _name(rhs[1:].strip()))
if rhs.startswith("*"):
return "instr", ("load", x, _name(rhs[1:].strip()))
parts = rhs.split()
if len(parts) == 1:
a = _operand(parts[0])
if isinstance(a, int):
return "instr", ("const", x, a)
return "instr", ("copy", x, a)
if len(parts) == 3 and parts[1] in OPS:
return "instr", ("op", x, parts[1], _operand(parts[0]), _operand(parts[2]))
raise ValueError("bad instruction: %r" % line)
def parse(text):
"""Parse the text form. A line "# params: a, b" gives the parameters;
without it, the parameters are the names that are read and never
defined, in the order of their first use."""
params = None
blocks = {}
cur = None
for raw in text.splitlines():
line = raw.strip()
if not line:
continue
if line.startswith("#"):
m = re.fullmatch(r"#\s*params:(.*)", line)
if m:
inner = m.group(1).strip()
params = [_name(p.strip()) for p in inner.split(",")] if inner else []
continue
if line.endswith(":") and re.fullmatch(_NAME, line[:-1]):
label = line[:-1]
if label in blocks:
raise ValueError("duplicate label: %r" % label)
cur = label
blocks[label] = Block([], None)
continue
if cur is None:
raise ValueError("instruction outside a block: %r" % line)
if blocks[cur].term is not None:
raise ValueError("instruction after the terminator in %r" % cur)
kind, item = _parse_instr(line)
if kind == "term":
blocks[cur].term = item
else:
blocks[cur].instrs.append(item)
for label, b in blocks.items():
if b.term is None:
raise ValueError("block %r has no terminator" % label)
if not blocks:
raise ValueError("empty program")
prog = Program([], blocks)
if params is None:
params = _free_names(prog)
prog.params = params
return prog
def _free_names(prog):
defined = set()
for b in prog.blocks.values():
for ins in b.instrs:
d = defs(ins)
if d is not None:
defined.add(d)
out = []
for b in prog.blocks.values():
for ins in b.instrs:
for a in uses(ins):
if a not in defined and a not in out:
out.append(a)
for a in term_uses(b.term):
if a not in defined and a not in out:
out.append(a)
return out
def _show_instr(ins):
k = ins[0]
if k == "const":
return "%s = %d" % (ins[1], ins[2])
if k == "copy":
return "%s = %s" % (ins[1], ins[2])
if k == "op":
return "%s = %s %s %s" % (ins[1], ins[3], ins[2], ins[4])
if k == "phi":
return "%s = phi [%s]" % (ins[1], ", ".join("%s: %s" % (p, a) for p, a in ins[2].items()))
if k == "addr":
return "%s = &%s" % (ins[1], ins[2])
if k == "load":
return "%s = *%s" % (ins[1], ins[2])
if k == "store":
return "*%s = %s" % (ins[1], ins[2])
if k == "alloc":
return "%s = alloc" % ins[1]
if k == "call":
return "%s = call %s(%s)" % (ins[1], ins[2], ", ".join(str(a) for a in ins[3]))
raise ValueError("bad instruction: %r" % (ins,))
def _show_term(t):
if t[0] == "jump":
return "jump %s" % t[1]
if t[0] == "br":
return "br %s %s %s" % (t[1], t[2], t[3])
if t[0] == "ret":
return "ret %s" % (t[1],)
raise ValueError("bad terminator: %r" % (t,))
def show(prog):
lines = ["# params: " + ", ".join(prog.params)]
for label, b in prog.blocks.items():
lines.append(label + ":")
for ins in b.instrs:
lines.append(" " + _show_instr(ins))
lines.append(" " + _show_term(b.term))
return "\n".join(lines) + "\n"
# ---------------------------------------------------------- names and graph
def defs(ins):
"""The name an instruction defines, or None for a store."""
return None if ins[0] == "store" else ins[1]
def uses(ins):
"""The names an instruction reads, in order (phi operands included)."""
k = ins[0]
if k == "const" or k == "alloc" or k == "addr":
ops = []
elif k == "copy":
ops = [ins[2]]
elif k == "op":
ops = [ins[3], ins[4]]
elif k == "phi":
ops = list(ins[2].values())
elif k == "load":
ops = [ins[2]]
elif k == "store":
ops = [ins[1], ins[2]]
elif k == "call":
ops = list(ins[3])
else:
raise ValueError("bad instruction: %r" % (ins,))
return [a for a in ops if isinstance(a, str)]
def term_uses(t):
if t[0] == "br" or t[0] == "ret":
return [t[1]] if isinstance(t[1], str) else []
return []
def succs(prog, label):
"""Successor labels of a block, without repeats, in terminator order."""
t = prog.blocks[label].term
if t[0] == "jump":
return [t[1]]
if t[0] == "br":
return [t[2]] if t[2] == t[3] else [t[2], t[3]]
return []
def edges(prog):
return [(a, b) for a in prog.blocks for b in succs(prog, a)]
def preds(prog):
"""Dict from label to the list of predecessor labels, in block order."""
out = {label: [] for label in prog.blocks}
for a, b in edges(prog):
out[b].append(a)
return out
def is_acyclic(prog):
color = {label: 0 for label in prog.blocks}
for root in prog.blocks:
if color[root]:
continue
color[root] = 1
stack = [(root, iter(succs(prog, root)))]
while stack:
v, it = stack[-1]
w = next(it, None)
if w is None:
color[v] = 2
stack.pop()
elif color[w] == 1:
return False
elif color[w] == 0:
color[w] = 1
stack.append((w, iter(succs(prog, w))))
return True
def paths(prog):
"""Every path from the entry to a ret block, as a list of labels.
The CFG must be acyclic."""
if not is_acyclic(prog):
raise ValueError("paths needs an acyclic CFG")
out = []
def walk(path):
last = path[-1]
s = succs(prog, last)
if not s:
out.append(list(path))
for w in s:
path.append(w)
walk(path)
path.pop()
walk([prog.entry])
return out
# ------------------------------------------------------------------ running
class _Trap(Exception):
pass
class _Fuel(Exception):
pass
def _binop(op, a, b):
if not isinstance(a, int) or not isinstance(b, int):
raise TypeError("arithmetic on a pointer")
if op == "+":
return a + b
if op == "-":
return a - b
if op == "*":
return a * b
if op == "/" or op == "%":
if b == 0:
raise _Trap()
q = abs(a) // abs(b)
if (a < 0) != (b < 0):
q = -q
return q if op == "/" else a - b * q
if op == "&":
return a & b
if op == "|":
return a | b
if op == "^":
return a ^ b
if op == "<<" or op == ">>":
if b < 0 or b > 63:
raise _Trap()
return a << b if op == "<<" else a >> b
if op == "<":
return int(a < b)
if op == "<=":
return int(a <= b)
if op == "==":
return int(a == b)
if op == "!=":
return int(a != b)
raise ValueError("bad operator: %r" % op)
class _Frame:
"""One activation: its program, its variables and its position."""
def __init__(self, prog, args, fid):
if len(args) != len(prog.params):
raise ValueError("expected %d arguments" % len(prog.params))
self.prog = prog
self.env = dict(zip(prog.params, args))
self.fid = fid
self.label = prog.entry
self.prev = None
self.pc = 0 # 0 means: the phis of the block have not run yet
self.dest = None # the name that receives the value of a pending call
def val(self, a):
if isinstance(a, int):
return a
if a not in self.env:
raise UndefinedName(a)
return self.env[a]
def _run(prog, args, fuel, funcs):
"""Run with an explicit stack of frames, so deep recursion in the toy
program does not use Python recursion."""
heap = {}
envs = {}
stack = []
fr = _Frame(prog, args, 0)
envs[0] = fr.env
nframes = 1
def tick():
nonlocal fuel
if fuel <= 0:
raise _Fuel()
fuel -= 1
while True:
block = fr.prog.blocks[fr.label]
instrs = block.instrs
if fr.pc == 0:
# Phis at the top of the block read all operands first, then assign.
incoming = []
i = 0
while i < len(instrs) and instrs[i][0] == "phi":
tick()
ins = instrs[i]
if fr.prev not in ins[2]:
raise ValueError("phi %s has no operand for %r" % (ins[1], fr.prev))
incoming.append((ins[1], fr.val(ins[2][fr.prev])))
i += 1
for x, v in incoming:
fr.env[x] = v
fr.pc = i if i > 0 else -1
start = fr.pc if fr.pc > 0 else 0
called = False
env = fr.env
for j in range(start, len(instrs)):
ins = instrs[j]
tick()
k = ins[0]
if k == "const":
env[ins[1]] = ins[2]
elif k == "copy":
env[ins[1]] = fr.val(ins[2])
elif k == "op":
env[ins[1]] = _binop(ins[2], fr.val(ins[3]), fr.val(ins[4]))
elif k == "addr":
env[ins[1]] = ("var", fr.fid, ins[2])
elif k == "alloc":
cell = ("heap", len(heap))
heap[cell] = None
env[ins[1]] = cell
elif k == "load":
p = fr.val(ins[2])
if p[0] == "var":
if p[2] not in envs[p[1]]:
raise UndefinedName(p[2])
env[ins[1]] = envs[p[1]][p[2]]
else:
if heap[p] is None:
raise UndefinedName(repr(p))
env[ins[1]] = heap[p]
elif k == "store":
p = fr.val(ins[1])
if p[0] == "var":
envs[p[1]][p[2]] = fr.val(ins[2])
else:
heap[p] = fr.val(ins[2])
elif k == "call":
if funcs is None or ins[2] not in funcs:
raise ValueError("unknown function %r" % ins[2])
vals = [fr.val(a) for a in ins[3]]
fr.pc = j + 1
fr.dest = ins[1]
stack.append(fr)
fr = _Frame(funcs[ins[2]], vals, nframes)
envs[nframes] = fr.env
nframes += 1
called = True
break
elif k == "phi":
raise ValueError("phi after a non-phi instruction")
else:
raise ValueError("bad instruction: %r" % (ins,))
if called:
continue
tick()
t = block.term
if t[0] == "jump" or t[0] == "br":
if t[0] == "jump":
nxt = t[1]
else:
nxt = t[2] if fr.val(t[1]) != 0 else t[3]
fr.prev, fr.label, fr.pc = fr.label, nxt, 0
continue
v = fr.val(t[1])
if not stack:
return ("ret", v), fuel
fr = stack.pop()
fr.env[fr.dest] = v
def run(prog, args, fuel=10000, funcs=None):
"""Run prog on args. Returns ("ret", v), ("trap",) or ("fuel",).
Each instruction, phi and terminator uses one unit of fuel. funcs is an
optional dict from function name to Program, used by call; deep
recursion in the toy program is fine, because the frames are kept on an
explicit stack."""
try:
out, _ = _run(prog, list(args), fuel, funcs)
return out
except _Trap:
return ("trap",)
except _Fuel:
return ("fuel",)
# ------------------------------------------------------------ random programs
_SAFE = ("+", "-", "*", "&", "|", "^", "<", "<=", "==", "!=")
_CONST_RIGHT = ("/", "%", "<<", ">>")
def random_program(rng, nvars, nblocks, acyclic):
"""A random program with blocks B0 .. B(nblocks-1) and variables
x0 .. x(nvars-1). x0 and x1 are the parameters; the entry defines the
others, so no run reads an undefined name. A division by a variable can
trap. Every block is reachable from
B0 and B0 has no predecessor. With acyclic=False, each loop has its own
counter c that is set to 0 in B0 and never reset, and the back edge is
taken only while c < m and c < 4, where m is the first parameter. So the
whole run takes each back edge at most 3 times."""
nvars = max(nvars, 1)
nblocks = max(nblocks, 1)
xs = ["x%d" % i for i in range(nvars)]
params = xs[:2]
labels = ["B%d" % i for i in range(nblocks)]
def operand():
if rng.random() < 0.25:
return rng.randint(-3, 9)
return rng.choice(xs)
def instr():
x = rng.choice(xs)
r = rng.random()
if r < 0.15:
return ("const", x, rng.randint(-5, 9))
if r < 0.25:
return ("copy", x, rng.choice(xs))
if r < 0.3:
# A division by a variable may trap.
return ("op", x, rng.choice(("/", "%")), rng.choice(xs), rng.choice(xs))
if r < 0.4:
op = rng.choice(_CONST_RIGHT)
k = rng.randint(1, 5)
return ("op", x, op, rng.choice(xs), k)
return ("op", x, rng.choice(_SAFE), operand(), operand())
blocks = {}
has_pred = [False] * nblocks
has_pred[0] = True
for i in range(nblocks):
instrs = [instr() for _ in range(rng.randint(1, 3))]
if i == 0:
instrs = [("const", x, rng.randint(-5, 9)) for x in xs[len(params):]] + instrs
if i == nblocks - 1:
term = ("ret", rng.choice(xs))
elif has_pred[i + 1] and rng.random() < 0.2:
term = ("ret", rng.choice(xs))
else:
first = i + 1 if not has_pred[i + 1] else rng.randrange(i + 1, nblocks)
if rng.random() < 0.5:
term = ("jump", labels[first])
has_pred[first] = True
else:
second = rng.randrange(i + 1, nblocks)
if second == first:
term = ("jump", labels[first])
else:
term = ("br", rng.choice(xs), labels[first], labels[second])
has_pred[second] = True
has_pred[first] = True
blocks[labels[i]] = Block(instrs, term)
if not acyclic and nblocks > 1:
nloops = rng.randint(1, max(1, nblocks // 3))
for k in range(nloops):
latches = [lab for lab in labels[1:] if blocks[lab].term[0] == "jump"]
if not latches:
break
t = rng.choice(latches)
h = labels[rng.randint(1, labels.index(t))]
c, m, w1, w2, w = "c%d" % k, "m%d" % k, "t%d" % k, "u%d" % k, "w%d" % k
blocks[labels[0]].instrs[0:0] = [("const", c, 0), ("copy", m, params[0])]
out = blocks[t].term[1]
blocks[t].instrs += [
("op", c, "+", c, 1),
("op", w1, "<", c, m),
("op", w2, "<", c, 4),
("op", w, "&", w1, w2),
]
blocks[t].term = ("br", w, h, out)
return Program(list(params), blocks)
test_operator_strength_reduction.py 409 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/operator-strength-reduction/. The authors are listed in prov/VGSWKK.jsonl.
import random
import pytest
import toyir
from operator_strength_reduction import check_ssa, osr
PAGE = """
# params: k, n
entry:
jump h
h:
i = phi [entry: 0, body: i2]
s = phi [entry: 0, body: s2]
c = i < n
br c body done
body:
x = i * 4
y = x + 5
s2 = s + y
i2 = i + 1
jump h
done:
ret s
"""
PAGE_OUT = """
# params: k, n
entry:
osr6 = n * 4
osr7 = osr6 + 5
jump h
h:
osr4 = phi [entry: 5, body: osr5]
s = phi [entry: 0, body: s2]
c = osr4 < osr7
br c body done
body:
osr3 = osr4
y = osr3
s2 = s + y
osr5 = osr4 + 4
jump h
done:
ret s
"""
FUNC_F = toyir.parse("# params: u\nentry:\n v = u * 3\n w = v - 1\n ret w\n")
FUNCS = {"f": FUNC_F}
def kinds(prog, kind):
return [ins for blk in prog.blocks.values() for ins in blk.instrs if ins[0] == kind]
def ops(prog, op):
return [ins for ins in kinds(prog, "op") if ins[2] == op]
def same(p, q, args, funcs=None, fuel=20000):
a = toyir.run(p, args, fuel, funcs)
b = toyir.run(q, args, fuel, funcs)
assert a[0] != "fuel"
assert a == b, (args, a, b, toyir.show(p), toyir.show(q))
return a
def test_page_example():
p = toyir.parse(PAGE)
st = {}
q = osr(p, st)
assert toyir.show(q) == toyir.show(toyir.parse(PAGE_OUT))
assert st == {"replaced": 2, "tests": 1}
assert ops(q, "*") == [("op", "osr6", "*", "n", 4)]
for n in range(-3, 9):
same(p, q, [7, n])
assert toyir.run(q, [0, 3]) == ("ret", 27)
def test_input_is_not_changed():
p = toyir.parse(PAGE)
before = toyir.show(p)
osr(p)
assert toyir.show(p) == before
def test_stores_and_calls_are_kept():
p = toyir.parse("""
# params: n
entry:
m = alloc
*m = 0
jump h
h:
i = phi [entry: 1, body: i2]
c = i <= n
br c body done
body:
x = i * 5
*m = x
r = call f(x)
i2 = i + r
jump h
done:
v = *m
ret v
""")
q = osr(p)
assert len(kinds(q, "store")) == 2
assert len(kinds(q, "call")) == 1
assert len(kinds(q, "load")) == 1
assert len(kinds(q, "alloc")) == 1
for n in range(-2, 40):
same(p, q, [n], FUNCS)
def test_no_trap_is_added_or_removed():
p = toyir.parse("""
# params: a, n
entry:
jump h
h:
i = phi [entry: -2, body: i2]
c = i < n
br c body done
body:
d = a / i
x = i * 3
y = d + x
i2 = i + 1
jump h
done:
ret i
""")
q = osr(p)
assert ops(q, "/") == [("op", "d", "/", "a", "i")]
outs = {same(p, q, [a, n])[0] for a in range(-3, 4) for n in range(-4, 4)}
assert outs == {"ret", "trap"}
def test_negative_multiplier_swaps_the_test():
p = toyir.parse("""
# params: n
entry:
jump h
h:
i = phi [entry: 0, body: i2]
s = phi [entry: 0, body: s2]
c = i < n
br c body done
body:
x = i * -2
s2 = s + x
i2 = i + 1
jump h
done:
ret s
""")
st = {}
q = osr(p, st)
assert st["tests"] == 1
(cmp,) = ops(q, "<")
m = [ins for ins in ops(q, "*") if ins[3] == "n"]
assert cmp[3] == m[0][1] # the sides are swapped: -2 * n < -2 * i
for n in range(-3, 9):
same(p, q, [n])
def test_name_multiplier_keeps_the_test():
p = toyir.parse("""
# params: k, n
entry:
jump h
h:
i = phi [entry: 0, body: i2]
s = phi [entry: 0, body: s2]
c = i < n
br c body done
body:
x = i * k
s2 = s + x
i2 = i + 1
jump h
done:
ret s
""")
st = {}
q = osr(p, st)
assert st == {"replaced": 1, "tests": 0}
assert ("op", "c", "<", "i", "n") in kinds(q, "op")
for k in (-2, 0, 3):
for n in range(-2, 6):
same(p, q, [k, n])
def test_non_candidates_are_kept():
p = toyir.parse("""
# params: a, n
entry:
jump h
h:
i = phi [entry: 0, body: i2]
s = phi [entry: 0, body: s4]
c = i < n
br c body done
body:
x = i * i
y = a - i
s2 = s + x
s3 = s2 + y
s4 = s3 * 2
i2 = i + 1
jump h
done:
ret s
""")
st = {}
q = osr(p, st)
assert st["replaced"] == 0
assert ("op", "x", "*", "i", "i") in kinds(q, "op")
for a in (-1, 2):
for n in range(-1, 6):
same(p, q, [a, n])
def test_nested_loops():
p = toyir.parse("""
# params: n, m
entry:
jump h
h:
i = phi [entry: 0, latch: i2]
s = phi [entry: 0, latch: s2]
c = i < n
br c pre done
pre:
jump h2
h2:
j = phi [pre: i, l2: j2]
t = phi [pre: s, l2: t2]
d = j < m
br d l2 latch
l2:
x = j * 7
t2 = t + x
j2 = j + 1
jump h2
latch:
s2 = t + 1
i2 = i + 1
jump h
done:
ret s
""")
st = {}
q = osr(p, st)
# j * 7 becomes an inner induction variable that starts at i * 7, and
# i * 7 becomes an outer one, so both tests are replaced and the only
# multiplications left are in the entry block.
assert st == {"replaced": 1, "tests": 2}
assert [ins[3:] for ins in ops(q, "*")] == [("n", 7), ("m", 7)]
assert all(ins in q.blocks["entry"].instrs for ins in ops(q, "*"))
for n in range(-1, 5):
for m in range(-1, 6):
same(p, q, [n, m])
def test_errors():
with pytest.raises(ValueError):
osr(toyir.parse("# params: a\nentry:\n x = a + 1\n x = a + 2\n ret x\n"))
with pytest.raises(ValueError):
osr(toyir.parse("# params: a\nentry:\n p = &a\n ret 0\n"))
with pytest.raises(ValueError):
osr(toyir.parse("entry:\n ret 0\nlost:\n jump entry\n"))
with pytest.raises(ValueError):
osr(toyir.parse("# params: a\nentry:\n y = x + 1\n x = a + 1\n ret y\n"))
with pytest.raises(ValueError):
osr(toyir.parse("# params: a\nentry:\n x = a + 1\n ret x\nb:\n ret 0\n"))
with pytest.raises(ValueError):
osr(toyir.parse("# params: a\nentry:\n x = a + 1\n br x entry out\nout:\n ret x\n"))
# ------------------------------------------------------------ random programs
def gen(rng):
"""A random strict SSA program with params a, b, n. The outer loop runs
at most 4 times and the inner loop at most 3 times, so it always ends."""
rcs = ["a", "b", "n", "k1", "k2"]
def rc():
return rng.choice(rcs + [str(rng.randint(-3, 5)) for _ in range(3)])
def cand(iv):
form = rng.randrange(5)
r = rc()
return ["%s * %s" % (iv, r), "%s * %s" % (r, iv), "%s + %s" % (iv, r), "%s + %s" % (r, iv), "%s - %s" % (iv, r)][form]
def other(iv):
return rng.choice(["%s * %s" % (iv, iv), "%s - %s" % (rc(), iv), "%s & 3" % iv, "%s * %s" % (iv, "x1")])
mem = rng.random() < 0.4
call = rng.random() < 0.4
inner = rng.random() < 0.6
trap = rng.random() < 0.5
cmp = rng.choice(["<", "<=", "!=", "=="])
L = ["# params: a, b, n", "entry:"]
L.append(" k1 = a + %d" % rng.randint(-2, 3))
L.append(" k2 = b * %d" % rng.randint(-2, 3))
if trap:
L.append(" q0 = a / b")
if mem:
L += [" m = alloc", " *m = 0"]
L += [" jump h", "h:"]
L.append(" c = phi [entry: 0, latch: c2]")
L.append(" i = phi [entry: %s, latch: i3]" % rc())
L.append(" j = phi [entry: %s, latch: j2]" % rc())
L.append(" s = phi [entry: 0, latch: s3]")
L.append(" t1 = c %s n" % cmp)
L.append(" t2 = c < 4")
L.append(" t = t1 & t2")
L.append(" br t body done")
L.append("body:")
L.append(" x1 = %s" % cand(rng.choice(["i", "j", "c"])))
L.append(" x2 = %s" % cand(rng.choice(["x1", "i", "j"])))
L.append(" x3 = %s" % other(rng.choice(["i", "j", "c"])))
L.append(" x4 = %s" % cand(rng.choice(["c", "x2"])))
L.append(" tq = %s %s %s" % (rng.choice(["i", "j", "c"]), rng.choice(["<", "<=", "==", "!="]), rc()))
if trap:
L.append(" x5 = a / %s" % rng.choice(["i", "j", "x1"]))
else:
L.append(" x5 = x3 + 0")
if mem:
L.append(" *m = x2")
if call:
L.append(" x6 = call f(x4)")
else:
L.append(" x6 = x4 + tq")
if inner:
L += [" jump h2", "h2:"]
L.append(" ci = phi [body: 0, l2: ci2]")
L.append(" p = phi [body: %s, l2: p2]" % rng.choice(["i", "x1", "0", "k1"]))
L.append(" acc = phi [body: 0, l2: acc2]")
L.append(" u1 = ci < b")
L.append(" u2 = ci < 3")
L.append(" u = u1 & u2")
L.append(" br u l2 e2")
L.append("l2:")
L.append(" y1 = %s" % cand(rng.choice(["p", "ci"])))
L.append(" y2 = %s" % cand(rng.choice(["i", "y1", "p"])))
L.append(" acc1 = acc + y1")
L.append(" acc2 = acc1 + y2")
L.append(" p2 = p %s %s" % (rng.choice(["+", "-"]), rng.choice(["i", "k2", "2", "x1", "-1"])))
L.append(" ci2 = ci + 1")
L.append(" jump h2")
L.append("e2:")
last = "acc"
else:
last = "x5"
L.append(" bc = c & 1")
L.append(" br bc left right")
L.append("left:")
L.append(" iL = i + %s" % rc())
L.append(" jump latch")
L.append("right:")
L.append(" iR = %s" % rng.choice(["i - %s" % rc(), "%s + i" % rc(), "i * 2", "iRx"]).replace("iRx", "i + 1"))
L.append(" jump latch")
L.append("latch:")
L.append(" i3 = phi [left: iL, right: iR]")
L.append(" j2 = j %s %s" % (rng.choice(["+", "-"]), rc()))
L.append(" c2 = c + 1")
L.append(" s1 = s + x1")
L.append(" s2 = s1 + x6")
L.append(" s4 = s2 + %s" % last)
L.append(" s5 = s4 + x5")
L.append(" s3 = s5 + x3")
L.append(" jump h")
L.append("done:")
L.append(" z1 = %s" % cand(rng.choice(["i", "j", "c"])))
L.append(" z2 = s + z1")
if mem:
L.append(" z3 = *m")
L.append(" z4 = z2 + z3")
L.append(" ret z4")
else:
L.append(" ret z2")
return toyir.parse("\n".join(L) + "\n")
def test_random_programs():
rng = random.Random(20011201)
totals = {"replaced": 0, "tests": 0}
outcomes = {"ret": 0, "trap": 0}
for _ in range(600):
p = gen(rng)
st = {}
q = osr(p, st)
check_ssa(q)
for key in totals:
totals[key] += st[key]
for _ in range(8):
args = [rng.randint(-4, 6) for _ in range(3)]
outcomes[same(p, q, args, FUNCS)[0]] += 1
assert totals["replaced"] > 2400
assert totals["tests"] > 1000
assert outcomes["trap"] > 300 and outcomes["ret"] > 3000
History
Strength reduction is one of the oldest loop optimizations of optimizing compilers. Cocke and Kennedy published an algorithm in 1977, and Allen, Cocke and Kennedy gave the full method with linear function test replacement in 1981. It works on the strongly connected regions of the flow graph. Cooper, Simpson and Vick moved it to SSA form in 2001: they found the induction variables as strongly connected components of the SSA graph with Tarjan's algorithm of 1972, and kept the table of temporaries of the earlier work. Their algorithm OSR is the one taught in the textbook of Cooper and Torczon.
References
- 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 algorithm OSR with the procedures ClassifyIV, Replace, Reduce and Apply, the header as the member first in reverse postorder, region constants, and linear function test replacement through the edges that Reduce records
- 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 earlier algorithm on strongly connected regions of the flow graph, with a table of temporaries 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 table of temporaries indexed by the reduced expression, and the replacement of loop tests
- Robert E. Tarjan, Depth-first search and linear graph algorithms, SIAM Journal on Computing 1(2), 1972, 146-160, the strongly connected components algorithm, which emits a component after every component it reaches
- Keith D. Cooper and Linda Torczon, Engineering a Compiler, third edition, Morgan Kaufmann, 2022, Chapter 10 (Scalar Optimizations), the part on strength reduction with the algorithm OSR and linear function test replacement
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 | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag VGSWKK Edit this page History Report an error Markdown