Algorithm Search⌘K

Algorithmadvanced

Trace scheduling

Also called Fisher trace scheduling.

Schedules a likely path through several blocks as one block and adds compensation code where other paths enter or leave it.

Time
O(m (s N + n^2)) worst
Space
O(s N + n^2) extra
Where
N = the number of names; m = the number of traces; n = the number of items of one trace; s = the number of instructions and terminators of the largest program during the run
Properties
deterministicofflineiterative
Origin
Joseph A. Fisher, 1981

Trace scheduling is a global instruction scheduling method. It picks a trace, a path through several basic blocks that a profile says is likely, and schedules the whole trace as if it were one block. So an instruction can move above a branch or below the point where another path joins, which a block-by-block scheduler cannot do. The other paths must still compute the same values. When an instruction moves below a side exit (a branch that leaves the trace), a copy goes on the edge that leaves. When an instruction moves above a side entrance (a point where another path joins the trace), a copy goes on the edge that joins. These copies are the compensation code. Fisher (1981) introduced the method to compact horizontal microcode. It became the main scheduler of the first commercial VLIW compilers.

In plain words

A program often takes the same way through its branches. Trace scheduling finds that usual way, treats it as one long straight line of code, and packs the instructions of that line tightly, so that a wide machine can run several of them in each cycle. Packing moves some instructions past the branches. Then a run that leaves the usual way at a branch could miss an instruction that it needs, and a run that comes in from the side could miss one that moved up past its entry point. So the method puts a copy of each such instruction on the side path. The usual way gets faster, and the rare ways get a little slower and a little longer. The method then packs the next most usual way, until all code is done.

The problem

The input is a program in the toy IR of these pages: a control flow graph with no cycle whose blocks hold const, copy and op instructions and end with jump, br or ret, and an edge profile, a count for each edge. A run ends with ret v or with a trap (a division or remainder by 0). The machine issues at most 2 items per cycle, at most one multiply-unit operation (*, /, %, latency 3) and at most one branch (latency 1). Other operations have latency 1.

The output is a program that has the same outcome as the input on every input, the same returned value or a trap, and whose blocks are list schedules of traces. Loops are not handled here: real compilers unroll a loop and schedule traces inside its body, or use software pipelining.

The algorithm

  1. TRACE-SCHEDULE(P, freq)
  2. 1while some block of P is not scheduled do
  3. 2T <- the seed of highest count, grown along edges that are most likely at both ends, never backward past the entry
  4. 3live <- the live-in sets of P
  5. 4D <- the dependence DAG of the items of T: data edges, branches in order, the end item last
  6. 5add an edge from each branch B to each later operation that may trap or whose result is in live(off(B))
  7. 6add an edge from each item to each later entrance, and from each entrance to each later branch
  8. 7S <- a list schedule of D by height; order the items by (cycle, original position)
  9. 8for each branch B of T do
  10. 9C <- the operations from above B that S puts after B
  11. 10put copies of C, in the order of S, in a new block on the off-trace edge of B
  12. 11for each entrance J of T into a block b do
  13. 12C <- the operations from below J that S puts before J
  14. 13put copies of C, in the order of S, in a new block that takes the label b and jumps to the code after J
  15. 14replace T by S cut after each branch and at each entrance; mark the pieces scheduled; update freq
  16. 15return P

Trace selection (line L2). The seed is the block not yet scheduled with the highest count, the larger of the sums of its incoming and its outgoing edge counts. The trace grows forward from its last block aa to the successor bb of the largest edge count, but only if aa is also the predecessor of bb with the largest count, and bb is not yet scheduled. It grows backward in the same way, and it stops at the entry block, so that the entry stays the head of its trace. This is the mutual most likely rule. Chang and Hwu (1988) describe this growth from a seed with a best successor and a best predecessor.

Items (line L4). In the original order, the items of the trace b1,…,bkb_1, \dots, b_k are: an entrance JjJ_j for each bjb_j, j≥2j \ge 2, that has a predecessor other than bj−1b_{j-1}; the instructions of each block; a branch item for each br of bjb_j, j<kj < k, whose other target off(B)\mathrm{off}(B) is off the trace; and the end item, the terminator of bkb_k. An entrance takes no issue slot.

Dependences (lines L4 to L6). The data edges are the usual true, anti and output dependences of data dependence: a true dependence waits for the latency of the writer, an output dependence waits 1 cycle, and an anti dependence waits 0 cycles, so the two items can issue in the same cycle with the reader first. The branches keep their order, and every item comes before the end item. Line L5 lets an operation move above a branch only if it cannot trap and its result is dead on the off-trace edge. Such a motion is speculation: the operation runs also on runs that leave, and does nothing visible there. Line L6 keeps every item that is above an entrance above it, and keeps the order of entrances and branches. An operation may still move above an entrance.

Compensation (lines L8 to L13). An operation uu from above a branch BB that the schedule puts after BB does not run on a run that leaves at BB. So lines L9 and L10 put a copy of it on that edge. An operation from below an entrance JJ that the schedule puts before JJ does not run on a run that comes in at JJ. So lines L12 and L13 put a copy of it on the side edges: the new block takes the label of bjb_j, which all side edges already use, and it jumps to the code after JJ. The trace edge from bj−1b_{j-1} goes straight to that code.

Cutting (line L14). The schedule becomes blocks: a new block starts after each branch and at each entrance. The first piece keeps the label b1b_1. The compensation blocks are not scheduled yet, so later traces schedule them with their neighbors.

Example

Take this program with parameters a and b, and the profile 90 for B0→B1B_0 \to B_1 and B1→B3B_1 \to B_3, and 10 for B0→B2B_0 \to B_2 and B2→B3B_2 \to B_3:

B0:
  c = b < 5
  s = a - b
  br c B1 B2
B1:
  y = a / b
  jump B3
B2:
  y = a - 1
  jump B3
B3:
  w = b + 1
  v = w * w
  z = y + v
  r = z + s
  ret r

Line L2 picks B0B_0, the block of highest count, and grows it to the trace B0,B1,B3B_0, B_1, B_3. Line L3 gives live(B2)={a,b,s}\mathrm{live}(B_2) = \{a, b, s\}. The items, with their units, latencies and heights, are:

index item unit latency height
0 c = b < 5 alu 1 7
1 s = a - b alu 1 3
2 branch, off B2B_2 br 1 6
3 y = a / b mul 3 6
4 entrance into B3B_3 none 0 1
5 w = b + 1 alu 1 7
6 v = w * w mul 3 6
7 z = y + v alu 1 3
8 r = z + s alu 1 2
9 ret r br 1 1

Line L5 adds the edge from the branch to y = a / b, since a division by b can trap. It adds no edge to w, v, z or r: they cannot trap and their names are dead at B2B_2. Line L6 keeps items 0 to 3 above the entrance. The list scheduler gives:

cycle ready, by height issued
0 c, w, s c, w
1 branch, v, s, then y once the branch issues branch, y
2 v, s, then the entrance v, s, entrance
3, 4 none none
5 z z
6 r r
7 ret r ret r

The length is 7+1=87 + 1 = 8 cycles. This is optimal. The two multiply-unit operations y and v cannot start at cycle 0, because y waits for the branch and v waits for w, and they cannot share cycle 1. So one of them starts at 2 or later, z starts at 5 or later, and ret r at 7 or later. Block by block, the best schedules of B0B_0, B1B_1 and B3B_3 take 2, 3 and 7 cycles, so the same path takes 12.

