Algorithm Search⌘K

Algorithmadvanced

Ball-Larus path profiling

Also called efficient path profiling.

Numbers the acyclic paths of a procedure so that adding values on some edges yields a unique path number, counting paths cheaply.

Time
O(V + E log E) worst
Space
Θ(V + E) extra
Where
E = the number of DAG edges after back edges are replaced by dummy edges; N = the number of ENTRY-to-EXIT paths, assumed to fit in a word; V = the number of nodes of the DAG (basic blocks plus ENTRY and EXIT)
Properties
deterministicexactofflineiterative

Ball-Larus path profiling counts how often each acyclic path through a procedure runs. It gives each edge of the control-flow graph an integer so that the sum of the integers along any path from the entry to the exit is a number in 0,…,N−10, \ldots, N-1, and different paths get different numbers. At run time a register adds up the integers of the edges it crosses, and at the end of the path it holds the path number, which indexes a table of counters. Loops are handled by cutting each back edge and recording a path there. A second step moves the integers to the chords of a maximum spanning tree, so that frequent edges carry no code. The profile feeds profile-guided optimization.

In plain words

Picture all the routes through a procedure that do not go around a loop. There can be very many, but they can be counted from the end backwards: a block with two exits has as many routes as its two successors added together. Now give each route a ticket number. At each branch, the routes that take the first exit get the lowest tickets, the routes that take the second exit get the next group, and so on. To make this happen, the program adds a fixed amount to a counter when it takes the second or a later exit. When the route ends, the counter is its ticket. Loops are cut where they jump back, and each trip around the loop is a route of its own. A last trick moves the additions off the busiest edges, so the program runs almost as fast as before.

The problem

The input is a control-flow graph with a single entry block. The goal is to instrument it so that every run reports how many times each acyclic path ran, with as little work at run time as possible. An edge profile, which counts how often each edge runs, does not give this: two runs can cross the same edges the same number of times and still take different paths.

First the graph is made acyclic. A depth-first search from the entry finds the back edges, the edges b→hb \to h to a block hh that is still on the search stack. Add two new nodes ENTRY and EXIT and an edge ENTRY →\to entry block. Every block that ends in ret gets an edge to EXIT. Each back edge b→hb \to h is removed, and two dummy edges take its place: a start edge ENTRY →h\to h (one per header hh) and a stop edge b→b \to EXIT (one per source bb). The result is a DAG G=(V,E)G = (V, E) in which ENTRY reaches every node and every node reaches EXIT. A path of GG always means a path from ENTRY to EXIT, and NN is their number.

The task on the DAG: find integers Val(e)\mathrm{Val}(e) on the edges such that the map from a path to the sum of Val\mathrm{Val} along it is a bijection onto {0,…,N−1}\{0, \ldots, N-1\}. Then find increments Inc(e)\mathrm{Inc}(e) with the same sum on every path and with Inc(e)=0\mathrm{Inc}(e) = 0 on as much of the run-time traffic as possible.

The algorithm

out(v)\mathrm{out}(v) is the list of edges that leave vv, in a fixed order. num(v)\mathrm{num}(v) is the number of paths from vv to EXIT.

  1. BALL-LARUS(G, ENTRY, EXIT, weight)
  2. 1for each node v in reverse topological order do
  3. 2if v = EXIT then num(v) <- 1
  4. 3else
  5. 4num(v) <- 0
  6. 5for each edge e = v -> w in out(v), in order do
  7. 6Val(e) <- num(v)
  8. 7num(v) <- num(v) + num(w)
  9. 8H <- the undirected multigraph of G plus one edge EXIT -- ENTRY
  10. 9T <- a maximum spanning tree of H by weight that contains EXIT -- ENTRY
  11. 10phi(ENTRY) <- 0
  12. 11for each edge u -> v of G in T, walking T outwards from ENTRY do
  13. 12set phi of the new endpoint so that phi(v) = phi(u) + Val(u -> v)
  14. 13for each edge e = u -> v of G do
  15. 14Inc(e) <- Val(e) + phi(u) - phi(v)
  16. 15return num, Val, Inc
  17. REGENERATE(r) // 0 <= r < num(ENTRY)
  18. 16v <- ENTRY; path <- empty
  19. 17while v != EXIT do
  20. 18find the edge e = v -> w in out(v) with Val(e) <= r < Val(e) + num(w)
  21. 19append e to path; r <- r - Val(e); v <- w
  22. 20return path

Lines L1 to L7 number the paths. The first edge out of a node gets value 0, and each later edge gets the number of paths through the earlier edges, so the paths through each edge form one block of consecutive numbers. REGENERATE inverts this and turns a path number back into its path.

Lines L8 to L14 are the placement. Walking the tree in L11 and L12 means: start at ENTRY, and for each tree edge with one endpoint already set, set the other endpoint from it (forwards along u→vu \to v with +Val+\mathrm{Val}, or backwards with −Val-\mathrm{Val}). The edge EXIT -- ENTRY is in the tree and carries no value, so ϕ(EXIT)=ϕ(ENTRY)=0\phi(\mathrm{EXIT}) = \phi(\mathrm{ENTRY}) = 0. Then Inc(e)=0\mathrm{Inc}(e) = 0 on every tree edge, so only the chords need code.

The instrumented program keeps a register rr:

  • on the edge ENTRY →\to entry: r←Incr \gets \mathrm{Inc} of that edge (the reset and the first increment in one instruction);
  • on an edge ee that is a chord with Inc(e)≠0\mathrm{Inc}(e) \ne 0: r←r+Inc(e)r \gets r + \mathrm{Inc}(e);
  • at a ret block bb: count the path r+Inc(b→EXIT)r + \mathrm{Inc}(b \to \mathrm{EXIT});
  • on a back edge b→hb \to h: count the path r+Inc(stop edge of b)r + \mathrm{Inc}(\text{stop edge of } b), then r←Inc(start edge of h)r \gets \mathrm{Inc}(\text{start edge of } h).

