Algorithm Search⌘K

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)
Properties
deterministicofflinerecursive

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 NN be a strongly connected component of it with more than one member, and let its header hh be the block of a member that comes first in reverse postorder. A region constant for hh is an integer, a parameter, or a name whose definition is in a block that strictly dominates hh. NN is an induction variable if hh dominates the blocks of all its members and every member is a phi-function, a copy, iv+rciv + rc, rc+ivrc + iv or iv−rciv - rc, with iviv in NN and rcrc a region constant for hh. A candidate is an instruction x=iv×rcx = iv \times rc, x=rc×ivx = rc \times iv, x=iv+rcx = iv + rc, x=rc+ivx = rc + iv or x=iv−rcx = iv - rc with iviv an induction variable and rcrc a region constant for its header.

The algorithm

The table maps a key (op,o1,o2)(op, o_1, o_2) to the name that holds o1opo2o_1 \mathbin{op} o_2. It is what makes two products of the same induction variable and constant share one new variable.

  1. OSR(P)
  2. 1compute the dominator tree and a reverse postorder of the blocks of P
  3. 2for each SCC N of the SSA graph, in the order Tarjan's algorithm finds them, do
  4. 3if N has more than one member then ClassifyIV(N)
  5. 4else if the member n of N is a candidate x = iv op rc then Replace(n, iv, rc)
  6. 5else mark n as not an induction variable
  7. 6replace the tests of induction variables (linear function test replacement)
  8. 7delete the instructions that no effect, branch or return needs
  9. ClassifyIV(N)
  10. 8header <- the block of a member of N that comes first in reverse postorder
  11. 9if 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
  12. 10mark every member of N as an induction variable with this header
  13. 11else for each member n of N do
  14. 12if n is a candidate then Replace(n, iv, rc) else mark n as not an induction variable
  15. Replace(n, iv, rc)
  16. 13result <- Reduce(op, iv, rc)
  17. 14replace n by x = result and mark x as an induction variable with the header of iv
  18. Reduce(op, iv, rc)
  19. 15if (op, iv, rc) is in the table then return its entry
  20. 16result <- a new name; add (op, iv, rc) -> result to the table
  21. 17make a copy of the definition of iv that defines result
  22. 18for each operand o of the copy do
  23. 19if o is an induction variable with the header of iv then replace o by Reduce(op, o, rc)
  24. 20else if op is * or the copy is a phi then replace o by Apply(op, o, rc)
  25. 21insert the copy right after the definition of iv; mark result as an induction variable with the header of iv
  26. 22return result
  27. Apply(op, o1, o2)
  28. 23if (op, o1, o2) is in the table then return its entry
  29. 24if o1 is an induction variable and o2 is a region constant for its header then return Reduce(op, o1, o2)
  30. 25if op is commutative, o2 is an induction variable and o1 is a region constant for its header then return Reduce(op, o2, o1)
  31. 26if o1 and o2 are constants then return o1 op o2
  32. 27result <- a new name; add (op, o1, o2) -> result to the table
  33. 28insert result = o1 op o2 at the end of the deeper of the blocks that define o1 and o2
  34. 29return 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 1⋅41 \cdot 4. For a phi-function, the start value 0 becomes 0oprc0 \mathbin{op} rc. 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 iviv with a region constant bb. If iviv has a reduction r=ivopkr = iv \mathbin{op} k, the comparison becomes rr against Apply(op,b,k)\mathrm{Apply}(op, b, k), and the step repeats with rr. For + and - this is always valid. For * the pass uses only an integer k≠0k \ne 0, and for k<0k < 0 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 {i,i2}\{i, i2\} with header h. Its members are a phi and i + 1, so it is an induction variable. The component {s,s2}\{s, s2\} 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 0⋅4=00 \cdot 4 = 0, and the add into osr2 = osr1 + 4 with 1⋅4=41 \cdot 4 = 4, 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 n=3n = 3 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 n=10n = 10 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.

  1. 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.
  2. The new names hold what their keys say. At every read of a name for the key (op,o1,o2)(op, o_1, o_2), its value equals o1opo2o_1 \mathbin{op} o_2 for the current values. The proof is by induction on the time of the read. For a copy of Reduce it uses the identities (a+b)k=ak+bk(a + b) k = ak + bk, (a−b)k=ak−bk(a - b) k = ak - bk and (a+b)±k=(a±k)+b(a + b) \pm k = (a \pm k) + b. Two facts on dominance show that the operands have not changed since the last definition.
  3. The rewritten instructions compute the same values. A replaced candidate reads a name that holds ivoprciv \mathbin{op} rc. 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.
  4. 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. PP 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 pp, the definition must dominate pp. 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. P′P' is the program that osr returns.

Claim. For every input, the run of P′P' visits the same blocks in the same order as the run of PP, and it ends with the same return value or the same trap, or it runs forever exactly when the run of PP does.