Two motions need copies. s moved below the branch, so line L10 puts s = a - b on the edge to B2B_2. w moved above the entrance into B3B_3 (and above the branch, which line L5 allows since w is dead at B2B_2), so line L13 makes a block with label B3B_3 that computes w and jumps to the code after the entrance. y = a / b stays below the branch. The second trace is the exit block, B2B_2 and the entrance block, which have no side entrance and become one block. The output is:

B0:
  c = b < 5
  w = b + 1
  br c B0.1 B0.2
B0.1:
  y = a / b
  s = a - b
  jump B0.3
B0.3:
  v = w * w
  z = y + v
  r = z + s
  ret r
B0.2:
  s = a - b
  y = a - 1
  w = b + 1
  jump B0.3

On (a,b)=(1,7)(a, b) = (1, 7) both programs take the rare path and return 58. On (4,2)(4, 2) both return 13, and on (4,0)(4, 0) both trap. Without the copy of s in B0.2, the run on (1,7)(1, 7) would read s before any write. The copy of w in B0.2 is correct but not needed here: the only side entrance comes after B0, which has already computed w. Removing such copies is the subject of Freudenberger, Gross and Lowney (1994).

Correctness

Theorem. On every input, the output of TRACE-SCHEDULE returns the same value as the input program, or traps exactly when the input program traps. The loop of line L1 stops.

The full proof is in the proof file. It goes one trace at a time. The dependence edges make the schedule keep the order of any two items that read or write the same name, and keep the branches and entrances in their original order. So from the head or from an entrance, the new code runs the same items as the old code with the same last writer for every read, up to the point where a run leaves. At a side exit, an operation from below that ran early cannot trap and wrote only a name that is dead there (line L5), and an operation from above that did not run yet is in the exit block (line L10). So both runs leave with the same values of the live names. The same holds at the end of the trace, and a trap happens in both runs or in neither. An induction over the blocks in reverse topological order finishes the step. For termination, the number of paths from the blocks not yet scheduled to the first scheduled block or ret drops by at least 1 with each trace, although the compensation blocks are new blocks.

Proof: Trace scheduling with compensation code keeps the meaning of the program and stopsfull

We prove that one step of TRACE-SCHEDULE (lines L2 to L14: pick a trace, schedule it, add compensation code, cut it into blocks) gives a program with the same outcome as the input on every input. Then we prove that the loop of line L1 stops on an acyclic control flow graph. The rules of code motion in lines L4 to L6 are exactly what the proof needs: each rule appears in one lemma.

Setup

The program PP has an acyclic control flow graph and only const, copy and op instructions. Every value is an integer. A run of PP ends with ret v or with a trap (a division or remainder by 0, or a shift by an amount outside 0 to 63). As the graph is acyclic, every run is finite. live(L)\mathrm{live}(L) is the set of names that some path from the start of block LL reads before it writes them. It is the least solution of the usual backward equations, which line L3 computes.

The trace and its items. The trace is a path b1,…,bkb_1, \dots, b_k of the graph. The entry block of PP is never bjb_j for j≥2j \ge 2, because line L2 never grows a trace backward from the entry. Its items I0,…,In−1I_0, \dots, I_{n-1} are, in this index order:

  • for each bjb_j with j≥2j \ge 2 that has a predecessor other than bj−1b_{j-1}: an entrance JjJ_j;
  • the instructions of bjb_j, which we call operations;
  • for j<kj < k, if bjb_j ends with a br to two labels: a branch BB. One target is bj+1b_{j+1}, and the other is its off-trace target off(B)\mathrm{off}(B);
  • for j=kj = k: the end item, the terminator of bkb_k.

A branch or the end item reads its condition or its returned name. We say that two items u<vu < v conflict if one of them writes a name that the other reads or writes.

The DAG. DD has these edges u→vu \to v with u<vu < v and a delay δ(u,v)≥0\delta(u, v) \ge 0:

  • (E1) data: from the last writer of xx before vv to each reader vv of xx, delay the latency of the writer; from the last writer of xx before vv to a writer vv of xx, delay 1; from each reader of xx after the last writer of xx before vv to a writer vv of xx, delay 0;
  • (E2) from a branch BB to each later branch and to the end item; and from BB to each later operation that can trap or whose result is in live(off(B))\mathrm{live}(\mathrm{off}(B)) (line L5);
  • (E3) from each item before an entrance JJ to JJ, and from JJ to each later branch and to the end item (line L6);
  • (E4) from each item to the end item.

The schedule. Line L7 gives each item a cycle tvt_v with tv≥tu+δ(u,v)t_v \ge t_u + \delta(u, v) for each edge. The order π\pi sorts the items by (tv,v)(t_v, v). We write u≺vu \prec v when uu comes before vv in π\pi.

The output P′P'. Walk π\pi and cut it after each branch, at each entrance and after the end item. The pieces become blocks. The first piece keeps the label b1b_1. A piece that ends with a branch BB ends with br to the next piece and to the exit target of BB: that is off(B)\mathrm{off}(B) if MBM_B is empty, and otherwise a new exit block with copies of the operations of

MB={u operation:u<B, B≺u}M_B = \{u \text{ operation} : u < B,\ B \prec u\}

in the order π\pi, and then jump off(B) (lines L8 to L10). A piece that ends at an entrance JjJ_j jumps to the next piece. The label bjb_j goes to a new entrance block with copies of the operations of

Cj={u operation:u>Jj, u≺Jj}C_j = \{u \text{ operation} : u > J_j,\ u \prec J_j\}

in the order π\pi, and then a jump to the piece after JjJ_j. If CjC_j is empty, the piece after JjJ_j takes the label bjb_j itself (lines L11 to L13). The last piece ends with the terminator of bkb_k. All other blocks of PP stay as they are.

Lemma 1. Order

(a) Each edge u→vu \to v of DD has u≺vu \prec v. (b) If u<vu < v conflict, then u≺vu \prec v.

Proof. (a) u<vu < v and tv≥tu+δ(u,v)≥tut_v \ge t_u + \delta(u, v) \ge t_u, so (tu,u)<(tv,v)(t_u, u) < (t_v, v).

(b) By (a) it is enough to find a path from uu to vv in DD. Let xx be the name of the conflict and let w1<w2<…w_1 < w_2 < \dots be the writers of xx. Consecutive writers are joined by output edges of (E1), so the writers form a path in index order. If uu writes and vv reads, the last writer ww before vv has u≤wu \le w, and the path goes u→⋯→w→vu \to \dots \to w \to v. If uu reads and vv writes, the first writer ww after uu has w≤vw \le v, uu is a reader after the last writer before ww, so (E1) has u→wu \to w, and the path goes on along the writers to vv. If both write, the writers path joins them. □\square

Lemma 2. Shape of the order

(a) The branches and the end item are in index order in π\pi.

(b) For an entrance JJ: every item u<Ju < J has u≺Ju \prec J, and every branch or end item v>Jv > J has J≺vJ \prec v. So the items v≻Jv \succ J all have v>Jv > J.