"Count the path tt" is count[t] += 1 in an array when NN is small, and in a hash table keyed by tt when NN is large. Code on an edge goes into a new block on the edge, as in critical edge splitting. The implementation here records the sequence of paths of one run in a single integer, so the tests can compare it with the blocks the run executed.

Example

Take the DAG with nodes A to F and edges A→\toB, A→\toC, B→\toC, B→\toD, C→\toD, D→\toE, D→\toF, E→\toF, with A as ENTRY and F as EXIT. In reverse topological order, num\mathrm{num} is F 1, E 1, D 2, C 2, B 4 and A 6. The edges with a nonzero value are the second exits: Val(A→C)=4\mathrm{Val}(A \to C) = 4, Val(B→D)=2\mathrm{Val}(B \to D) = 2 and Val(D→F)=1\mathrm{Val}(D \to F) = 1. The six paths get these numbers:

path sum of Val number
A B C D E F 0 + 0 + 0 + 0 + 0 0
A B C D F 0 + 0 + 0 + 1 1
A B D E F 0 + 2 + 0 + 0 2
A B D F 0 + 2 + 1 3
A C D E F 4 + 0 + 0 + 0 4
A C D F 4 + 0 + 1 5

To regenerate path 3: at A, edge A→\toB covers numbers 0 to 3, so take it. At B with r=3r = 3, B→\toC covers 0 to 1 and B→\toD covers 2 to 3, so take B→\toD and set r=1r = 1. At D, D→\toF covers 1, so the path is A B D F.

Now suppose a profile run took A C D F 75 times and each other path 5 times. The edge frequencies are A→\toB 20, A→\toC 80, B→\toC 10, B→\toD 10, C→\toD 90, D→\toE 15, D→\toF 85 and E→\toF 15. Kruskal's algorithm on these weights, with F -- A taken first, puts C→\toD, D→\toF, D→\toE and A→\toB in the tree. The potentials are ϕ(A)=0\phi(A) = 0, ϕ(B)=0\phi(B) = 0, ϕ(F)=0\phi(F) = 0, ϕ(D)=−1\phi(D) = -1, ϕ(C)=−1\phi(C) = -1 and ϕ(E)=−1\phi(E) = -1, so the increments are A→\toC 5, B→\toC 1, B→\toD 3, E→\toF −1-1 and 0 on the four tree edges. Every path keeps its number: A C D F gives 5+0+0=55 + 0 + 0 = 5 and A B C D E F gives 0+1+0+0−1=00 + 1 + 0 + 0 - 1 = 0. With one add on each edge that has a nonzero amount, the plain values run 80+10+85=17580 + 10 + 85 = 175 adds, and the tree placement runs 80+10+10+15=11580 + 10 + 10 + 15 = 115. On the hot path A C D F the only code left is on A→\toC, the first edge, which becomes the reset r←5r \gets 5.

A loop in the toy IR:

# params: n
B0:
  i = 0
  s = 0
  jump B1
B1:
  t = i < n
  br t B2 B3
B2:
  s = s + i
  i = i + 1
  jump B1
B3:
  ret s

The back edge is B2→\toB1. The DAG has the edges ENTRY→\toB0, B0→\toB1, B1→\toB2, B1→\toB3, B3→\toEXIT, the start edge ENTRY→\toB1 and the stop edge B2→\toEXIT. There are four paths: 0 is B0 B1 B2 (ends at the back edge), 1 is B0 B1 B3, 2 is B1 B2 (one more trip around the loop) and 3 is B1 B3 (the last test and the return). A run with n=2n = 2 is the path sequence 0, 2, 3. With the tree ENTRY→\toB0, B0→\toB1, B1→\toB2, B1→\toB3, the only nonzero increments are on the dummy edges: Inc(B3→EXIT)=1\mathrm{Inc}(B3 \to \mathrm{EXIT}) = 1 and Inc(ENTRY→B1)=2\mathrm{Inc}(\mathrm{ENTRY} \to B1) = 2. So no edge inside the loop body gets an add. The back edge code is "count rr, then r←2r \gets 2", and B3 counts r+1r + 1.

Correctness

The full proof is in the proof file. The three parts:

  • Numbering. By induction in reverse topological order, the sums of Val\mathrm{Val} along the paths from a node vv to EXIT are exactly 0,…,num(v)−10, \ldots, \mathrm{num}(v) - 1, each once. The paths through the ii-th edge v→wv \to w get the block Val(v→w)+{0,…,num(w)−1}\mathrm{Val}(v \to w) + \{0, \ldots, \mathrm{num}(w) - 1\}, and these blocks tile the range. Regeneration follows the same blocks, so it inverts the map.
  • Placement. For any spanning tree of HH that contains EXIT -- ENTRY, Inc(u→v)=Val(u→v)+ϕ(u)−ϕ(v)\mathrm{Inc}(u \to v) = \mathrm{Val}(u \to v) + \phi(u) - \phi(v). Along a path from ENTRY to EXIT the ϕ\phi terms telescope to ϕ(ENTRY)−ϕ(EXIT)=0\phi(\mathrm{ENTRY}) - \phi(\mathrm{EXIT}) = 0, so the sums of Inc and Val agree. On a tree edge Inc is 0 by the choice of ϕ\phi.
  • Loops. Each run splits in one way into DAG paths, cut at every crossing of a back edge. Between two cuts the register holds the sum of Inc over the DAG edges crossed so far in the current DAG path, so each count records the number of the path that just ended.