We write P1P_1 for the program just before the deletion of line L7. It is PP with three changes: new instructions inserted by lines L21 and L28, each candidate x=ivoprcx = iv \mathbin{op} rc replaced by a copy x=rx = r at line L14, and some comparisons rewritten at line L6. We first show that P1P_1 behaves like PP, 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 DD and BB be blocks with DD strictly dominating BB, and let BB dominate a block QQ. In a run, if DD is visited and QQ is visited later, then BB is visited after that visit of DD and no later than that visit of QQ.

Proof. Every path from the entry to DD that passes BB passes DD before its first BB, because DD dominates BB. So the part of such a path up to its first DD does not contain BB. Join this part to the run from the visit of DD to the visit of QQ. If that part of the run did not visit BB, the joined path would go from the entry to QQ without BB, which is not possible. □\square

Say that an instruction II in block BB comes before a point qq in block QQ if BB strictly dominates QQ, or if B=QB = Q and II stands before qq in the block. The end of BB counts as a point after every instruction of BB.

Lemma 2 (freshness). Let II come before a point qq, and let JJ be an instruction that comes before II. In a run, if JJ executes and the run later reaches qq, then II executes in between.

Proof. If JJ and II are in the same block, take the visit of that block in which JJ executes. If qq is in the same visit, II stands between JJ and qq. Otherwise the run leaves the visit through its terminator, so every instruction after JJ in the block executes, II included. If JJ is in a block DD that strictly dominates the block BB of II, Lemma 1 gives a visit of BB after JJ and no later than the visit of qq. If that visit is the visit of qq, II stands before qq in it. Otherwise the run leaves it, so II executes. □\square

The usual consequence of strict SSA form follows from Lemma 2 with JJ the first step of the run: every name is defined before it is read. The same holds for P1P_1 once we show it is in strict SSA form.

Where the new instructions stand

Write hh for the header of an induction variable and def(y)\mathrm{def}(y) for the block that defines yy. A region constant rcrc for hh is an integer, a parameter, or a name with def(rc)\mathrm{def}(rc) strictly dominating hh. Line L9 accepts a component only if hh dominates all its members. A name that line L14 marks is defined where the candidate was, and the candidate reads an induction variable, so hh 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. P1P_1 is in strict SSA form, and each new instruction comes before every point that reads its name.

Proof. Names of line L28. r=o1opo2r = o_1 \mathbin{op} o_2 is appended to the block dd 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 dd is well defined. The parameters count as defined before the entry, so dd is the entry if both operands are parameters or integers. Apply is called from three places.

  1. For a phi operand from a predecessor pp. The operand oo is defined in a block that dominates pp. The region constant is defined in a block that strictly dominates hh. If pp is not dominated by hh, the phi is at hh itself, because every predecessor of a block other than hh that hh dominates is also dominated by hh. A path from the entry to pp that avoids the definition of the region constant continues to hh, so the definition dominates pp. If hh dominates pp, the definition dominates pp too, because it strictly dominates hh. So dd dominates pp, and the read at the end of pp comes after rr.
  2. For an operand of a copied operation, or for the new side of a comparison at line L6. Both operands are region constants for hh, so dd strictly dominates hh, and the reading point is in a block that hh dominates.
  3. 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 rr of the definition of iviv 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 oo of the definition, which stands right after the definition of oo 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 iviv that is kept as it is, which strict SSA form of PP already covers. Every point that reads rr reads it instead of iviv or next to iviv, so it comes after the definition of iviv, and rr stands right after that definition.

The copies of line L14 read rr at the place of the candidate, which reads iviv. If the candidate is in the block of iviv, it stands after iviv and so after rr. □\square

The values of the new names

Every name made at lines L16 and L27 has a meaning. For a key (op,o1,o2)(op, o_1, o_2) in the table, the meaning of its name rr is o1opo2o_1 \mathbin{op} o_2. The integers and operands that Apply returns at line L26 and in the simplifications x⋅0=0x \cdot 0 = 0, x⋅1=xx \cdot 1 = x, x+0=xx + 0 = x and x−0=xx - 0 = x satisfy the same identity on the spot.

Lemma 4. In every run of P1P_1, at every step that reads a new name rr with meaning o1opo2o_1 \mathbin{op} o_2, the current value of rr equals the current value of o1o_1 combined by opop with the current value of o2o_2.

Proof. By strong induction on the step τ\tau of the read. Let σ<τ\sigma < \tau be the step of the last execution of the definition of rr before τ\tau. It exists by Lemma 3.

Names of line L28. At σ\sigma the instruction computed rr from the current values of o1o_1 and o2o_2. Their definitions come before rr and rr comes before the reading point. If one of them ran again between σ\sigma and τ\tau, Lemma 2 would run rr again before τ\tau, against the choice of σ\sigma. So the operands have the same values at σ\sigma and at τ\tau.