(c) For a branch BB and an entrance J<BJ < B: every u∈MBu \in M_B has u>Ju > J.

(d) For a branch BB: every operation v>Bv > B with v≺Bv \prec B cannot trap, and its result is not in live(off(B))\mathrm{live}(\mathrm{off}(B)).

Proof. (a) is (E2) with Lemma 1. (b) is (E3) with Lemma 1; for the last sentence, an operation v<Jv < J would have v≺Jv \prec J. (c) If u<Ju < J, then u≺J≺Bu \prec J \prec B by (b), but u∈MBu \in M_B means B≺uB \prec u. (d) If vv could trap or wrote a name of live(off(B))\mathrm{live}(\mathrm{off}(B)), (E2) would give the edge B→vB \to v and so B≺vB \prec v. □\square

The run through one region

Fix an entrance point ee: either e=−1e = -1 for the head b1b_1, or ee is the index of an entrance JjJ_j. Its label LeL_e is b1b_1 or bjb_j. Both labels exist in P′P'. Let πe\pi_e be π\pi restricted to the items with index above ee.

What PP does from LeL_e. It runs the items e+1,e+2,…e+1, e+2, \dots in index order. An entrance does nothing. A branch either goes on along the trace or leaves to off(B)\mathrm{off}(B).

What P′P' does from LeL_e. For e=−1e = -1 it runs the pieces from the first one, that is π\pi in order. For an entrance it first runs the copies of CjC_j in the order π\pi, then the pieces after JjJ_j. By Lemma 2(b), the items after JjJ_j in π\pi are the items above ee that are not in CjC_j. So in both cases P′P' runs πe\pi_e in order, until a branch BB leaves the trace. Then it runs the copies of MBM_B in the order π\pi and jumps to off(B)\mathrm{off}(B). By Lemma 2(c), MBM_B has only items above ee. If no branch leaves, it ends with the end item. Call the items that P′P' runs in this region, in the order it runs them, the sequence XX.

Ideal values. For an item u>eu > e and a name xx that uu reads, let rw(u,x)\mathrm{rw}(u, x) be the last writer of xx among the items e+1,…,u−1e+1, \dots, u-1, or "the entrance" if there is none. Run the operations above ee in index order as straight-line code from a state σ\sigma, with a trapping operation giving the special value ⊥\bot, and with ⊥\bot for any operation that reads ⊥\bot. This gives each operation uu its ideal value valσ(u)\mathrm{val}_\sigma(u). The run of PP from LeL_e computes exactly these values for the items it runs, because it runs them in index order.

Lemma 3. The same writers

If uu is in XX and reads xx, then the last item before uu in XX that writes xx is rw(u,x)\mathrm{rw}(u, x), or there is none if rw(u,x)\mathrm{rw}(u, x) is the entrance.

Proof. First, for two items u<wu < w in XX that conflict, uu is before ww in XX. If both are in πe\pi_e or both in MBM_B, this is Lemma 1(b), as both parts follow π\pi. If u∈MBu \in M_B and ww is in the part of πe\pi_e that runs, then w⪯B≺uw \preceq B \prec u, which is against Lemma 1(b). If uu runs in πe\pi_e and w∈MBw \in M_B, then uu is before ww in XX anyway.

Next, w=rw(u,x)w = \mathrm{rw}(u, x) is in XX before uu. If uu runs in the part of πe\pi_e, then w≺uw \prec u by Lemma 1(b), and w>ew > e, so ww runs before uu. If u∈MBu \in M_B, then w<u<Bw < u < B. Either w≺Bw \prec B and ww ran in πe\pi_e, or w∈MBw \in M_B and w≺uw \prec u.

Last, take any other writer w′w' of xx in XX. If w′<ww' < w, it is before ww by the first step. No writer lies strictly between ww and uu in index order. If w′>uw' > u, it conflicts with uu and so is after uu. So ww is the last writer before uu. If rw(u,x)\mathrm{rw}(u, x) is the entrance, every writer of xx in XX is above uu, so after uu. □\square

Lemma 4. The same values

Let σ\sigma and σ′\sigma' agree on live(Le)\mathrm{live}(L_e). Run PP from LeL_e with σ\sigma, and P′P' from LeL_e with σ′\sigma'. Then every item in XX reads the same values as in the ideal run from σ\sigma, and every operation in XX that does not trap computes valσ(u)\mathrm{val}_\sigma(u).

Proof. By induction along XX. Take uu and a name xx that it reads. If rw(u,x)=w\mathrm{rw}(u, x) = w, then by Lemma 3, uu reads the value that ww computed in XX, which is valσ(w)\mathrm{val}_\sigma(w) by induction. (ww did not trap, or the run would have stopped.) If rw(u,x)\mathrm{rw}(u, x) is the entrance, uu reads σ′(x)\sigma'(x). The trace path from LeL_e to the block of uu reads xx at uu with no write before, so x∈live(Le)x \in \mathrm{live}(L_e) and σ′(x)=σ(x)\sigma'(x) = \sigma(x). In both cases uu reads the ideal value. □\square

Lemma 5. One region

Under the hypothesis of Lemma 4, exactly one of these holds.

  1. Both runs trap in the region.
  2. Both leave at the same branch BB to off(B)\mathrm{off}(B), with states that agree on live(off(B))\mathrm{live}(\mathrm{off}(B)).
  3. Both reach the end item. If it is ret a, both return the same value. Otherwise both go to the same successor of bkb_k, with states that agree on its live set.

Proof. There are three cases for the run of PP.

PP leaves at a branch B∗B^* without a trap. The items of πe\pi_e that P′P' meets before B∗B^* are of three kinds. Branches: by Lemma 2(a) they are the branches below B∗B^* in index order. They read the ideal values by Lemma 4, the same as in PP, so they stay on the trace. Operations below B∗B^*: PP ran them without a trap, and they compute the same values. Operations above B∗B^* that are before B∗B^* in π\pi: they cannot trap, by Lemma 2(d). So P′P' reaches B∗B^*, leaves the trace, and runs MB∗M_{B^*}, whose operations are below B∗B^* and do not trap. The items that P′P' ran are all the items e+1,…,B∗e+1, \dots, B^* and the set S={v>B∗:v≺B∗}S = \{v > B^* : v \prec B^*\} of operations. Take x∈live(off(B∗))x \in \mathrm{live}(\mathrm{off}(B^*)). By Lemma 2(d), no item of SS writes xx. The writers of xx in e+1,…,B∗e+1, \dots, B^* run in index order (Lemma 3, first step), so the last one is the same as in PP, and it computed the same value. If none of them writes xx, then x∈live(Le)x \in \mathrm{live}(L_e) and both states keep the entry value. This is case 2.

PP reaches the end item without a trap. The same argument with B∗B^* the end item. By (E4), SS is empty. The end item reads the same value. This is case 3.

PP traps at an operation oo, and every branch below oo stays on the trace. Suppose that P′P' does not trap in the region. Then it leaves at a branch BB or reaches the end item, and as above it ran every item from e+1e+1 to BB (or to the end). The branches below BB stayed on the trace in P′P' with the ideal values, so they also do so in PP. BB left in P′P', so it would leave in PP too. As PP trapped first, o<Bo < B. So P′P' ran oo, with the ideal values of its operands by Lemma 4, and these are the values with which oo traps in PP. So P′P' traps, which is a contradiction. This is case 1. □\square