Proof: Ball-Larus path numbers are a bijection, and the chord placement keeps themfull

Setting. G=(V,E)G = (V, E) is a finite directed acyclic multigraph with two nodes ENTRY and EXIT. EXIT has no out-edges, ENTRY reaches every node, and every node reaches EXIT. A path from vv is a directed path from vv to EXIT, given as a list of edges. P(v)P(v) is the set of paths from vv, and num(v)\mathrm{num}(v) and Val(e)\mathrm{Val}(e) are computed by lines L1 to L7 of the algorithm. For a path pp, Val(p)=∑e∈pVal(e)\mathrm{Val}(p) = \sum_{e \in p} \mathrm{Val}(e).

Lemma 1. For every node vv, num(v)=∣P(v)∣≥1\mathrm{num}(v) = |P(v)| \ge 1, and the map p↦Val(p)p \mapsto \mathrm{Val}(p) is a bijection from P(v)P(v) onto {0,1,…,num(v)−1}\{0, 1, \ldots, \mathrm{num}(v) - 1\}.

Proof. Induction along the reverse topological order used in L1. When vv is processed, every successor ww of vv has been processed, because vv comes before ww in the topological order.

For v=EXITv = \mathrm{EXIT}, P(v)P(v) holds only the empty path, whose sum is 0, and num(v)=1\mathrm{num}(v) = 1.

Let v≠EXITv \ne \mathrm{EXIT} with out-edges e1=v→w1,…,ek=v→wke_1 = v \to w_1, \ldots, e_k = v \to w_k in the order of L5. Since vv reaches EXIT, k≥1k \ge 1. By L6 and L7, Val(ei)=si\mathrm{Val}(e_i) = s_i with s1=0s_1 = 0 and si+1=si+num(wi)s_{i+1} = s_i + \mathrm{num}(w_i), and num(v)=sk+1=∑inum(wi)\mathrm{num}(v) = s_{k+1} = \sum_i \mathrm{num}(w_i). Every path from vv is eie_i followed by a path qq from wiw_i, for exactly one ii and one qq, so ∣P(v)∣=∑i∣P(wi)∣=num(v)|P(v)| = \sum_i |P(w_i)| = \mathrm{num}(v) by induction. For such a path, Val(eiq)=si+Val(q)\mathrm{Val}(e_i q) = s_i + \mathrm{Val}(q). By induction Val(q)\mathrm{Val}(q) ranges bijectively over {0,…,num(wi)−1}\{0, \ldots, \mathrm{num}(w_i) - 1\}, so the paths through eie_i map bijectively onto the block Bi={si,…,si+1−1}B_i = \{s_i, \ldots, s_{i+1} - 1\}. The blocks B1,…,BkB_1, \ldots, B_k are disjoint and their union is {0,…,sk+1−1}\{0, \ldots, s_{k+1} - 1\}, since each starts where the previous one ends. Hence the map is a bijection from P(v)P(v) onto {0,…,num(v)−1}\{0, \ldots, \mathrm{num}(v) - 1\}. Each num(wi)≥1\mathrm{num}(w_i) \ge 1, so num(v)≥1\mathrm{num}(v) \ge 1. □\square

With v=ENTRYv = \mathrm{ENTRY}: the N=num(ENTRY)N = \mathrm{num}(\mathrm{ENTRY}) paths of GG get the numbers 0,…,N−10, \ldots, N - 1, each exactly once.

Lemma 2 (regeneration). For 0≤r<num(ENTRY)0 \le r < \mathrm{num}(\mathrm{ENTRY}), REGENERATE(r)(r) returns the unique path pp with Val(p)=r\mathrm{Val}(p) = r.

Proof. Invariant at the top of L17: the edges in path form a path from ENTRY to vv whose sum is the original rr minus the current rr, and 0≤r<num(v)0 \le r < \mathrm{num}(v). It holds at the start. If v≠EXITv \ne \mathrm{EXIT}, the blocks BiB_i of Lemma 1 partition {0,…,num(v)−1}\{0, \ldots, \mathrm{num}(v) - 1\}, so L18 finds exactly one edge eie_i with r∈Bir \in B_i. After L19, the new rr is r−si∈{0,…,num(wi)−1}r - s_i \in \{0, \ldots, \mathrm{num}(w_i) - 1\}, so the invariant holds at wiw_i. Each step moves forward in a finite DAG, so the loop ends, at v=EXITv = \mathrm{EXIT} where num(v)=1\mathrm{num}(v) = 1 forces r=0r = 0. Then the sum of path is the original rr. By Lemma 1 there is exactly one such path. □\square

Lemma 3 (placement). Let HH be the undirected multigraph with the edges of GG and one extra edge xx joining EXIT and ENTRY, and give xx the value Val(x)=0\mathrm{Val}(x) = 0, read in the direction EXIT →\to ENTRY. Let TT be any spanning tree of HH that contains xx. There is a function ϕ\phi on the nodes with ϕ(ENTRY)=0\phi(\mathrm{ENTRY}) = 0 and ϕ(v)=ϕ(u)+Val(u→v)\phi(v) = \phi(u) + \mathrm{Val}(u \to v) for every edge u→vu \to v of TT (including xx). With Inc(u→v)=Val(u→v)+ϕ(u)−ϕ(v)\mathrm{Inc}(u \to v) = \mathrm{Val}(u \to v) + \phi(u) - \phi(v):

  1. Inc(e)=0\mathrm{Inc}(e) = 0 for every edge ee of GG in TT;
  2. ∑e∈pInc(e)=Val(p)\sum_{e \in p} \mathrm{Inc}(e) = \mathrm{Val}(p) for every path pp from ENTRY to EXIT.