Names of line L21. Here rr has meaning ivoprciv \mathbin{op} rc with opop one of ++, −- and ×\times. Write kk for the value of rcrc. The definition of iviv runs in the step just before σ\sigma, 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 iviv 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 r=ivopkr = iv \mathbin{op} k right after σ\sigma.

  • iv=ϕ(…,op,…)iv = \phi(\ldots, o_p, \ldots). The copy is r=ϕ(…,ep,…)r = \phi(\ldots, e_p, \ldots) where epe_p is Reduce or Apply of (op,op,rc)(op, o_p, rc). Coming from pp, both read at the end of pp, a step before τ\tau, so by induction ep=opopke_p = o_p \mathbin{op} k there, and iv=opiv = o_p.
  • iv=oiv = o, a copy of an induction variable with the same header. Then r=er = e with e=Reduce(op,o,rc)e = \mathrm{Reduce}(op, o, rc), and by induction e=oopke = o \mathbin{op} k.
  • iv=a+biv = a + b with aa in the component and bb a region constant, or the same with the sides swapped. The copy is r=a′+b′r = a' + b' with a′=aopka' = a \mathbin{op} k by induction. If opop is ×\times, then b′=b⋅kb' = b \cdot k and r=(a+b)kr = (a + b) k. If opop is ++ or −-, then b′=bb' = b and r=(a±k)+b=(a+b)±kr = (a \pm k) + b = (a + b) \pm k.
  • iv=a−biv = a - b with aa in the component and bb a region constant. The same identities give (a−b)k(a - b) k and (a−b)±k(a - b) \pm k.

Between σ\sigma and τ\tau the value of iviv does not change: its definition stands right before rr and cannot trap, so a new execution of it is followed by a new execution of rr in the same visit. The value of rcrc does not change either: its definition comes before rr, and Lemma 2 applies as for line L28. So at τ\tau the identity still holds. □\square

The rewritten instructions

Lemma 5. In every run of P1P_1, every replaced candidate and every rewritten comparison computes the same value as the original instruction would compute at the same step.

Proof. A candidate x=ivoprcx = iv \mathbin{op} rc became x=rx = r with r=Reduce(op,iv,rc)r = \mathrm{Reduce}(op, iv, rc), and Lemma 4 gives r=ivoprcr = iv \mathbin{op} rc at that step.

A comparison c=acmpbc = a \mathbin{cmp} b with an induction variable aa and a region constant bb is rewritten in rounds. One round uses a reduction r=aopkr = a \mathbin{op} k of aa and the name or value b′=bopkb' = b \mathbin{op} k of Apply, and Lemma 4 holds for both at the step of the comparison. For opop equal to ++ or −-, acmpba \mathbin{cmp} b and rcmpb′r \mathbin{cmp} b' agree for every cmpcmp in <<, ≤\le, == and ≠\ne, because adding the same integer to both sides keeps the order. For opop equal to ×\times, line L6 uses only an integer k≠0k \ne 0. For k>0k > 0 the order is kept. For k<0k < 0 it is reversed, so a<ba < b holds if and only if b′<rb' < r, the same for ≤\le, and the sides are swapped. Equality and inequality do not depend on the sign. With bb on the left the argument is the same. Each round keeps the value, and b′b' is again a region constant for hh, so by induction on the rounds the final comparison computes the original value. □\square

The same behavior

Lemma 6. P1P_1 behaves like PP 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, P1P_1 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 ×\times 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. □\square

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 P1P_1 and P′P' in lock-step. P′P' 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. □\square

Lemmas 6 and 7 together prove the claim. The run of P′P' visits the same blocks as the run of PP, so it ends exactly when the run of PP ends.

Integers that wrap. The identities of Lemma 4 hold modulo 2w2^w, so the rewrite of candidates is also correct for integers of ww bits that wrap. Lemma 5 for the order tests << and ≤\le is not: with wrapping, neither adding kk nor multiplying by kk 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 ×\times they need an odd kk or a proof that nothing wraps.

Complexity

The input has size nn, counting instructions and operands, in bb blocks, and the pass creates mm instructions. Dominators by the iterative algorithm of Cooper, Harvey and Kennedy take O(b3)O(b^3) time in the worst case and close to O(b)O(b) on the graphs of real programs. Tarjan's algorithm takes O(n)O(n). 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 O((n+m)2)O((n + m)^2) term. With a map from names to positions, the work after the dominators is close to O(n+m)O(n + m).

The number mm of new instructions is not bounded by a constant factor of nn. Each distinct pair (op,rc)(op, rc) used with an induction variable makes a copy of its whole component, so mm 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) + 5 reduce 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 * 4 in 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 k≠0k \ne 0, or a test of order if it knows the sign of kk.

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 2w2^w, but test replacement with < or <= does not: osr4 < n * 4 + 5 can wrap when i < n cannot. 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 + i is 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 * k with k not known must not change <. With k=0k = 0 every product is 0, and for k<0k < 0 the order reverses.
  • Traps. A candidate never traps, but a / i does when i is 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.

operator_strength_reduction.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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
  4. 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
  5. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • History with a source
  • a scene preset for the example