Algorithmadvanced
Superblock scheduling
Also called superblock formation.
Forms traces with one entry by tail duplication and schedules each as a block, with no compensation code at side entries.
- Solves
- Instruction scheduling
- 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 superblocks; n = the number of items of one superblock; s = the number of instructions and terminators of the program after formation
- Model
- Word RAM
- Properties
- deterministicofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Wen mei W. Hwu, Scott A. Mahlke, Pohua P. Chang, 1993
Superblock scheduling is a global instruction scheduling method. A superblock is a trace, a likely path through several basic blocks, that control can enter only at its head and can leave at many side exits. The method makes superblocks by tail duplication: when another path joins a trace in the middle, the part of the trace from that point to its end is copied, and the other path goes to the copy. Then each superblock is scheduled as one block. It differs from trace scheduling in where it pays for side entrances. Trace scheduling keeps them and puts compensation code on them after scheduling. Superblock scheduling removes them before scheduling, so it needs no compensation code at entrances and, with the motion rules of this page, none at exits either. The IMPACT group (Hwu et al. 1993) introduced it.
In plain words
A program usually takes the same way through its branches. This method finds that usual way and makes sure that nothing can jump into the middle of it. Where some other path did jump in, the method gives that path its own copy of the rest of the way. Now the usual way is one straight line that can only be left early, never entered late. The scheduler packs that line tightly for a wide machine, and it moves an instruction past an early exit only when the exit does not need the instruction and the instruction cannot fail. So no repair code is needed. The price is the copied code, which makes the program larger.
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, or a shift by an amount outside 0 to 63). The machine is the one of trace scheduling: 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 superblocks. Loops are not handled here. A real compiler forms superblocks inside a loop body, often after unrolling, or uses software pipelining.
The algorithm
SUPERBLOCK-SCHEDULE(P, freq)- 1
done <- empty; S <- empty list - 2
while some block of P is not in done do - 3
T = b1 .. bk <- the seed of highest count, grown along edges that are most likely at both ends, never into or backward past the entry - 4
j <- the least i >= 2 such that bi has a predecessor other than b(i-1); if there is none, go to L7 - 5
for i <- j to k do make a copy ci of bi whose edges to a block bm with m >= j go to cm - 6
for i <- j to k do send each edge from a predecessor p != b(i-1) of bi to ci - 7
append T to S; add b1 .. bk to done - 8
for each superblock T in S do - 9
live <- the live-in sets of the current P - 10
D <- the dependence DAG of the items of T: data edges, and an edge from each item to the end item - 11
add an edge from each side exit B to each later branch, and to each later operation that may trap or writes a name of live(off(B)) - 12
add an edge to each side exit B from each earlier operation that may trap or writes a name of live(off(B)) - 13
t <- a list schedule of D by height; order the items by (t, original position) - 14
emit the items in that order, starting a new block after each side exit; the first piece keeps the label b1 - 15
return P
Formation (lines L1 to L7). Line L3 picks a trace among the blocks not yet in a superblock, as in trace scheduling. The seed is the block of highest count, the larger of the sums of its incoming and its outgoing edge counts. The trace grows forward from its last block to the successor of the largest edge count, but only if is also the predecessor of with the largest count and is not done. It grows backward in the same way. It never takes the entry block except as its head. Chang and Hwu (1988) describe this growth with a best successor and a best predecessor. Line L4 finds the first side entrance, the first block after the head with a second predecessor. Lines L5 and L6 copy the tail . A copy keeps the instructions of . Its edges into the tail go to the copies, so the copies never become new side entrances. Every side edge into moves to . After this, the trace edge from is the only edge into , and is a superblock. The copies are new blocks that are not done, so later rounds put them in superblocks of their own.
Items (line L10). In the original order, the items of a superblock are: the instructions of each block, called operations; a side exit item for each br of , , whose other target leaves the superblock; and the end item, the terminator of . A jump from to gives no item.
Dependences (lines L10 to L12). The data edges are the 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. Line L11 keeps the side exits in order, and lets an operation from below a side exit move above it only if the operation cannot trap and its result is dead on the exit. Such a motion is safe speculation. Line L12 is the rule that replaces compensation code: an operation from above a side exit moves below it only under the same two conditions. Then a run that leaves at the exit does not need the operation, and it is correct that the operation did not run. Trace scheduling lets such an operation move and puts a copy on the exit edge instead.
Emission (line L14). The scheduled items run in the order of , so items with a delay 0 between them can share a cycle. A new block starts after each side exit and ends with the old br on the same condition, to the next piece and to the old exit target. The other labels of the superblock disappear: by tail duplication, nothing else jumps to them.
Example
Take the program of the trace scheduling page, with parameters a and b, and the profile 90 for and , and 10 for and :
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
Formation. Line L3 picks , the block of highest count, and grows it to . The block has a second predecessor, , so line L4 gives . Lines L5 and L6 make the copy B3.1 of and send the edge to it. The second round picks and grows it to , B3.1, which has no side entrance. The formed program has the two superblocks below, and four more instructions than the input.
| round | trace | first side entrance | copies | edge counts after the round |
|---|---|---|---|---|
| 1 | , from | B3.1 |
: 90, B3.1: 10 |
|
| 2 | , B3.1 |
none | none | unchanged |
Scheduling the first superblock. Line L9 gives . The items, with their units, latencies, heights and cycles, are:
| index | item | unit | latency | height | cycle |
|---|---|---|---|---|---|
| 0 | c = b < 5 |
alu | 1 | 7 | 0 |
| 1 | s = a - b |
alu | 1 | 6 | 1 |
| 2 | side exit, off | br | 1 | 6 | 1 |
| 3 | y = a / b |
mul | 3 | 6 | 2 |
| 4 | w = b + 1 |
alu | 1 | 7 | 0 |
| 5 | v = w * w |
mul | 3 | 6 | 3 |
| 6 | z = y + v |
alu | 1 | 3 | 6 |
| 7 | r = z + s |
alu | 1 | 2 | 7 |
| 8 | ret r |
br | 1 | 1 | 8 |
Line L11 adds the edge from the exit 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 . Line L12 adds the edge from s = a - b to the exit, since s is live at . The list scheduler gives:
| cycle | ready, by height | issued |
|---|---|---|
| 0 | c, w, s |
c, w |
| 1 | s, exit, v (all of height 6) |
s, exit |
| 2 | y, v |
y (one multiply unit) |
| 3 | v |
v |
| 4, 5 | none | none |
| 6 | z |
z |
| 7 | r |
r |
| 8 | ret r |
ret r |
The length is cycles. The optimum for this DAG is 8: v and s at cycle 1, the exit and y at cycle 2, z at 5. The list scheduler breaks the tie at cycle 1 by original position and fills the cycle with s and the exit, so the two multiplies start one cycle later. Trace scheduling reaches 8 cycles on the same path with this list scheduler, because it moves s below the exit and puts a copy of s on the exit edge. Line L12 forbids that motion here. Block by block, the same path takes cycles.
The second superblock. , B3.1 is one block of six items. Its list schedule puts y and w at cycle 0, v at 1, z at 4, r at 5 and ret r at 6, a length of 7, which is optimal. The output is:
B0:
c = b < 5
w = b + 1
s = a - b
br c B0.1 B2
B0.1:
y = a / b
v = w * w
z = y + v
r = z + s
ret r
B2:
y = a - 1
w = b + 1
v = w * w
z = y + v
r = z + s
ret r
The operation w = b + 1 moved above the exit by speculation. It also runs on the rare path, where its value is computed again in B2. No other code was added: the output has 12 instructions, the same as the formed program, while the trace scheduling output has 10. On both the input and the output take the rare path and return 58. On both return 13, and on both trap.
Correctness
Theorem. On every input, the output of SUPERBLOCK-SCHEDULE returns the same value as the input program, or traps exactly when the input program traps. Formation stops, and scheduling adds no instruction.
The full proof is in the proof file. For formation, each block of the new program maps to a block of the old one with the same instructions and the same targets after the map, so the two programs run in step. After the copies, the only edge into , , is from , and later rounds keep this. Formation stops because the number of paths from the blocks not yet done drops by at least 1 in each round, although the copies are new blocks. For scheduling, the edges keep the order of any two items that read or write the same name, and the order of the exits. An operation that crosses an exit in either direction cannot trap and writes only a name that is dead on the exit (lines L11 and L12). So a run that leaves at an exit sees the same values of the live names as before, a run that reaches the end item sees the same values of all names, and a trap happens in both runs or in neither. An induction over the blocks in reverse topological order finishes the proof.
Proof: Superblock formation and superblock scheduling keep the meaning of the program and stopfull
We prove three things about SUPERBLOCK-SCHEDULE. Tail duplication (lines L4 to L6) keeps the outcome of every run and gives each trace one entry. The formation loop (lines L2 to L7) stops. Scheduling one superblock (lines L9 to L14) keeps the outcome of every run, and adds no instruction. The rules of code motion of lines L11 and L12 are exactly what the scheduling proof needs.
Setup
The program has an acyclic control flow graph and only const, copy and op instructions. Every value is an integer. A run 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. The outcome of a run is its returned value or the trap. is the set of names that some path from the start of block reads before it writes them, the least solution of the usual backward equations, which line L9 computes in one pass in reverse topological order.
An operation may trap if it is a division or remainder whose right operand is not a nonzero constant, or a shift whose amount is not a constant from 0 to 63. Every operation that traps on some run may trap.
Part 1. Tail duplication
Line L3 gives a trace , a path of blocks that are in no superblock yet. If some with has a predecessor other than (a side entrance), let be the least such (line L4). Line L5 makes a new block for each with the instructions of , and the terminator of in which every target with is replaced by . Line L6 replaces, in the terminator of every predecessor of with , the target by . Call the result , and let map each to and every other label to itself.
Lemma 1. For every block of , the block of has the same instructions, and its terminator is the terminator of with applied to each target. So and have the same outcome on every input.
Proof. For a copy this is the construction of line L5. For any other block, line L6 only renames a target to , and . Now run and on the same input. By induction on the number of blocks run, after each block the runs are at labels and with the same state: the two blocks run the same instructions on the same state, so they trap together or reach the same state, and the terminators read the same name and take the targets in the same position, which maps one to the other. The entry is not a copy, so both runs start at the same label.
Lemma 2. In , for every , the only predecessor of is .
Proof. For , by the choice of , had no other predecessor, and lines L5 and L6 add no edge into : a copy only targets copies and blocks outside the tail. For , line L6 moved every edge from a predecessor other than to , and a copy never targets . The edge from to is not renamed, since line L6 renames the target only in predecessors other than , and renames a target of only to .
Lemma 3. Once is a superblock, it stays one: in every later program of the loop, for has the one predecessor .
Proof. A later step of line L6 renames only targets that are blocks of the later trace, which are in no superblock yet, so it never removes or adds an edge into . A later step of line L5 copies a block that is in no superblock. If had an edge to with , then by induction, but is in a superblock. So the copies add no edge into .
Lemma 4. The formation loop stops. For a program and the set of blocks in superblocks, let if is done or has no successor, and otherwise over the successors of . Let . Each step of the loop makes smaller by at least 1, so the loop stops after at most steps of the input.
Proof. Write before the step and after it, when the blocks of are done. We show for every block of that is not done after the step, by induction in reverse topological order of . If has no successor, both are 1. Otherwise was not done before the step (copies are made only of blocks that were not done), and by Lemma 1 the successors of map one to one under to the successors of . A successor that is done after the step has , and any other successor has by induction. So .
The blocks not done after the step are the old blocks not done, minus , plus the copies . So
since and . Without a side entrance there are no copies, and the bound is the same.
So formation stops, keeps the outcome of every run (Lemma 1), keeps the graph acyclic (a copy only has edges to copies of later trace blocks and to blocks after , and an edge renamed by line L6 goes to a copy whose original came after its source), and gives superblocks that cover all blocks, each with a single entry at its head (Lemmas 2 and 3). The entry block is never with , because line L3 does not grow a trace into the entry or backward past it.
Part 2. Scheduling one superblock
Fix a superblock of the current program . Its items are, in index order: the instructions of each block, called operations; for , a branch when ends with a br to two labels, one of them and the other its exit target ; and the end item, the terminator of . A branch or the end item reads its condition or its returned name. Two items conflict if one of them writes a name that the other reads or writes.
By Lemmas 2 and 3, is not a block of the superblock: would close a cycle, is the trace target, and would give a second predecessor.
Say that an operation stays at a branch if may trap or writes a name of . The DAG has these edges , all with and a delay :
- (E1) data: from the last writer of before to each reader of , delay the latency of the writer; from the last writer of before to a writer of , delay 1; from each reader of after the last writer of before to a writer of , delay 0;
- (E2) from a branch to each later branch, to the end item, and to each later operation that stays at (line L11);
- (E3) from each operation that stays at to each later branch (line L12);
- (E4) from each item to the end item.
Line L13 gives each item a cycle with for each edge. The order sorts the items by , and means that is before in . Line L14 cuts after each branch: the first piece takes the label , the other pieces get new labels, a piece that ends at a branch ends with br on the same condition to the next piece and to , in the positions of the old targets, and the last piece ends with the end item. The blocks are removed. All other blocks stay as they are. Call the result .
Lemma 5. Order. (a) Each edge of has . (b) If conflict, then .
Proof. (a) and , so . (b) By (a) it is enough to find a path from to in . Let be the name of the conflict. The writers of form a path in index order by the output edges of (E1). If writes and reads, the last writer of before has , and the path is . If reads and writes, the first writer of after has , reads after the last writer before , so (E1) has , and the path goes on along the writers to . If both write, the writers path joins them.
Lemma 6. Shape. (a) The branches and the end item are in index order in , and the end item is last. (b) If an operation and a branch are in a different order in than in index order, then does not stay at : it cannot trap, and it writes no name of .
Proof. (a) is (E2) and (E4) with Lemma 5(a). (b) If and stayed at , (E2) would give . If and stayed at , (E3) would give .
So an operation moves above a branch only by speculation that is safe, and below a branch only when it is not needed on the exit and cannot trap. This is why no copy is needed.
The two runs. Run and from the label , with states and that agree on . runs the items in index order until a branch leaves or the end item. runs the items in the order until a branch leaves or the end item. Call the items that runs, a prefix of .
For an item and a name that it reads, let be the last writer of among , or "none". The ideal value of an operation is its result when all operations run in index order as straight-line code from , with a special value for an operation that traps or reads . computes exactly the ideal values for the items it runs.
Lemma 7. The same values. Every item of reads the ideal values of its operands, and every operation of that does not trap computes its ideal value.
Proof. By induction along . Let read . If exists, then by Lemma 5(b), so before , since is a prefix of . Any other writer of in has , and then , or , and then , by Lemma 5(b). So the last writer of before in is , and reads by induction ( did not trap, or the run would have stopped). If is none, every writer of in comes after , so reads . The trace path reads at with no write before it, so and .
Lemma 8. One superblock. Exactly one of these holds.
- Both runs trap.
- Both leave at the same branch to , with states that agree on .
- Both reach the end item. If it is
ret a, both return the same value. Otherwise both go to the same successor of , with states that agree on its live set.
Proof. leaves at a branch without a trap. Before in , meets: branches below , which are in index order (Lemma 6(a)) and read the same values as in (Lemma 7), so they stay on the superblock; operations below that are before in , which ran in without a trap and get the same operands; and operations above that are before in , which cannot trap by Lemma 6(b). So reaches , reads the same condition, and leaves to . Take . ran the writers of among the items below . ran the same writers: by Lemma 6(b), no operation that crossed writes . Their order is the same by Lemma 5(b), so the last writer is the same, and it computed the same value by Lemma 7. If there is no such writer, both states keep the value at , and because the path through to reads first. This is case 2.
reaches the end item without a trap. The same argument with the end item for . By Lemma 6(a), is all of , so both runs ran all items, with the same last writer of each name. The end item reads the same value. If it is ret, both return it. Otherwise both take the same target with states that agree on every name, and in particular on its live set. This is case 3.
traps at an operation . Then may trap. Suppose that does not trap. Then it leaves at a branch or reaches the end item. The branches before in stayed on the superblock in with the ideal values, so they stay in too, and leaves (or is the end) in too. As trapped first, . Since may trap, it stays at , so (E3), or (E4) for the end item, gives , and . By Lemma 7, got its ideal operands in , the values with which it traps in . So traps, a contradiction. In the first two cases, ran only operations that do not trap. So this is case 1, and in cases 2 and 3 does not trap either.
Theorem 9. and have the same outcome on every input, and has exactly as many instructions as .
Proof. The labels of are the labels of other than , plus the new pieces, which only pieces of the same superblock reach. By Lemma 2 and Lemma 3, the only edge into , , is from , so no other block of refers to a removed label. We show, for each label of other than , that runs of and from with states that agree on have the same outcome, by induction on in reverse topological order of . If , both have the same block at : they trap together, return the same value, or go to the same successor with states that agree on its live set, and that successor is not with (it would be , which is not ) and comes later. If , Lemma 8 applies; in case 2, is not in the superblock and comes after , and in case 3 the successor of comes after . The entry of is or not in the superblock, so it stays the entry. Line L14 puts every operation in exactly one piece, so no instruction is added or removed.
Lemma 10. The rest of the loop. is acyclic, has only const, copy and op instructions, and every other superblock is still a path with a single entry in .
Proof. The pieces form a chain, and the edges out of the chain go to the exit targets and to the successors of , which come after or after some in ; a cycle through the chain would give a cycle in . The instructions are the old ones. Scheduling changes only the blocks of this superblock and keeps the exit targets, so the edges into the blocks of other superblocks are the same as before.
Summary
Formation keeps the outcome (Lemma 1), stops (Lemma 4), and gives superblocks with one entry each (Lemmas 2 and 3). Each scheduling step keeps the outcome and the instruction count (Theorem 9) and keeps the other superblocks valid (Lemma 10). So SUPERBLOCK-SCHEDULE stops, its output has the same outcome as its input on every input, and all its new instructions come from tail duplication, none from scheduling.
Complexity
Let be the number of items of one superblock, the number of instructions and terminators of the program after formation, the number of names and the number of superblocks.
- Lines L3 to L7. The counts, the growth and the copies look at each edge and each instruction a constant number of times: per round.
- Line L9. One backward pass in reverse topological order solves the liveness equations of an acyclic graph, with sets of at most names: .
- Lines L10 to L12. The DAG has edges, and each one is made in : .
- Line L13. Heights in one pass over the edges, then a list schedule with a ready queue: , as the number of cycles is at most the sum of the latencies, . The Python code scans all items for each choice, which is .
- Line L14. for the pieces and for the rebuild.
So the run costs time and space. Tail duplication can make exponential in the number of blocks of the input, since a tail copied in one round can be copied again in later rounds. Real compilers limit the length of a superblock and the amount of copied code.
Properties
- Correct for every input. The profile only chooses the superblocks. A bad profile makes the code slower, never wrong.
- No compensation code. All new instructions come from tail duplication, before scheduling. Scheduling only reorders.
- Simpler than trace scheduling. There are no entrances in a superblock, so the scheduler needs no entrance items, no entrance copies and no rejoin blocks. The copies also make a superblock a better target for classic optimizations, since no other path reaches its middle.
- The optimum is never worse than block by block. The best schedule of a superblock is at most the sum of the best schedules of its blocks. The list scheduler is a heuristic, so this holds for the optimum, not for every list schedule.
- Less freedom at exits. An operation whose result is live on an exit cannot move below it, so some schedules of trace scheduling are not possible, as for
sin the example. - Code growth. Each side entrance copies the whole tail after it, also code that is not on the hot path.
Variants and improvements
- Superblock optimizations (Hwu et al. 1993). Since a superblock has one entry, the compiler can unroll superblock loops, rename registers and expand accumulators and induction variables inside it before scheduling, to remove dependences.
- Speculation with hardware help. With instructions that do not trap, such as non-trapping loads, the scheduler can also move operations that may trap above an exit. The IMPACT papers compare such scheduling models (Chang et al. 1991).
- Hyperblocks (Mahlke et al. 1992). If-conversion turns several paths into one block with one entry and predicated instructions, so that a rare path no longer cuts the hot one.
- Better traces. Path profiles give the real hot paths instead of a chain of locally likely edges. A tracing JIT records a hot path at run time and compiles it as a superblock-like trace with one entry and many exits.
- Loops. The superblock stops at a back edge. Loop unrolling gives longer superblocks, and software pipelining overlaps iterations instead.
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, when a simple scheduler matters more than code size. It suits compilers that run classic optimizations on the hot path too, since a superblock is easier to optimize than a trace with entrances. Prefer trace scheduling when code size is tight, or when moving an operation below an exit matters. On an out-of-order processor the gain is smaller. For loops with many iterations, use iterative modulo scheduling.
Pitfalls
- Moving the trace edge to the copy. If line L6 sends every edge into to , the edge from also goes to the copy, and is no longer reached from the trace. Move only the edges from predecessors .
- Copies that point back into the tail. If line L5 keeps the targets of in , the copy jumps to , which gets a new side entrance from . The copy edges into , , must go to .
- Starting the copy at the last side entrance. If line L4 takes the greatest such , the earlier side entrances stay in the superblock. Take the least , so that the copied tail covers all of them.
- Moving a live write below an exit. If line L12 is left out, as in a trace scheduler that relies on copies, an operation can move below an exit whose path reads its result, and the rare path reads an old value. In the example,
swould move below the exit and the run on would readsbefore any write. Keep line L12, or add compensation code. - Speculating an operation that can trap. If line L11 adds edges only for live names, a division from below an exit can move above it, and a run that leaves at that exit with a divisor of 0 traps where the input did not. Line L11 must also add the edge for every operation that may trap.
- Stale live sets. If line L9 runs once on the input, the copies have no live sets and the exit targets of later superblocks have the wrong ones. Compute live-in sets on the current program.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/superblock-scheduling/. The authors are listed in prov/WWP2JP.jsonl.
"""Superblock formation by tail duplication and superblock scheduling, on
the toy IR.
superblock_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).
Formation. While some block is in no superblock, pick a trace among those
blocks (the block of highest count, grown along edges that are the most
likely way out of one end and the most likely way into the other end). If
some block b_j, j >= 2, of the trace has a predecessor other than b_(j-1),
copy the tail b_j .. b_k and send every such side edge to the copy. Then
the trace has one entry, at its head: it is a superblock. The copies are new
blocks and later get superblocks of their own.
Scheduling. Each superblock is list scheduled as one block. Its only side
paths are side exits, so no compensation code is needed if an operation
moves above a side exit only when it cannot trap and its result is dead on
the exit, and moves below a side exit only under the same two conditions.
The machine: each cycle issues at most `width` items, at most cap[u] of
unit u. A multiply, divide or remainder uses "mul" (latency 3), a branch or
the last terminator "br" (latency 1), and the other operations "alu"
(latency 1). The scheduled superblock runs its items in the order (cycle,
original position), so a dependence with delay 0 lets two items share a
cycle.
Cost: with s instructions and terminators, N names, n items in a
superblock and m superblocks, O(m (s N + n^2)) time besides the Python
list scheduler, which is O(n^3) per superblock. Tail duplication can make s
grow exponentially in the number of blocks in the worst case.
"""
import toyir
MACHINE = {"width": 2, "cap": {"mul": 1, "br": 1}}
LATENCY = {"alu": 1, "mul": 3, "br": 1}
class Item:
"""One item of a superblock: an operation ("op"), a side exit ("br")
or the terminator of the last block ("end")."""
def __init__(self, kind, blk, ins=None, term=None, off=None):
self.kind = kind
self.blk = blk
self.ins = ins
self.term = term
self.off = off
if kind == "op":
self.uses = toyir.uses(ins)
self.defs = toyir.defs(ins)
else:
self.uses = toyir.term_uses(term)
self.defs = None
def unit(self):
if self.kind != "op":
return "br"
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("superblock 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 topological_order(prog):
order, seen = [], set()
for root in prog.blocks:
if root in seen:
continue
seen.add(root)
stack = [(root, iter(toyir.succs(prog, root)))]
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))))
order.reverse()
return order
def liveness(prog):
"""live_in[label]: the names that some path from the start of the block
reads before it writes them. One backward pass in reverse topological
order, which is exact on an acyclic graph."""
live_in = {}
for lab in reversed(topological_order(prog)):
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))
live_in[lab] = live
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."""
bf = {lab: 0.0 for lab in prog.blocks}
bf[prog.entry] = 1.0
freq = {}
for lab in topological_order(prog):
ss = toyir.succs(prog, lab)
for s in ss:
freq[(lab, s)] = bf[lab] / len(ss)
bf[s] += freq[(lab, s)]
return freq
# ---------------------------------------------------------------- formation
def pick_trace(prog, freq, done):
"""The seed is the block outside every superblock 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 in no superblock. The entry
block is always the head of its trace."""
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 b == prog.entry 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
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 _retarget(term, old, new):
if term[0] == "jump":
return ("jump", new) if term[1] == old else term
if term[0] == "br":
return ("br", term[1], new if term[2] == old else term[2], new if term[3] == old else term[3])
return term
def tail_duplicate(prog, trace, freq):
"""Copy the trace from its first side entrance to its end and send the
side entrances to the copy. Returns (new program, new edge counts)."""
pr = toyir.preds(prog)
k = len(trace)
side = [i for i in range(1, k) if any(p != trace[i - 1] for p in pr[trace[i]])] # @line L4
if not side:
return prog, dict(freq)
j = side[0]
taken = set(prog.blocks)
copy_of = {trace[i]: _fresh(taken, trace[i]) for i in range(j, k)}
blocks = {lab: toyir.Block(list(b.instrs), b.term) for lab, b in prog.blocks.items()}
for i in range(j, k): # @line L5
lab = trace[i]
term = prog.blocks[lab].term
# A copy is never the trace predecessor of a tail block, so every
# edge from a copy into the tail goes to the copy of the target.
for s in toyir.succs(prog, lab):
if s in copy_of:
term = _retarget(term, s, copy_of[s])
blocks[copy_of[lab]] = toyir.Block(list(prog.blocks[lab].instrs), term)
for i in range(j, k):
lab = trace[i]
for p in pr[lab]:
if p != trace[i - 1]:
blocks[p].term = _retarget(blocks[p].term, lab, copy_of[lab]) # @line L6
new = toyir.Program(list(prog.params), blocks)
return new, _split_counts(prog, new, trace, j, copy_of, freq)
def _split_counts(prog, new, trace, j, copy_of, freq):
"""Edge counts for the program after tail duplication. The out-counts
of a tail block are split between it and its copy in the ratio of the
flow that now enters the copy to the flow that entered the block."""
orig = {c: lab for lab, c in copy_of.items()}
pr_old = toyir.preds(prog)
pr_new = toyir.preds(new)
ratio = {}
def weight(a, b):
a0, b0 = orig.get(a, a), orig.get(b, b)
w = freq.get((a0, b0), 0)
if a0 in ratio:
w = w * ratio[a0] if a in orig else w * (1 - ratio[a0])
return w
for i in range(j, len(trace)):
lab = trace[i]
total = sum(freq.get((p, lab), 0) for p in pr_old[lab])
inflow = sum(weight(p, copy_of[lab]) for p in pr_new[copy_of[lab]])
ratio[lab] = min(1, inflow / total) if total else 0
return {(a, b): weight(a, b) for a, b in toyir.edges(new)}
def form_superblocks(prog, freq):
"""Returns (program, list of superblocks, edge counts). Each
superblock is a path of blocks whose only entry is its head."""
done = set() # @line L1
superblocks = []
while any(lab not in done for lab in prog.blocks): # @line L2
trace = pick_trace(prog, freq, done) # @line L3
prog, freq = tail_duplicate(prog, trace, freq)
superblocks.append(trace) # @line L7
done |= set(trace)
return prog, superblocks, freq
# ---------------------------------------------------------------- scheduling
def superblock_items(prog, sb):
"""The items of the superblock in their original order."""
items = []
for i, lab in enumerate(sb):
b = prog.blocks[lab]
for ins in b.instrs:
items.append(Item("op", i, ins=ins))
t = b.term
if i == len(sb) - 1:
items.append(Item("end", i, term=t))
elif t[0] == "br" and t[2] != t[3]:
off = t[3] if t[2] == sb[i + 1] else t[2]
items.append(Item("br", i, term=t, off=off))
return items
def _stays(it, live):
"""An operation must stay on its side of a side exit if it can trap or
if it writes a name that is live on the exit."""
return can_trap(it.ins) or it.defs in live
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":
continue
live = live_in[it.off]
for v in range(b + 1, len(items)): # @line L11
w = items[v]
if w.kind != "op" or _stays(w, live):
add(b, v, 0)
for u in range(b): # @line L12
w = items[u]
if w.kind == "op" and _stays(w, live):
add(u, b, 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()
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
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)))
def schedule_superblock(prog, sb, machine=MACHINE):
"""Schedule one superblock. Returns (new program, labels of its
pieces, (items, t))."""
live_in = liveness(prog) # @line L9
items = superblock_items(prog, sb)
edges = build_dag(items, live_in) # @line L10
t = list_schedule(items, edges, machine) # @line L13
order = sorted(range(len(items)), key=lambda v: (t[v], v))
taken = set(prog.blocks)
head = sb[0]
pieces = {}
cur, body = head, []
for v in order: # @line L14
it = items[v]
if it.kind == "op":
body.append(it.ins)
elif it.kind == "br":
nxt = _fresh(taken, head)
c = it.term
term = ("br", c[1], it.off, nxt) if c[2] == it.off else ("br", c[1], nxt, it.off)
pieces[cur] = toyir.Block(body, term)
cur, body = nxt, []
else:
pieces[cur] = toyir.Block(body, it.term)
blocks = {}
for lab, b in prog.blocks.items():
if lab == head:
blocks.update(pieces)
elif lab not in sb:
blocks[lab] = b
return toyir.Program(list(prog.params), blocks), list(pieces), (items, t)
def superblock_schedule(prog, freq=None, machine=MACHINE):
"""Form superblocks, then schedule each one. Returns (new program,
list of superblocks, list of (items, t) for each superblock)."""
check_input(prog)
if freq is None:
freq = static_profile(prog)
prog, superblocks, _ = form_superblocks(prog, freq)
log = []
for sb in superblocks: # @line L8
prog, _, sched = schedule_superblock(prog, sb, machine)
log.append(sched)
return prog, superblocks, log # @line L15
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_superblock_scheduling.py 248 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/superblock-scheduling/. The authors are listed in prov/WWP2JP.jsonl.
import random
import pytest
import toyir
import superblock_scheduling as sbs
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 ninstrs(prog):
return sum(len(b.instrs) for b in prog.blocks.values())
def legal(items, edges, t, machine):
for (u, v), d in edges.items():
if u in t and v in t and t[v] < t[u] + d:
return False
by_cycle = {}
for v in t:
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], sbs.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_formation():
p = toyir.parse(EXAMPLE)
f, superblocks, freq = sbs.form_superblocks(p, EXAMPLE_FREQ)
assert superblocks == [["B0", "B1", "B3"], ["B2", "B3.1"]]
assert f.blocks["B2"].term == ("jump", "B3.1")
assert f.blocks["B3.1"].instrs == f.blocks["B3"].instrs
assert toyir.preds(f)["B3"] == ["B1"]
assert freq[("B2", "B3.1")] == 10 and freq[("B1", "B3")] == 90
assert same_meaning(p, f, grid())
def test_example_schedule():
p = toyir.parse(EXAMPLE)
q, superblocks, log = sbs.superblock_schedule(p, EXAMPLE_FREQ)
items, t = log[0]
got = {it.ins[1]: t[v] for v, it in enumerate(items) if it.kind == "op"}
assert got == {"c": 0, "s": 1, "y": 2, "w": 0, "v": 3, "z": 6, "r": 7}
assert [(it.kind, t[v]) for v, it in enumerate(items) if it.kind != "op"] == [("br", 1), ("end", 8)]
assert sbs.length(items, t) == 9
f, _, _ = sbs.form_superblocks(p, EXAMPLE_FREQ)
live = sbs.liveness(f)
assert live["B2"] == {"a", "b", "s"}
assert brute_optimum(items, sbs.build_dag(items, live), sbs.MACHINE) == 8
assert list(q.blocks) == ["B0", "B0.1", "B2"]
assert q.blocks["B0"].instrs == [("op", "c", "<", "b", 5), ("op", "w", "+", "b", 1), ("op", "s", "-", "a", "b")]
assert q.blocks["B0"].term == ("br", "c", "B0.1", "B2")
assert sbs.length(*log[1]) == 7
assert ninstrs(q) == ninstrs(f)
assert same_meaning(p, q, grid())
assert toyir.run(q, [1, 7]) == ("ret", 58)
assert toyir.run(q, [4, 2]) == ("ret", 13)
assert toyir.run(q, [4, 0]) == ("trap",)
def test_formation_on_random_programs():
rng = random.Random(11)
for _ in range(150):
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)}
f, superblocks, _ = sbs.form_superblocks(p, freq)
assert toyir.is_acyclic(f)
assert f.entry == p.entry and any(sb[0] == p.entry for sb in superblocks)
assert sorted(lab for sb in superblocks for lab in sb) == sorted(f.blocks)
pr = toyir.preds(f)
for sb in superblocks:
for i in range(1, len(sb)):
assert pr[sb[i]] == [sb[i - 1]]
assert sb[i] in toyir.succs(f, sb[i - 1])
inputs = [[rng.randint(-6, 9), rng.randint(-6, 9)] for _ in range(20)]
assert same_meaning(p, f, inputs)
def test_meaning_random_programs():
rng = random.Random(12)
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, _, _ = sbs.superblock_schedule(p, freq)
assert toyir.is_acyclic(q)
f, _, _ = sbs.form_superblocks(p, freq)
assert ninstrs(q) == ninstrs(f)
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(13)
for _ in range(35):
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 (sbs.profile(p, inputs), sbs.static_profile(p), None):
q, _, _ = sbs.superblock_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_formation_stops():
rng = random.Random(14)
for _ in range(200):
prog = toyir.random_program(rng, 3, rng.randint(2, 9), 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 = sbs.pick_trace(prog, freq, done)
prog, freq = sbs.tail_duplicate(prog, trace, freq)
done |= set(trace)
nphi = potential(prog, done)
assert nphi < phi
phi = nphi
def test_motion_rules():
rng = random.Random(15)
seen = {"above": 0, "below": 0}
for _ in range(120):
p = toyir.random_program(rng, rng.randint(2, 6), rng.randint(2, 8), True)
freq = {e: rng.randint(0, 9) for e in toyir.edges(p)}
prog, superblocks, _ = sbs.form_superblocks(p, freq)
for sb in superblocks:
live = sbs.liveness(prog)
new, _, (items, t) = sbs.schedule_superblock(prog, sb)
pos = {v: k for k, v in enumerate(sorted(range(len(items)), key=lambda v: (t[v], v)))}
for b, it in enumerate(items):
if it.kind != "br":
continue
for v, w in enumerate(items):
if w.kind != "op":
assert (v < b) == (pos[v] < pos[b])
continue
if (v < b) != (pos[v] < pos[b]):
assert not sbs.can_trap(w.ins) and w.defs not in live[it.off]
seen["above" if v > b else "below"] += 1
prog = new
assert min(seen.values()) > 20
def test_schedules_against_brute_force():
rng = random.Random(16)
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)}
f, superblocks, _ = sbs.form_superblocks(p, freq)
sb = superblocks[0]
live = sbs.liveness(f)
items = sbs.superblock_items(f, sb)
if len(items) > 9:
continue
edges = sbs.build_dag(items, live)
assert all(u < v for u, v in edges)
t = sbs.list_schedule(items, edges)
assert legal(items, edges, t, sbs.MACHINE)
best = brute_optimum(items, edges, sbs.MACHINE)
assert sbs.length(items, t) >= best
local = 0
for lab in sb:
one = sbs.superblock_items(f, [lab])
local += brute_optimum(one, sbs.build_dag(one, live), sbs.MACHINE)
assert best <= local
checked += 1
def test_input_checks():
with pytest.raises(ValueError):
sbs.superblock_schedule(toyir.parse("B0:\n x = 1\n br x B1 B0\nB1:\n ret x\n"))
with pytest.raises(ValueError):
sbs.superblock_schedule(toyir.parse("# params: p\nB0:\n x = *p\n ret x\n"))
one = toyir.parse("# params: a\nB0:\n x = a + 1\n ret x\n")
q, superblocks, _ = sbs.superblock_schedule(one)
assert superblocks == [["B0"]] and toyir.run(q, [4]) == ("ret", 5)
History
Fisher introduced trace scheduling in 1981, with a bookkeeping phase that copies operations onto the side entrances and exits of a trace. Chang and Hwu (1988) studied trace selection for C programs in the IMPACT compiler at the University of Illinois. In 1991 Chang, Mahlke, Chen, Warter and Hwu used superblocks in the IMPACT-I C compiler to measure scheduling models, issue rates and load latencies for multiple-issue processors. Hwu and eleven coauthors gave the full account in 1993: trace selection, tail duplication, a set of optimizations on superblocks, and superblock scheduling, with large speedups on a 4-issue processor. Mahlke and others extended the idea to hyperblocks with predication in 1992. The idea of a region with one entry and many exits reappeared in dynamic optimizers and tracing JIT compilers.
References
- Wen-mei W. Hwu, Scott A. Mahlke, William Y. Chen, Pohua P. Chang, Nancy J. Warter, Roger A. Bringmann, Roland G. Ouellette, Richard E. Hank, Tokuzo Kiyohara, Grant E. Haab, John G. Holm and Daniel M. Lavery, The superblock, an effective technique for VLIW and superscalar compilation, The Journal of Supercomputing 7(1-2), 1993, 229-248, the definition of a superblock as a trace with one entry and one or more exits, its formation by trace selection and tail duplication, the superblock optimizations, and superblock scheduling
- Pohua P. Chang, Scott A. Mahlke, William Y. Chen, Nancy J. Warter and Wen-mei W. Hwu, IMPACT, an architectural framework for multiple-instruction-issue processors, Proceedings of the 18th Annual International Symposium on Computer Architecture, 1991, 266-275, the experiments on the code scheduling model, the issue rate, the load latency and the limits of the function units for code from the IMPACT-I C compiler
- 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 4 on trace selection by node weights and arc weights from a seed with the best successor and the best predecessor
- Scott A. Mahlke, David C. Lin, William Y. Chen, Richard E. Hank and Roger A. Bringmann, Effective compiler support for predicated execution using the hyperblock, Proceedings of the 25th Annual International Symposium on Microarchitecture, 1992, 45-54, the hyperblock, a block with one entry formed from several paths by if-conversion and predication, as an extension of the superblock
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag WWP2JP Edit this page History Report an error Markdown