Proof. HH is connected, because every node is joined to ENTRY by a directed path of GG. So TT exists. Define ϕ(v)\phi(v) by walking the unique tree path from ENTRY to vv and adding Val(e)\mathrm{Val}(e) for each edge crossed along its direction and subtracting it for each edge crossed against its direction. This is what L10 to L12 compute, and because the tree path is unique, ϕ\phi is well defined. For a tree edge u→vu \to v, the tree path to one endpoint is the tree path to the other plus this edge, so ϕ(v)=ϕ(u)+Val(u→v)\phi(v) = \phi(u) + \mathrm{Val}(u \to v) in both cases. For xx this gives ϕ(ENTRY)=ϕ(EXIT)+0\phi(\mathrm{ENTRY}) = \phi(\mathrm{EXIT}) + 0, so ϕ(EXIT)=0\phi(\mathrm{EXIT}) = 0.

Part 1 is the rule for tree edges: Inc(u→v)=Val(u→v)+ϕ(u)−ϕ(v)=0\mathrm{Inc}(u \to v) = \mathrm{Val}(u \to v) + \phi(u) - \phi(v) = 0.

Part 2: let pp be v0→v1→⋯→vmv_0 \to v_1 \to \cdots \to v_m with v0=ENTRYv_0 = \mathrm{ENTRY} and vm=EXITv_m = \mathrm{EXIT}. Then

∑j=1mInc(vj−1→vj)=Val(p)+∑j=1m(ϕ(vj−1)−ϕ(vj))=Val(p)+ϕ(ENTRY)−ϕ(EXIT)=Val(p).\sum_{j=1}^{m} \mathrm{Inc}(v_{j-1} \to v_j) = \mathrm{Val}(p) + \sum_{j=1}^{m} (\phi(v_{j-1}) - \phi(v_j)) = \mathrm{Val}(p) + \phi(\mathrm{ENTRY}) - \phi(\mathrm{EXIT}) = \mathrm{Val}(p).

□\square

So the chord placement assigns the same number to every path as Val does, and needs code only on chords, the edges of GG outside TT. There are ∣E∣+1−(∣V∣−1)=∣E∣−∣V∣+2|E| + 1 - (|V| - 1) = |E| - |V| + 2 chords, none of them xx. The choice of a maximum spanning tree for the edge frequencies is a cost choice: among all spanning trees that contain xx, it is one whose chords have the least total frequency. It does not affect correctness.

Lemma 4 (programs with loops). Let the DAG come from a program as described on the page: back edges b→hb \to h of a depth-first search from the entry block are removed, and replaced by a start edge ENTRY →h\to h and a stop edge b→b \to EXIT. Then every finite run that ends in a ret splits in exactly one way into a sequence of DAG paths, and the instrumented program counts exactly the numbers of these paths, in order.

Proof. Removing all DFS back edges leaves a DAG, because in a DFS every cycle contains a back edge (an edge to a node on the stack). The run is a walk c0,c1,…,ctc_0, c_1, \ldots, c_t in the CFG from the entry block to a ret block. Cut it at every step cj→cj+1c_{j} \to c_{j+1} that is a back edge. Each piece is a walk that uses only DAG edges. The first piece starts at the entry block, so prefixing ENTRY →\to entry gives a DAG path start. A later piece starts at the header hh of the back edge just crossed, so its DAG path starts with the start edge ENTRY →h\to h. A piece that ends before a back edge b→hb \to h ends at bb and is closed by the stop edge b→b \to EXIT, and the last piece ends at a ret block and is closed by its edge to EXIT. Each piece is thus a path from ENTRY to EXIT. The cut points are fixed by the run, so the split is unique.

Now the register. Claim: while the run is inside a piece, rr equals the sum of Inc over the DAG edges of the current piece crossed so far, starting with its first edge from ENTRY. At the start of the run, rr is set to Inc(ENTRY→entry)\mathrm{Inc}(\mathrm{ENTRY} \to \text{entry}). Crossing a DAG edge ee inside a piece adds Inc(e)\mathrm{Inc}(e) (no code is the same as adding 0). At a ret block bb the count uses r+Inc(b→EXIT)r + \mathrm{Inc}(b \to \mathrm{EXIT}), which is the sum over the whole piece. At a back edge b→hb \to h, the count uses r+Inc(stop edge of b)r + \mathrm{Inc}(\text{stop edge of } b), again the sum over the whole piece, and then rr is set to Inc(ENTRY→h)\mathrm{Inc}(\mathrm{ENTRY} \to h), the first edge of the next piece. By Lemma 3 each counted value is the Val sum of the piece, and by Lemma 1 it is the number of that DAG path. □\square

A run that traps or does not end also has its completed pieces counted correctly; only the last, incomplete piece is not counted.

Theorem. The Ball-Larus numbering gives the NN paths of the DAG the numbers 0,…,N−10, \ldots, N - 1 bijectively, REGENERATE inverts it, the increments placed on the chords of any spanning tree of HH that contains EXIT -- ENTRY give every path the same sum, and the instrumented program counts each path of each run under its number. This is Lemmas 1 to 4. □\square

Complexity

The numbering visits each node and edge once after a topological sort, so it takes Θ(V+E)\Theta(V + E) word operations. Kruskal's algorithm takes O(Elog⁡E)O(E \log E) to sort the edges and almost linear time for the union-find steps, and the potentials take Θ(V+E)\Theta(V + E) more. Regeneration of one path takes O(its length+the out-degrees on it)O(\text{its length} + \text{the out-degrees on it}). At run time, each crossed chord with a nonzero increment costs one add, and each path end costs one counter update.