Theorem 6. One step keeps the meaning

On every input, PP and P′P' have the same outcome.

Proof. Call a label of PP kept if it is not on the trace, or it is b1b_1, or it is a bjb_j with an entrance. Every kept label is a label of P′P'. We show, for every kept label LL, that runs of PP and P′P' from LL with states that agree on live(L)\mathrm{live}(L) have the same outcome. We use induction on LL in reverse topological order of PP.

If LL is not on the trace, P′P' has the same block at LL. Both runs compute the same values on the live names, trap together, and go to the same successor L′L' with states that agree on live(L′)\mathrm{live}(L'). L′L' is kept: if L′=bjL' = b_j with j≥2j \ge 2, then LL is a predecessor other than bj−1b_{j-1}, so bjb_j has an entrance. L′L' comes after LL in the topological order, so the induction applies.

If LL is b1b_1 or an entrance label bjb_j, Lemma 5 applies. In case 1 both trap, and in case 3 with ret both return the same value. In case 2, off(B)\mathrm{off}(B) for a branch of bib_i with i≥ji \ge j is either off the trace, or it is some bmb_m. In the second case m>i+1m > i + 1, because m≤im \le i would close a cycle and m=i+1m = i + 1 is the trace target. Then bib_i is a predecessor of bmb_m other than bm−1b_{m-1}, so bmb_m has an entrance and is kept. off(B)\mathrm{off}(B) comes after bib_i, so after LL, and the induction applies. Case 3 with a jump or a branch is the same.

The entry of PP is kept, because it is b1b_1 or off the trace, and it stays the entry of P′P'. Both runs start there with the same arguments. □\square

Lemma 7. The new program can go through the loop again

P′P' has only const, copy and op instructions, and its graph is acyclic.

Proof. The copies are copies of operations. For the graph, give each block of P′P' a key, and compare the keys first by the topological rank of a block of PP, then by a number. Let c0,c1,…c_0, c_1, \dots be the cut items in π\pi (branches, entrances and the end item). By Lemma 2(a) and 2(b) they are in index order. Let β(c)\beta(c) be the block of PP that holds cc, where β(Jj)=bj\beta(J_j) = b_j. The keys are:

  • a block not on the trace: (its rank, 0);
  • the piece that ends at crc_r: (β(cr),r)(\beta(c_r), r);
  • the exit block of a branch of bib_i: (bi,n+1)(b_i, n + 1);
  • the entrance block of bjb_j: (bj,−1)(b_j, -1).

Every edge of P′P' goes to a larger key. From a piece to the next piece: the block does not go down, and the number goes up. From the piece of a branch of bib_i to its exit block: r≤nr \le n. From an exit block of bib_i, or from the piece of a branch of bib_i, to off(B)\mathrm{off}(B): off(B)\mathrm{off}(B) comes after bib_i in PP, and its key has that block or a later one. From an entrance block (bj,−1)(b_j, -1) to the piece after JjJ_j: that piece has a block at least bjb_j and a number at least 0. From a block off the trace to b1b_1 or bjb_j: it comes before bjb_j in PP. From the last piece to a successor of bkb_k: the successor comes after bkb_k. So there is no cycle. □\square

Theorem 8. The loop stops

For a program QQ with a set done\mathrm{done} of scheduled blocks, let p(c)=1p(c) = 1 if cc is done or has no successor, and otherwise p(c)=∑sp(s)p(c) = \sum_{s} p(s) over the successors ss of cc. So p(c)p(c) counts the paths from cc that stop at the first done block or at a ret. Let

Φ=∑c not donep(c).\Phi = \sum_{c \text{ not done}} p(c).

Φ\Phi is a positive integer while some block is not done, and each step makes it smaller by at least 1. So the loop of line L1 stops after at most Φ\Phi steps of the input.

Proof. Write pp before the step and p′p' after. The step removes b1,…,bkb_1, \dots, b_k from the blocks that are not done, marks the pieces done, and adds exit blocks and entrance blocks.

Old blocks do not grow. For a block cc off the trace, the edges into the trace now go to b1b_1 (a done piece, p′=1p' = 1) or to the label bjb_j (a done piece, p′=1p' = 1, or an entrance block whose only successor is done, so p′=1p' = 1). Each of these has p′=1≤p(bj)p' = 1 \le p(b_j). By induction in reverse topological order, p′(c)≤p(c)p'(c) \le p(c).

The exit blocks. An exit block of BB has the one successor off(B)\mathrm{off}(B), so its p′p' is p′(off(B))≤p(off(B))p'(\mathrm{off}(B)) \le p(\mathrm{off}(B)). Each path from b1b_1 leaves the trace at a first place: at a branch BB to off(B)\mathrm{off}(B), or at the end of bkb_k. So p(b1)=∑Bp(off(B))+Ep(b_1) = \sum_B p(\mathrm{off}(B)) + E, where E≥1E \ge 1 counts the paths that leave at the end (E=1E = 1 if bkb_k returns). So the exit blocks add at most p(b1)−1p(b_1) - 1.

The entrance blocks. There are at most k−1k - 1, and each has p′=1p' = 1.

The removed blocks. They had ∑ip(bi)≥p(b1)+(k−1)\sum_i p(b_i) \ge p(b_1) + (k - 1).

So Φ′≤Φ−p(b1)−(k−1)+(p(b1)−1)+(k−1)=Φ−1\Phi' \le \Phi - p(b_1) - (k - 1) + (p(b_1) - 1) + (k - 1) = \Phi - 1. □\square

Summary

Each step keeps the outcome (Theorem 6), keeps the input form (Lemma 7), and lowers Φ\Phi (Theorem 8). So TRACE-SCHEDULE stops, and its output has the same outcome as its input on every input. The bound Φ\Phi counts paths, so it can be exponential in the number of blocks. This proof does not bound the code growth any better.

Complexity

Let nn be the number of items of one trace, ss the number of instructions and terminators of the program, NN the number of names and mm the number of traces.

  • Line L2. The counts and the growth look at each edge a constant number of times: O(s)O(s).
  • Line L3. One backward pass in reverse topological order solves the liveness equations of an acyclic graph, with sets of at most NN names: O(sN)O(s N). The Python code repeats the pass until nothing changes, which can take more passes.
  • Lines L4 to L6. The DAG has O(n2)O(n^2) edges. Each data edge, each branch edge and each entrance edge is made in O(1)O(1): O(n2)O(n^2).
  • Line L7. Heights in one pass over the edges, then a list schedule with a ready queue: O(n2+nlog⁡n)O(n^2 + n \log n), as the number of cycles is at most the sum of the latencies, O(n)O(n). The Python code scans all items for each choice, which is O(n3)O(n^3).
  • Lines L8 to L14. Each branch and each entrance copies at most nn operations: O(n2)O(n^2), and the rebuild is O(s)O(s).

So one trace costs O(sN+n2)O(s N + n^2), and the run costs O(m(sN+n2))O(m (s N + n^2)) time and O(sN+n2)O(s N + n^2) space. Here ss is the size of the largest program during the run. The termination proof bounds mm by the number of paths, which can be exponential in the number of blocks, and the copies can make ss grow in the same way. In practice compilers limit the length of a trace and the motions that need copies.

Properties

  • Correct for every input. The profile only chooses the traces. A bad profile makes the code slower, never wrong.
  • The optimum is never worse than block by block. The best schedule of the whole trace is at most the sum of the best schedules of its blocks, because the block schedules placed one after the other are a legal schedule of the trace. In the example, 8 cycles against 12. The list scheduler is a heuristic, so this holds for the optimum, not for every list schedule.
  • Slower rare paths. A run that leaves at a side exit runs the exit block, and a run that comes in at a side entrance runs the entrance block. Their cost goes on the rare paths.
  • Code growth. Every motion past a side exit or entrance makes a copy, and copies are scheduled again in later traces, where they can be copied again.
  • Speculation without hardware help. Only operations that cannot trap move above a branch. With loads and stores this needs memory dependence analysis, or hardware with non-trapping loads.

Variants and improvements

  • Superblock scheduling (Hwu et al. 1993) removes the side entrances first by tail duplication. Then only side exits need care, and the bookkeeping is much simpler, at the cost of more code.
  • Avoidance and suppression of compensation code (Freudenberger, Gross and Lowney 1994). The scheduler can refuse a motion that needs a copy when the gain is small, or drop a copy whose value the side path already has, as with w in the example.
  • Better traces. Chang and Hwu (1988) compare selection by block counts and by edge counts, and stop a trace when an edge is not likely enough. Path profiles give the real hot paths instead of a chain of locally likely edges.
  • Loops. The trace stops at a back edge. Unrolling the loop with loop unrolling first gives longer traces. For loops with many iterations, software pipelining overlaps the iterations instead.
  • Percolation scheduling (Nicolau) moves operations one edge at a time by a small set of local transformations, each of which keeps the meaning, instead of scheduling a whole trace at once. Muchnick (Section 17.6) describes it.

When to use it

Use it for a wide in-order machine, such as a VLIW or EPIC processor, on code with small blocks and branches that a profile can predict. There the machine does not reorder instructions, and a block alone has too little parallel work. Prefer superblock scheduling when simple bookkeeping matters more than code size. On an out-of-order processor, the hardware already looks past branches, and the gain is smaller. For loops, use iterative modulo scheduling. Without a profile, the static guess of even branch splits gives traces that can slow down the paths that matter.

Pitfalls

  • Speculating an operation that can trap. If line L5 adds edges only for live names, a division can move above the branch that tests its divisor, and a run that leaves at that branch traps where the input did not. Line L5 must also add the edge for every operation that may trap.
  • Speculating a write to a live name. If line L5 ignores live(off(B))\mathrm{live}(\mathrm{off}(B)), an operation from below the branch can overwrite a name that the off-trace path still reads. Use the live-in set of the off-trace target, computed by line L3 on the current program.
  • Missing exit copies. If line L9 collects only the operations of the block of BB, an operation from an earlier block that moved below BB is lost on the exit. In the example, dropping the copy of s makes the rare path read an undefined name. Take every operation from above BB, in any block of the trace.
  • Moving an operation below an entrance. If line L6 does not add the edges into the entrance, an operation from above the entrance can move below it, and then it also runs on the side path, where it did not run before. Keep every earlier item above the entrance.
  • Entrance copies on the wrong edge. If line L13 gives the label bjb_j to the piece after the entrance and puts the copies elsewhere, the side edges skip the copies. The new block must take the label bjb_j, which the side edges use, and the trace edge from bj−1b_{j-1} must go past it.
  • Growing a trace backward past the entry. If line L2 puts the entry block in the middle of a trace, the entry gets an entrance and its label moves to a new block. Stop the backward growth at the entry.

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.

toyir.pyI0RawGitHub
# 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)
trace_scheduling.py 432 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/trace-scheduling/. The authors are listed in prov/5GWXK6.jsonl.
"""Trace scheduling after Fisher, on the toy IR.

trace_schedule(prog, freq) takes a toy IR program with an acyclic control
flow graph and only const, copy and op instructions, and an edge profile
freq (a dict from an edge (a, b) to a count). While some block is not
scheduled, it

1. picks a trace: the unscheduled block of highest count, grown forward and
   backward along edges that are the most likely way out of one end and the
   most likely way into the other end;
2. builds the dependence DAG of the items of the trace (its operations, its
   side exits and its side entrances) and list schedules it as one block;
3. puts copies of the operations that moved below a side exit on the
   off-trace edge of that exit, and copies of the operations that moved
   above a side entrance on the edges that enter there;
4. cuts the scheduled trace into blocks and marks them scheduled.

The compensation blocks are new unscheduled blocks, so later traces
schedule them too.

The machine: each cycle issues at most `width` items, at most cap[u] of
unit u. The unit of a multiply, divide or remainder is "mul" (latency 3),
of a branch or of the last terminator "br" (latency 1), and of the other
operations "alu" (latency 1). An entrance is a mark that takes no slot.
The scheduled trace runs its items in the order (cycle, original
position), so a dependence with delay 0 lets two items share a cycle.

Code motion rules. An operation may move below a side exit; it is copied
onto the off-trace edge. An operation may move above a side exit only if it
cannot trap and its result is dead on the off-trace edge. No operation moves
below a side entrance: entrances and branches keep their order. An
operation may move above a side entrance; it is copied onto the side edges.
"""

import toyir

MACHINE = {"width": 2, "cap": {"mul": 1, "br": 1}}
LATENCY = {"alu": 1, "mul": 3, "br": 1, "join": 0}


class Item:
    """One item of a trace: an operation ("op"), a side exit ("br"), a
    side entrance ("join") or the terminator of the last block ("end")."""

    def __init__(self, kind, blk, ins=None, term=None, label=None, off=None):
        self.kind = kind
        self.blk = blk
        self.ins = ins
        self.term = term
        self.label = label
        self.off = off
        if kind == "op":
            self.uses = toyir.uses(ins)
            self.defs = toyir.defs(ins)
        elif kind in ("br", "end"):
            self.uses = toyir.term_uses(term)
            self.defs = None
        else:
            self.uses = []
            self.defs = None

    def unit(self):
        if self.kind in ("br", "end"):
            return "br"
        if self.kind == "join":
            return "join"
        if self.ins[0] == "op" and self.ins[2] in ("*", "/", "%"):
            return "mul"
        return "alu"

    def latency(self):
        return LATENCY[self.unit()]


def can_trap(ins):
    if ins[0] in ("const", "copy"):
        return False
    if ins[0] != "op":
        return True
    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 check_input(prog):
    if not toyir.is_acyclic(prog):
        raise ValueError("trace scheduling here needs an acyclic CFG")
    for b in prog.blocks.values():
        for ins in b.instrs:
            if ins[0] not in ("const", "copy", "op"):
                raise ValueError("only const, copy and op instructions: %r" % (ins,))


def liveness(prog):
    """live_in[label]: the names read before any write on some path."""
    live_in = {lab: set() for lab in prog.blocks}
    changed = True
    while changed:
        changed = False
        for lab in reversed(list(prog.blocks)):
            b = prog.blocks[lab]
            live = set()
            for s in toyir.succs(prog, lab):
                live |= live_in[s]
            live |= set(toyir.term_uses(b.term))
            for ins in reversed(b.instrs):
                live.discard(toyir.defs(ins))
                live |= set(toyir.uses(ins))
            if live != live_in[lab]:
                live_in[lab] = live
                changed = True
    return live_in


# ---------------------------------------------------------------- profiles


def profile(prog, inputs):
    """Edge counts from runs of prog on the inputs (a run that traps
    counts the edges it took before the trap)."""
    freq = {e: 0 for e in toyir.edges(prog)}
    for args in inputs:
        env = dict(zip(prog.params, args))
        lab = prog.entry
        try:
            while True:
                b = prog.blocks[lab]
                for ins in b.instrs:
                    env[ins[1]] = _value(ins, env)
                t = b.term
                if t[0] == "ret":
                    break
                if t[0] == "jump":
                    nxt = t[1]
                else:
                    nxt = t[2] if _operand(t[1], env) != 0 else t[3]
                freq[(lab, nxt)] += 1
                lab = nxt
        except toyir._Trap:
            pass
    return freq


def _operand(a, env):
    return a if isinstance(a, int) else env[a]


def _value(ins, env):
    if ins[0] == "const":
        return ins[2]
    if ins[0] == "copy":
        return _operand(ins[2], env)
    return toyir._binop(ins[2], _operand(ins[3], env), _operand(ins[4], env))


def static_profile(prog):
    """A guess without runs: the entry runs once and each br splits evenly."""
    order = []
    seen = set()

    def visit(lab):
        seen.add(lab)
        for s in toyir.succs(prog, lab):
            if s not in seen:
                visit(s)
        order.append(lab)

    visit(prog.entry)
    order.reverse()
    bf = {lab: 0.0 for lab in prog.blocks}
    bf[prog.entry] = 1.0
    freq = {}
    for lab in order:
        ss = toyir.succs(prog, lab)
        for s in ss:
            freq[(lab, s)] = bf[lab] / len(ss)
            bf[s] += freq[(lab, s)]
    return freq


# ---------------------------------------------------------- trace selection


def pick_trace(prog, freq, done):
    """The seed is the unscheduled block with the highest count. The trace
    grows from its last block a to the most likely successor b, and from its
    first block b to the most likely predecessor a, only while a is also the
    most likely predecessor of b (or b the most likely successor of a) and
    the new block is not scheduled. The entry block is always the head of
    its trace, so the entry label stays the entry."""
    pr = toyir.preds(prog)
    rank = {lab: i for i, lab in enumerate(prog.blocks)}
    inn = {lab: 0 for lab in prog.blocks}
    out = {lab: 0 for lab in prog.blocks}
    for a, b in toyir.edges(prog):
        out[a] += freq.get((a, b), 0)
        inn[b] += freq.get((a, b), 0)

    def count(lab):
        return max(inn[lab], out[lab])

    def best_succ(a):
        return max(toyir.succs(prog, a), key=lambda b: (freq.get((a, b), 0), -rank[b]), default=None)

    def best_pred(b):
        return max(pr[b], key=lambda a: (freq.get((a, b), 0), -rank[a]), default=None)

    seed = max((lab for lab in prog.blocks if lab not in done), key=lambda lab: (count(lab), -rank[lab]))
    trace = [seed]
    while True:
        b = best_succ(trace[-1])
        if b is None or b in done or b in trace or best_pred(b) != trace[-1]:
            break
        trace.append(b)
    while trace[0] != prog.entry:
        a = best_pred(trace[0])
        if a is None or a in done or a in trace or best_succ(a) != trace[0]:
            break
        trace.insert(0, a)
    return trace


# ------------------------------------------------------------ the DAG


def trace_items(prog, trace):
    """The items of the trace in their original order."""
    pr = toyir.preds(prog)
    items = []
    for i, lab in enumerate(trace):
        b = prog.blocks[lab]
        if i > 0 and any(p != trace[i - 1] for p in pr[lab]):
            items.append(Item("join", i, label=lab))
        for ins in b.instrs:
            items.append(Item("op", i, ins=ins))
        t = b.term
        if i == len(trace) - 1:
            items.append(Item("end", i, term=t))
        elif t[0] == "br" and t[2] != t[3]:
            off = t[3] if t[2] == trace[i + 1] else t[2]
            items.append(Item("br", i, term=t, off=off))
    return items


def build_dag(items, live_in):
    """Edges (u, v) -> delay, all with u < v."""
    edges = {}

    def add(u, v, d):
        edges[(u, v)] = max(edges.get((u, v), d), d)

    last_def = {}
    readers = {}
    for v, it in enumerate(items):
        for x in it.uses:
            if x in last_def:
                add(last_def[x], v, items[last_def[x]].latency())
        x = it.defs
        if x is not None:
            if x in last_def:
                add(last_def[x], v, 1)
            for r in readers.get(x, []):
                add(r, v, 0)
        for y in it.uses:
            readers.setdefault(y, []).append(v)
        if x is not None:
            last_def[x] = v
            readers[x] = []
    for b, it in enumerate(items):
        if it.kind == "br":  # @line L5
            for v in range(b + 1, len(items)):
                w = items[v]
                if w.kind in ("br", "end"):
                    add(b, v, 0)
                elif w.kind == "op" and (can_trap(w.ins) or w.defs in live_in[it.off]):
                    add(b, v, 0)
        elif it.kind == "join":  # @line L6
            for u in range(b):
                add(u, b, 0)
            for v in range(b + 1, len(items)):
                if items[v].kind in ("br", "end"):
                    add(b, v, 0)
    end = len(items) - 1
    for u in range(end):
        add(u, end, 0)
    return edges


def heights(items, edges):
    h = [it.latency() for it in items]
    succ = {}
    for (u, v), d in edges.items():
        succ.setdefault(u, []).append((v, d))
    for u in range(len(items) - 1, -1, -1):
        for v, d in succ.get(u, []):
            h[u] = max(h[u], d + h[v])
    return h


def fits(it, used, machine):
    u = it.unit()
    if u == "join":
        return True
    return len(used) < machine["width"] and used.count(u) < machine["cap"].get(u, machine["width"])


def list_schedule(items, edges, machine=MACHINE):
    """Cycle by cycle, start the ready item of greatest height that fits,
    until no ready item fits; then go to the next cycle."""
    n = len(items)
    preds = [[] for _ in range(n)]
    for (u, v), d in edges.items():
        preds[v].append((u, d))
    h = heights(items, edges)
    t = {}
    cyc = 0
    while len(t) < n:
        used = []
        while True:
            ready = [v for v in range(n) if v not in t and all(u in t and t[u] + d <= cyc for u, d in preds[v])]
            ok = [v for v in ready if fits(items[v], used, machine)]
            if not ok:
                break
            v = max(ok, key=lambda v: (h[v], -v))
            t[v] = cyc
            if items[v].unit() != "join":
                used.append(items[v].unit())
        cyc += 1
    return t


def length(items, t):
    return max(t[v] + items[v].latency() for v in range(len(items)))


# ------------------------------------------------------------ one trace


def _fresh(taken, base):
    k = 1
    while "%s.%d" % (base, k) in taken:
        k += 1
    lab = "%s.%d" % (base, k)
    taken.add(lab)
    return lab


def schedule_trace(prog, trace, freq, machine=MACHINE):
    """Schedule one trace. Returns (new program, labels of the scheduled
    pieces, new edge counts, (items, t))."""
    live_in = liveness(prog)  # @line L3
    items = trace_items(prog, trace)
    edges = build_dag(items, live_in)  # @line L4
    t = list_schedule(items, edges, machine)  # @line L7
    order = sorted(range(len(items)), key=lambda v: (t[v], v))
    where = {v: k for k, v in enumerate(order)}
    taken = set(prog.blocks)
    head = trace[0]
    pieces = {}
    extra = {}
    newfreq = {}
    cur, body = head, []
    for v in order:
        it = items[v]
        if it.kind == "op":
            body.append(it.ins)
        elif it.kind == "br":  # @line L8
            comp = [items[u].ins for u in order[where[v] + 1 :] if items[u].kind == "op" and u < v]  # @line L9
            nxt = _fresh(taken, head)
            w = freq.get((trace[it.blk], it.off), 0)
            target = it.off
            if comp:
                target = _fresh(taken, head)  # @line L10
                extra[target] = toyir.Block(list(comp), ("jump", it.off))
                newfreq[(target, it.off)] = w
            c = it.term
            term = ("br", c[1], target, nxt) if c[2] == it.off else ("br", c[1], nxt, target)
            pieces[cur] = toyir.Block(body, term)
            newfreq[(cur, target)] = w
            newfreq[(cur, nxt)] = freq.get((trace[it.blk], trace[it.blk + 1]), 0)
            cur, body = nxt, []
        elif it.kind == "join":  # @line L11
            comp = [items[u].ins for u in order[: where[v]] if items[u].kind == "op" and u > v]  # @line L12
            side = sum(freq.get((p, it.label), 0) for p in toyir.preds(prog)[it.label] if p != trace[it.blk - 1])
            if comp:
                nxt = _fresh(taken, head)
                extra[it.label] = toyir.Block(list(comp), ("jump", nxt))  # @line L13
                newfreq[(it.label, nxt)] = side
            else:
                nxt = it.label
            pieces[cur] = toyir.Block(body, ("jump", nxt))
            newfreq[(cur, nxt)] = freq.get((trace[it.blk - 1], it.label), 0)
            cur, body = nxt, []
        else:
            pieces[cur] = toyir.Block(body, it.term)
            last = trace[-1]
            for s in toyir.succs(prog, last):
                newfreq[(cur, s)] = freq.get((last, s), 0)
    blocks = {}
    for lab, b in prog.blocks.items():  # @line L14
        if lab == head:
            blocks.update(pieces)
        elif lab in trace:
            if lab in extra:
                blocks[lab] = extra.pop(lab)
        else:
            blocks[lab] = b
            for s in toyir.succs(prog, lab):
                newfreq[(lab, s)] = freq.get((lab, s), 0)
    blocks.update(extra)
    return toyir.Program(list(prog.params), blocks), set(pieces), newfreq, (items, t)


def trace_schedule(prog, freq=None, machine=MACHINE):
    """Schedule the whole program trace by trace. Returns (new program,
    list of (trace, items, t) for each trace)."""
    check_input(prog)
    if freq is None:
        freq = static_profile(prog)
    done = set()
    log = []
    while any(lab not in done for lab in prog.blocks):  # @line L1
        trace = pick_trace(prog, freq, done)  # @line L2
        prog, pieces, freq, (items, t) = schedule_trace(prog, trace, freq, machine)
        done |= pieces
        log.append((trace, items, t))
    return prog, log  # @line L15
test_trace_scheduling.py 230 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/trace-scheduling/. The authors are listed in prov/5GWXK6.jsonl.
import copy
import random

import pytest

import toyir
import trace_scheduling as ts

EXAMPLE = """# params: a, b
B0:
  c = b < 5
  s = a - b
  br c B1 B2
B1:
  y = a / b
  jump B3
B2:
  y = a - 1
  jump B3
B3:
  w = b + 1
  v = w * w
  z = y + v
  r = z + s
  ret r
"""
EXAMPLE_FREQ = {("B0", "B1"): 90, ("B0", "B2"): 10, ("B1", "B3"): 90, ("B2", "B3"): 10}


def same_meaning(p, q, inputs):
    return all(toyir.run(p, a) == toyir.run(q, a) for a in inputs)


def grid():
    return [[a, b] for a in range(-6, 7) for b in range(-6, 8)]


def legal(items, edges, t, machine):
    for (u, v), d in edges.items():
        if t[v] < t[u] + d:
            return False
    by_cycle = {}
    for v in t:
        if items[v].unit() != "join":
            by_cycle.setdefault(t[v], []).append(items[v].unit())
    for units in by_cycle.values():
        if len(units) > machine["width"]:
            return False
        for u, m in machine["cap"].items():
            if units.count(u) > m:
                return False
    return True


def brute_optimum(items, edges, machine):
    """Try every start cycle for every item, in index order (a topological
    order), and keep the shortest legal schedule."""
    n = len(items)
    horizon = sum(it.latency() for it in items) + 1
    preds = [[] for _ in range(n)]
    for (u, v), d in edges.items():
        preds[v].append((u, d))
    best = [horizon + 10]

    def rec(j, t):
        if j == n:
            assert legal(items, edges, t, machine)
            best[0] = min(best[0], ts.length(items, t))
            return
        lo = max([t[u] + d for u, d in preds[j]], default=0)
        for c in range(lo, horizon):
            if c + items[j].latency() >= best[0]:
                break
            t[j] = c
            if legal(items, {}, t, machine):
                rec(j + 1, t)
            del t[j]

    rec(0, {})
    return best[0]


def test_example():
    p = toyir.parse(EXAMPLE)
    live = ts.liveness(p)
    assert live["B2"] == {"a", "b", "s"}
    q, log = ts.trace_schedule(p, EXAMPLE_FREQ)
    assert [tr for tr, _, _ in log] == [["B0", "B1", "B3"], ["B0.2", "B2", "B3"]]
    items, t = log[0][1], log[0][2]
    got = {it.ins[1]: t[v] for v, it in enumerate(items) if it.kind == "op"}
    assert got == {"c": 0, "w": 0, "s": 2, "y": 1, "v": 2, "z": 5, "r": 6}
    assert [(it.kind, t[v]) for v, it in enumerate(items) if it.kind != "op"] == [("br", 1), ("join", 2), ("end", 7)]
    assert ts.length(items, t) == 8
    assert q.blocks["B0"].instrs == [("op", "c", "<", "b", 5), ("op", "w", "+", "b", 1)]
    assert q.blocks["B0"].term == ("br", "c", "B0.1", "B0.2")
    assert same_meaning(p, q, grid())
    assert toyir.run(q, [1, 7]) == ("ret", 58)
    assert toyir.run(q, [4, 0]) == ("trap",)


def test_example_lengths_against_blocks():
    p = toyir.parse(EXAMPLE)
    live = ts.liveness(p)
    local = 0
    for lab in ("B0", "B1", "B3"):
        items = ts.trace_items(p, [lab])
        edges = ts.build_dag(items, live)
        t = ts.list_schedule(items, edges)
        assert ts.length(items, t) == brute_optimum(items, edges, ts.MACHINE)
        local += ts.length(items, t)
    assert local == 12
    items = ts.trace_items(p, ["B0", "B1", "B3"])
    edges = ts.build_dag(items, live)
    assert brute_optimum(items, edges, ts.MACHINE) == 8


def test_compensation_is_needed():
    p = toyir.parse(EXAMPLE)
    q, _ = ts.trace_schedule(p, EXAMPLE_FREQ)
    broken = copy.deepcopy(q)
    b = broken.blocks["B0.2"]
    b.instrs = [ins for ins in b.instrs if ins[1] != "s"]
    assert toyir.run(p, [1, 7]) == ("ret", 58)
    with pytest.raises(toyir.UndefinedName):
        toyir.run(broken, [1, 7])


def test_meaning_random_programs():
    rng = random.Random(7)
    for _ in range(120):
        p = toyir.random_program(rng, rng.randint(2, 6), rng.randint(1, 8), True)
        freq = {e: rng.randint(0, 9) for e in toyir.edges(p)}
        q, _ = ts.trace_schedule(p, freq)
        assert toyir.is_acyclic(q)
        inputs = [[rng.randint(-6, 9), rng.randint(-6, 9)] for _ in range(25)]
        assert same_meaning(p, q, inputs)


def test_meaning_with_profiles():
    rng = random.Random(8)
    for _ in range(50):
        p = toyir.random_program(rng, rng.randint(2, 6), rng.randint(2, 8), True)
        inputs = [[rng.randint(-6, 9), rng.randint(-6, 9)] for _ in range(25)]
        for freq in (ts.profile(p, inputs), ts.static_profile(p), None):
            q, _ = ts.trace_schedule(p, freq)
            assert same_meaning(p, q, inputs)


def potential(prog, done):
    memo = {}

    def paths(lab):
        if lab not in memo:
            s = toyir.succs(prog, lab)
            memo[lab] = 1 if lab in done or not s else sum(paths(x) for x in s)
        return memo[lab]

    return sum(paths(lab) for lab in prog.blocks if lab not in done)


def test_motion_rules_and_termination():
    rng = random.Random(9)
    seen = {"exit copy": 0, "entrance copy": 0, "speculation": 0}
    for _ in range(200):
        prog = toyir.random_program(rng, rng.randint(2, 6), rng.randint(2, 8), True)
        freq = {e: rng.randint(0, 9) for e in toyir.edges(prog)}
        done = set()
        phi = potential(prog, done)
        while any(lab not in done for lab in prog.blocks):
            trace = ts.pick_trace(prog, freq, done)
            live = ts.liveness(prog)
            new, pieces, freq, (items, t) = ts.schedule_trace(prog, trace, freq)
            pos = {v: k for k, v in enumerate(sorted(range(len(items)), key=lambda v: (t[v], v)))}
            for b, it in enumerate(items):
                later = range(b + 1, len(items))
                if it.kind == "br":
                    for v in later:
                        w = items[v]
                        if w.kind in ("br", "end"):
                            assert pos[b] < pos[v]
                        elif w.kind == "op" and pos[v] < pos[b]:
                            assert not ts.can_trap(w.ins) and w.defs not in live[it.off]
                            seen["speculation"] += 1
                    if any(items[u].kind == "op" and pos[u] > pos[b] for u in range(b)):
                        seen["exit copy"] += 1
                if it.kind == "join":
                    assert all(pos[u] < pos[b] for u in range(b))
                    assert all(pos[v] > pos[b] for v in later if items[v].kind in ("br", "end"))
                    if any(items[v].kind == "op" and pos[v] < pos[b] for v in later):
                        seen["entrance copy"] += 1
            prog = new
            done |= pieces
            nphi = potential(prog, done)
            assert nphi < phi
            phi = nphi
    assert min(seen.values()) > 20


def test_schedules_against_brute_force():
    rng = random.Random(10)
    checked = 0
    while checked < 60:
        p = toyir.random_program(rng, 3, rng.randint(2, 4), True)
        freq = {e: rng.randint(0, 9) for e in toyir.edges(p)}
        trace = ts.pick_trace(p, freq, set())
        live = ts.liveness(p)
        items = ts.trace_items(p, trace)
        if len(items) > 9:
            continue
        edges = ts.build_dag(items, live)
        assert all(u < v for u, v in edges)
        t = ts.list_schedule(items, edges)
        assert legal(items, edges, t, ts.MACHINE)
        best = brute_optimum(items, edges, ts.MACHINE)
        assert ts.length(items, t) >= best
        local = 0
        for lab in trace:
            one = ts.trace_items(p, [lab])
            local += brute_optimum(one, ts.build_dag(one, live), ts.MACHINE)
        assert best <= local
        checked += 1


def test_input_checks():
    with pytest.raises(ValueError):
        ts.trace_schedule(toyir.parse("B0:\n  x = 1\n  br x B1 B0\nB1:\n  ret x\n"))
    with pytest.raises(ValueError):
        ts.trace_schedule(toyir.parse("# params: p\nB0:\n  x = *p\n  ret x\n"))

History

Fisher developed trace scheduling in his 1979 NYU thesis and the 1981 paper to compact horizontal microcode, where one long instruction word controls many units at once. The copies on the side edges came from a separate bookkeeping phase. Ellis built the Bulldog compiler for VLIW machines on trace scheduling in his Yale thesis, published as a book in 1986. Fisher and others then founded Multiflow, whose TRACE machines (Colwell et al. 1988) and compiler (Lowney et al. 1993) were designed around the method. Chang and Hwu (1988) studied trace selection for C programs in the IMPACT compiler, and the same group then gave superblocks (Hwu et al. 1993). Freudenberger, Gross and Lowney (1994) measured how much compensation code the Multiflow compiler made and how to avoid it.

References

  1. Joseph A. Fisher, Trace scheduling, a technique for global microcode compaction, IEEE Transactions on Computers C-30(7), 1981, 478-490, the selection of traces by expected execution counts, the compaction of a trace as if it were one block, and the bookkeeping phase that copies operations onto the edges that leave or join the trace
  2. Pohua P. Chang and Wen-mei W. Hwu, Trace selection for compiling large C application programs to microcode, Proceedings of the 21st Annual Workshop on Microprogramming and Microarchitecture, 1988, 21-29, Section 3 on trace selection, local compaction and bookkeeping with patch code at the splits and rejoins of a trace, and Section 4 on selection by node weights and arc weights from a seed with the best successor and the best predecessor
  3. P. Geoffrey Lowney, Stefan M. Freudenberger, Thomas J. Karzes, W. D. Lichtenstein, Robert P. Nix, John S. O'Donnell and John C. Ruttenberg, The Multiflow trace scheduling compiler, The Journal of Supercomputing 7(1-2), 1993, 51-142, the production trace scheduling compiler of the Multiflow TRACE machines, with its trace picker, its scheduler and its compensation code
  4. Stefan M. Freudenberger, Thomas R. Gross and P. Geoffrey Lowney, Avoidance and suppression of compensation code in a trace scheduling compiler, ACM Transactions on Programming Languages and Systems 16(4), 1994, 1156-1214, the amount of compensation code in practice, and the methods that avoid code motions that need copies or remove copies that are not needed
  5. Steven S. Muchnick, Advanced Compiler Design and Implementation, Morgan Kaufmann, 1997, Section 17.5 (Trace Scheduling), 569 to 571

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

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
  • a scene preset for the example