The numbers are the catch. NN can grow exponentially in VV: a chain of kk diamonds has 2k2^k paths. The word-RAM bound assumes NN fits in a word. Real tools fall back to a hash table, or cut the procedure into smaller regions, when NN is too large for an array of counters.

Properties

  • The path numbers are dense: they are exactly 0,…,N−10, \ldots, N-1, so an array of NN counters is enough.
  • The method is exact. It counts each acyclic path, not an estimate from edge counts.
  • The values do not depend on the profile. Only the placement uses frequencies, and any spanning tree that contains EXIT -- ENTRY gives correct counts.
  • The number of edges with a nonzero Val is at most E−V+1E - V + 1: each node other than EXIT has its first out-edge at 0. The tree placement can have nonzero increments on all E−V+2E - V + 2 chords. Its gain is in where the code goes, not in how many edges carry it.
  • An edge profile can be recovered from a path profile: the count of an edge is the sum of the counts of the paths through it. The converse fails.

Variants and improvements

  • Edge profiling. Ball and Larus's earlier placement puts one counter on each chord of a maximum spanning tree and recovers the tree edges by flow conservation (the flow into a node equals the flow out). Path profiling uses the same tree for a different purpose.
  • Profile to a hash table. When NN is large, the counts go to a hash table keyed by the path number, and only the paths that run take space.
  • Interprocedural and longer paths. Later work extends the numbering across calls or across loop iterations, at the cost of many more paths.
  • Sampling. A tool can turn the instrumentation on only part of the time to lower the overhead, at the cost of exact counts.

When to use it

Use it when an optimization needs correlated branch behavior, for example trace scheduling, superblock scheduling or the choice of a hot path to specialize. If only edge or block frequencies are needed, as for code layout, an edge profile is cheaper and enough. For long-running production code, sampling with hardware counters avoids instrumentation altogether.

Pitfalls

  • Counter overflow. The path register and the numbers can overflow a machine word on large procedures. Check NN at compile time and switch to a hash table or split the procedure.
  • Every cycle must lose an edge. If a cycle is left in the graph, there is no reverse topological order and the numbering does not exist. Cutting the back edges of a depth-first search breaks every cycle, also in a graph that is not reducible.
  • The tree must contain EXIT -- ENTRY. Without it, ϕ(EXIT)≠ϕ(ENTRY)\phi(\mathrm{EXIT}) \ne \phi(\mathrm{ENTRY}) in general, and every path sum is off by the same constant. The counts then go to the wrong slots.
  • Not fewer edges. Chord placement does not reduce the number of instrumented edges. It reduces the weighted cost only if the weights predict the real run. On random graphs it can do worse than plain Val placement for some frequencies, and it is a heuristic.
  • Code on the edge. An increment on an edge whose source has several successors and whose target has several predecessors needs a new block on the edge; putting it at the end of the source or the start of the target counts other paths too.
  • Loops are split. A path profile does not say which iterations follow which, and two runs with the same per-iteration paths in a different order look the same.

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.

ball_larus_path_profiling.pyI0RawGitHub
# SPDX-License-Identifier: MIT
"""Ball-Larus path profiling.

A DAG is given as a list of nodes and a list of edges (u, v). Edges are
named by their index in the list, so two edges may join the same pair of
nodes. ENTRY reaches every node and every node reaches EXIT.

number_paths gives each edge a value Val so that the sums of Val along the
N paths from ENTRY to EXIT are exactly 0, 1, ..., N - 1. place_increments
moves the values off the edges of a maximum spanning tree, so that only the
chords carry code, and the sum along every path stays the same.
regenerate turns a path number back into its path.

cfg_to_dag and instrument apply the method to a program of the toy IR
(toyir.py): back edges are cut and replaced by dummy edges, and the
instrumented program keeps the path register in bl.r and records each
finished path in bl.h.
"""

import toyir

ENTRY = "bl.entry"
EXIT = "bl.exit"


def out_edges(nodes, edges):
    """Dict from node to the indices of its outgoing edges, in list order."""
    out = {v: [] for v in nodes}
    for i, (u, _) in enumerate(edges):
        out[u].append(i)
    return out


def topological_order(nodes, edges):
    """Kahn's algorithm. Raises ValueError if the graph has a cycle."""
    indeg = {v: 0 for v in nodes}
    for _, v in edges:
        indeg[v] += 1
    out = out_edges(nodes, edges)
    ready = [v for v in nodes if indeg[v] == 0]
    order = []
    while ready:
        u = ready.pop()
        order.append(u)
        for i in out[u]:
            v = edges[i][1]
            indeg[v] -= 1
            if indeg[v] == 0:
                ready.append(v)
    if len(order) != len(nodes):
        raise ValueError("the graph has a cycle")
    return order


def number_paths(nodes, edges, entry, exit_):
    """The Ball-Larus numbering.

    Returns (num, val): num[v] is the number of paths from v to exit_, and
    val[i] is the value of edge i. The sum of val along a path from entry to
    exit_ is its path number, in 0 .. num[entry] - 1.
    """
    out = out_edges(nodes, edges)
    num = {}
    val = [0] * len(edges)
    for v in reversed(topological_order(nodes, edges)):  # @line L1
        if v == exit_:
            num[v] = 1  # @line L2
            continue
        num[v] = 0  # @line L3 L4
        for i in out[v]:  # @line L5
            val[i] = num[v]  # @line L6
            num[v] += num[edges[i][1]]  # @line L7
        if num[v] == 0:
            raise ValueError("node %r does not reach the exit" % (v,))
    return num, val


def regenerate(nodes, edges, num, val, entry, exit_, r):
    """The list of edge indices of the path with number r."""
    if not 0 <= r < num[entry]:
        raise ValueError("no path has number %r" % (r,))
    out = out_edges(nodes, edges)
    path, v = [], entry  # @line L16
    while v != exit_:  # @line L17
        for i in out[v]:
            w = edges[i][1]
            if val[i] <= r < val[i] + num[w]:  # @line L18
                path.append(i)  # @line L19
                r -= val[i]
                v = w
                break
    return path  # @line L20


def all_paths(nodes, edges, entry, exit_):
    """Every path from entry to exit_, as lists of edge indices (brute force)."""
    out = out_edges(nodes, edges)
    result, stack = [], [(entry, [])]
    while stack:
        v, path = stack.pop()
        if v == exit_:
            result.append(path)
            continue
        for i in out[v]:
            stack.append((edges[i][1], path + [i]))
    return result


class _Sets:
    """Disjoint sets with path halving and union by size."""

    def __init__(self, items):
        self.parent = {x: x for x in items}
        self.size = {x: 1 for x in items}

    def find(self, x):
        while self.parent[x] != x:
            self.parent[x] = self.parent[self.parent[x]]
            x = self.parent[x]
        return x

    def union(self, a, b):
        a, b = self.find(a), self.find(b)
        if a == b:
            return False
        if self.size[a] < self.size[b]:
            a, b = b, a
        self.parent[b] = a
        self.size[a] += self.size[b]
        return True


def place_increments(nodes, edges, val, entry, exit_, weight=None):
    """Ball and Larus's placement on the chords of a maximum spanning tree.

    The tree is taken in the undirected graph of the DAG plus one edge
    exit_ -> entry, which is always in the tree. weight[i] is the expected
    frequency of edge i (1 for every edge if omitted). Returns (inc, tree):
    inc[i] is the increment of edge i, and tree is the set of the indices
    of the DAG edges in the tree, where inc is 0.
    """
    if weight is None:
        weight = [1] * len(edges)
    sets = _Sets(nodes)  # @line L8
    sets.union(exit_, entry)
    adj = {v: [] for v in nodes}
    adj[exit_].append((entry, 0))
    adj[entry].append((exit_, 0))
    tree = set()
    for i in sorted(range(len(edges)), key=lambda i: (-weight[i], i)):  # @line L9
        u, v = edges[i]
        if sets.union(u, v):
            tree.add(i)
            adj[u].append((v, val[i]))
            adj[v].append((u, -val[i]))
    # A potential phi with phi[v] = phi[u] + val[i] along every tree edge u -> v.
    phi = {entry: 0}  # @line L10
    stack = [entry]
    while stack:  # @line L11
        u = stack.pop()
        for v, d in adj[u]:
            if v not in phi:
                phi[v] = phi[u] + d  # @line L12
                stack.append(v)
    inc = [val[i] + phi[u] - phi[v] for i, (u, v) in enumerate(edges)]  # @line L13 L14
    return inc, tree  # @line L15


def cfg_to_dag(prog):
    """The DAG of a toy IR program, with back edges cut.

    Returns (nodes, edges, kind, back). kind[i] is "real" for an edge of
    the CFG or the edge ENTRY -> entry block, "ret" for b -> EXIT where b
    ends in ret, "start" for the dummy ENTRY -> h of a loop header h, and
    "stop" for the dummy b -> EXIT of the source b of a back edge. back maps
    each back edge (b, h) to the indices of its stop and start edges.
    """
    labels = list(prog.blocks)
    # Back edges: the edges to a block on the DFS stack.
    back_edges = []
    state = {lab: 0 for lab in labels}
    state[prog.entry] = 1
    stack = [(prog.entry, iter(toyir.succs(prog, prog.entry)))]
    while stack:
        v, it = stack[-1]
        w = next(it, None)
        if w is None:
            state[v] = 2
            stack.pop()
        elif state[w] == 1:
            back_edges.append((v, w))
        elif state[w] == 0:
            state[w] = 1
            stack.append((w, iter(toyir.succs(prog, w))))
    cut = set(back_edges)
    nodes = [ENTRY] + labels + [EXIT]
    edges, kind = [(ENTRY, prog.entry)], ["real"]
    for a in labels:
        for b in toyir.succs(prog, a):
            if (a, b) not in cut:
                edges.append((a, b))
                kind.append("real")
        if prog.blocks[a].term[0] == "ret":
            edges.append((a, EXIT))
            kind.append("ret")
    start, stop, back = {}, {}, {}
    for b, h in back_edges:
        if h not in start:
            start[h] = len(edges)
            edges.append((ENTRY, h))
            kind.append("start")
        if b not in stop:
            stop[b] = len(edges)
            edges.append((b, EXIT))
            kind.append("stop")
        back[(b, h)] = (stop[b], start[h])
    return nodes, edges, kind, back


def instrument(prog, nodes, edges, kind, back, inc, radix):
    """The profiling version of prog.

    bl.r is the path register. When a path ends (at a ret or a back edge),
    its number t is recorded as bl.h = bl.h * radix + t + 1, and every ret
    returns bl.h in place of the program's value. radix must exceed the
    number of paths. Code on an edge goes into a new block on that edge.
    """
    index = {e: i for i, e in enumerate(edges) if kind[i] == "real"}
    ret_edge = {edges[i][0]: i for i in range(len(edges)) if kind[i] == "ret"}

    def add(k):
        return [("op", "bl.r", "+", "bl.r", k)] if k else []

    def record(k):
        return [("op", "bl.t", "+", "bl.r", k + 1),
                ("op", "bl.h", "*", "bl.h", radix),
                ("op", "bl.h", "+", "bl.h", "bl.t")]

    blocks = {ENTRY: toyir.Block([("const", "bl.r", 0), ("const", "bl.h", 0)]
                                 + add(inc[index[(ENTRY, prog.entry)]]),
                                 ("jump", prog.entry))}
    extra = {}
    for a, blk in prog.blocks.items():
        instrs = list(blk.instrs)
        term = blk.term
        if term[0] == "ret":
            instrs += record(inc[ret_edge[a]])
            term = ("ret", "bl.h")
        else:
            targets = [term[1]] if term[0] == "jump" else [term[2], term[3]]
            new = []
            for b in targets:
                if (a, b) in back:
                    s_stop, s_start = back[(a, b)]
                    code = record(inc[s_stop]) + [("const", "bl.r", inc[s_start])]
                else:
                    code = add(inc[index[(a, b)]])
                if code:
                    lab = "bl.%s.%s" % (a, b)
                    extra[lab] = toyir.Block(code, ("jump", b))
                    b = lab
                new.append(b)
            term = ("jump", new[0]) if term[0] == "jump" else ("br", term[1], new[0], new[1])
        blocks[a] = toyir.Block(instrs, term)
    blocks.update(extra)
    return toyir.Program(list(prog.params), blocks)


def decode_history(h, radix):
    """The path numbers recorded in bl.h, in order."""
    out = []
    while h:
        h, t = divmod(h, radix)
        out.append(t - 1)
    return out[::-1]


def path_blocks(edges, kind, path):
    """The blocks of the program on a DAG path, without ENTRY and EXIT."""
    blocks = [edges[i][1] for i in path]
    return [b for b in blocks if b not in (ENTRY, EXIT)]
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_ball_larus_path_profiling.py 192 lines
# SPDX-License-Identifier: MIT
import random
import unittest

import toyir
from ball_larus_path_profiling import (
    ENTRY, EXIT, all_paths, cfg_to_dag, decode_history, instrument,
    number_paths, path_blocks, place_increments, regenerate,
)


def random_dag(rng, n, p):
    """A random DAG on v0 .. v(n-1): v0 reaches every node, every node
    reaches v(n-1), and parallel edges are allowed."""
    nodes = ["v%d" % i for i in range(n)]
    edges = []
    for i in range(n - 1):
        edges.append((nodes[i], nodes[rng.randrange(i + 1, n)]))
        for j in range(i + 1, n):
            if rng.random() < p:
                edges.append((nodes[i], nodes[j]))
    for j in range(1, n):
        if not any(e[1] == nodes[j] for e in edges):
            edges.append((nodes[rng.randrange(0, j)], nodes[j]))
    return nodes, edges


def path_freq(edges, paths, rng):
    """Edge frequencies from random path counts."""
    freq = [0] * len(edges)
    for p in paths:
        c = rng.choice((0, 1, 1, 2, 5, 50))
        for i in p:
            freq[i] += c
    return freq


class NumberingTest(unittest.TestCase):
    def test_bijection_and_regeneration(self):
        rng = random.Random(7)
        for _ in range(400):
            nodes, edges = random_dag(rng, rng.randint(2, 9), rng.random() * 0.6)
            s, t = nodes[0], nodes[-1]
            num, val = number_paths(nodes, edges, s, t)
            paths = all_paths(nodes, edges, s, t)
            self.assertEqual(len(paths), num[s])
            sums = sorted(sum(val[i] for i in p) for p in paths)
            self.assertEqual(sums, list(range(num[s])))
            for p in paths:
                r = sum(val[i] for i in p)
                self.assertEqual(regenerate(nodes, edges, num, val, s, t, r), p)

    def test_textbook_graph(self):
        nodes = list("ABCDEF")
        edges = [("A", "B"), ("A", "C"), ("B", "C"), ("B", "D"),
                 ("C", "D"), ("D", "E"), ("D", "F"), ("E", "F")]
        num, val = number_paths(nodes, edges, "A", "F")
        self.assertEqual(num, {"A": 6, "B": 4, "C": 2, "D": 2, "E": 1, "F": 1})
        self.assertEqual(val, [0, 4, 0, 2, 0, 0, 1, 0])
        names = []
        for r in range(6):
            p = regenerate(nodes, edges, num, val, "A", "F", r)
            names.append("A" + "".join(edges[i][1] for i in p))
        self.assertEqual(names, ["ABCDEF", "ABCDF", "ABDEF", "ABDF", "ACDEF", "ACDF"])

    def test_cycle_is_rejected(self):
        with self.assertRaises(ValueError):
            number_paths(["a", "b"], [("a", "b"), ("b", "a")], "a", "b")


class PlacementTest(unittest.TestCase):
    def test_same_sums_and_code_only_on_chords(self):
        rng = random.Random(11)
        for _ in range(400):
            nodes, edges = random_dag(rng, rng.randint(2, 9), rng.random() * 0.6)
            s, t = nodes[0], nodes[-1]
            num, val = number_paths(nodes, edges, s, t)
            paths = all_paths(nodes, edges, s, t)
            freq = path_freq(edges, paths, rng)
            inc, tree = place_increments(nodes, edges, val, s, t, freq)
            # A spanning tree of V nodes has V - 1 edges, one of them t -> s.
            self.assertEqual(len(tree), len(nodes) - 2)
            for i in tree:
                self.assertEqual(inc[i], 0)
            chords = len(edges) - len(tree)
            self.assertEqual(chords, len(edges) - len(nodes) + 2)
            for p in paths:
                self.assertEqual(sum(inc[i] for i in p), sum(val[i] for i in p))

    def test_maximum_tree_has_the_lightest_chords(self):
        rng = random.Random(13)
        for _ in range(200):
            nodes, edges = random_dag(rng, rng.randint(3, 8), rng.random() * 0.6)
            s, t = nodes[0], nodes[-1]
            num, val = number_paths(nodes, edges, s, t)
            paths = all_paths(nodes, edges, s, t)
            freq = path_freq(edges, paths, rng)
            _, tree = place_increments(nodes, edges, val, s, t, freq)
            best = sum(freq[i] for i in range(len(edges)) if i not in tree)
            for _ in range(10):
                other_w = [rng.random() for _ in edges]
                inc2, tree2 = place_increments(nodes, edges, val, s, t, other_w)
                other = sum(freq[i] for i in range(len(edges)) if i not in tree2)
                self.assertLessEqual(best, other)
                for p in paths:
                    self.assertEqual(sum(inc2[i] for i in p), sum(val[i] for i in p))

    def test_textbook_graph_hot_path(self):
        nodes = list("ABCDEF")
        edges = [("A", "B"), ("A", "C"), ("B", "C"), ("B", "D"),
                 ("C", "D"), ("D", "E"), ("D", "F"), ("E", "F")]
        num, val = number_paths(nodes, edges, "A", "F")
        freq = [20, 80, 10, 10, 90, 15, 85, 15]
        inc, tree = place_increments(nodes, edges, val, "A", "F", freq)
        self.assertEqual(inc, [0, 5, 1, 3, 0, 0, 0, -1])
        self.assertEqual(sorted(tree), [0, 4, 5, 6])
        cost_val = sum(f for f, v in zip(freq, val) if v)
        cost_inc = sum(f for f, k in zip(freq, inc) if k)
        self.assertEqual((cost_val, cost_inc), (175, 115))


def tracer(prog, k):
    """prog changed to return the sequence of blocks it ran, in base k."""
    index = {lab: i for i, lab in enumerate(prog.blocks)}
    blocks = {"tr.entry": toyir.Block([("const", "tr", 0)], ("jump", prog.entry))}
    for lab, b in prog.blocks.items():
        code = [("op", "tr", "*", "tr", k), ("op", "tr", "+", "tr", index[lab] + 1)]
        term = ("ret", "tr") if b.term[0] == "ret" else b.term
        blocks[lab] = toyir.Block(code + list(b.instrs), term)
    return toyir.Program(list(prog.params), blocks)


def decode_trace(h, k, labels):
    out = []
    while h:
        h, d = divmod(h, k)
        out.append(labels[d - 1])
    return out[::-1]


class ProgramTest(unittest.TestCase):
    def check(self, prog, rng):
        nodes, edges, kind, back = cfg_to_dag(prog)
        num, val = number_paths(nodes, edges, ENTRY, EXIT)
        weight = [rng.randint(1, 9) for _ in edges]
        inc, _ = place_increments(nodes, edges, val, ENTRY, EXIT, weight)
        radix = num[ENTRY] + 1
        prof = instrument(prog, nodes, edges, kind, back, inc, radix)
        k = len(prog.blocks) + 1
        trace = tracer(prog, k)
        labels = list(prog.blocks)
        checked = 0
        for _ in range(6):
            args = [rng.randint(-3, 6), rng.randint(-3, 6)]
            out = toyir.run(prog, args, 4000)
            if out == ("fuel",):
                continue
            got = toyir.run(prof, args, 100000)
            self.assertEqual(got[0], out[0])
            if out[0] != "ret":
                continue
            seen = decode_trace(toyir.run(trace, args, 100000)[1], k, labels)
            regen = []
            for r in decode_history(got[1], radix):
                p = regenerate(nodes, edges, num, val, ENTRY, EXIT, r)
                regen += path_blocks(edges, kind, p)
            self.assertEqual(regen, seen)
            checked += 1
        return checked

    def test_acyclic_programs(self):
        rng = random.Random(3)
        total = 0
        for _ in range(150):
            prog = toyir.random_program(rng, 4, rng.randint(1, 8), True)
            total += self.check(prog, rng)
        self.assertGreater(total, 300)

    def test_programs_with_loops(self):
        rng = random.Random(5)
        total = 0
        loops = 0
        for _ in range(150):
            prog = toyir.random_program(rng, 4, rng.randint(2, 8), False)
            loops += bool(cfg_to_dag(prog)[3])
            total += self.check(prog, rng)
        self.assertGreater(total, 300)
        self.assertGreater(loops, 50)


if __name__ == "__main__":
    unittest.main()

History

Before path profiles, compilers used block or edge counts. Ball and Larus showed in 1994 how to place edge counters on the chords of a maximum spanning tree, and in 1996 they gave the path numbering, its regeneration and the chord placement for paths. Their method became the usual way to collect path profiles, and later work reused the numbering for longer paths and for calling contexts.

References

  1. Thomas Ball and James R. Larus, Efficient path profiling, Proceedings of the 29th Annual IEEE/ACM International Symposium on Microarchitecture (MICRO-29), Paris, 1996, 46-57, the numbering of the paths of a DAG (NumPaths and Val), the regeneration of a path from its number, the placement of increments on the chords of a spanning tree, and the treatment of loops by dummy edges for each back edge
  2. Thomas Ball and James R. Larus, Optimally profiling and tracing programs, ACM Transactions on Programming Languages and Systems 16(4), 1994, 1319-1360, the placement of edge counters on the chords of a maximum spanning tree, and the recovery of the tree edge counts by flow conservation

About this page

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

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