Algorithm Search⌘K

Data structureintro

Def-use chains

Also called use-def chains, du-chains, ud-chains.

Links each definition of a variable to the uses it can reach and each use to the definitions that can reach it.

Def-use chains record, for a program in three-address code, which definitions of a variable can supply the value that each use reads. A du-chain links a definition to all the uses it can reach; a ud-chain, or use-def chain, links a use to all the definitions that can reach it. Both are the same set of pairs, read in two directions. A definition dd of xx reaches a use of xx if some path in the control flow graph leads from dd to the use without another definition of xx. The chains are built from the answer of reaching definitions, and optimizations then follow them instead of scanning the whole program: copy propagation, dead code elimination, constant propagation, induction variable analysis and the webs of register allocation. They can be large: kk definitions that meet at one join and reach kk uses give k2k^2 links, which is one reason for static single assignment form.

In plain words

A program sets variables in some places and reads them in others. When a line reads a variable, the compiler wants to know which earlier lines could have set the value it gets. It looks at every way the program can run to that line and keeps the lines that set the variable last before it. A ud-chain is that list for one reading line. A du-chain goes the other way: for one line that sets a variable, the list of lines that can read the value it wrote. With these lists, a compiler can see that a value is never read, so its line can go, or that only one line can set a value, so that value is known. It follows the lists instead of reading the whole program again.

The abstract type

The structure stores a relation between two kinds of sites. A definition site (b,i,x)(b, i, x) is instruction ii of block bb when it writes the name xx; a parameter xx is the site (entry,−1,x)(\mathit{entry}, -1, x), written on the way into the program. A use site (b,i,x)(b, i, x) is instruction ii of block bb when it reads xx, and i=nbi = n_b, the number of instructions of bb, means the terminator. The operations are:

  • chains(P): build the structure for program PP.
  • du(d): the uses that definition dd reaches.
  • ud(u): the definitions that reach use uu.

The law: u∈du(d)u \in du(d) if and only if d∈ud(u)d \in ud(u) if and only if dd reaches uu. Here dd of xx reaches uu if some path from the point just after dd to uu passes no other definition of xx; the instruction at uu may itself define xx, since it reads first. A phi operand that comes from the predecessor pp counts as a use at the end of pp. The relation is about paths, not about runs: a path that no input can take still counts, so the chains may contain pairs that never happen, but they miss no pair that does happen in a run that writes variables only by name.

Representation

Two maps hold the relation: du from each definition site to the sorted list of its uses, and ud from each use site to the sorted list of its definitions. Every definition site is a key of du, even with no uses, and every use site is a key of ud, even with no definitions. A compiler keeps the lists on the instructions themselves, as pointers, so that it can go from an instruction to its uses in constant time per link.

To build the maps, the code first solves reaching definitions per block. GEN[b]GEN[b] holds the last definition in bb of each name, and KILL[b]KILL[b] holds the names that bb defines. IN[b]IN[b] and OUT[b]OUT[b] are the definitions that reach the start and the end of bb. Compilers store these sets as bit vectors with one bit per definition site; the Python code uses sets of site tuples.

Operations

  1. BUILD-CHAINS(P)
  2. 1for each block b: GEN[b] <- the last definition in b of each name; KILL[b] <- the names b defines
  3. 2OUT[b] <- GEN[b] for every block b
  4. 3repeat
  5. 4for each block b in reverse postorder do
  6. 5IN[b] <- the union of OUT[p] over the predecessors p of b, plus the parameters if b is the entry
  7. 6OUT[b] <- GEN[b] ∪ {d in IN[b] : the name of d is not in KILL[b]}
  8. 7until no OUT set changed in the pass
  9. 8for each block b do
  10. 9live[x] <- the definitions of x in IN[b], for every name x
  11. 10for each instruction s of b in order, then the terminator do
  12. 11link every d in live[x] with the use (s, x), for each name x that s reads
  13. 12if s defines x then live[x] <- {s}
  14. 13return du and ud

Lines L1 to L7 are the round-robin solution of reaching definitions. Lines L8 to L12 walk each block once: live[x]live[x] is always the set of definitions of xx that reach the current instruction, so a read of xx is linked to exactly those. Line L11 reads before line L12 writes, so i = i + 1 links its read of i to the earlier definitions, not to itself. A phi is the exception to line L11: its operand from predecessor pp is linked to the definitions of that name in OUT[p]OUT[p], because the value is chosen on the edge from pp.

du(d) and ud(u) are lookups in the two maps. The function reaching returns ININ, OUTOUT and the number of passes.

Example

The odd-sum program of the control flow graph page, with the parameter n:

B1:
  i = 0
  s = 0
  jump B2
B2:
  t1 = i < n
  br t1 B3 B6
B3:
  t2 = i % 2
  br t2 B4 B5
B4:
  s = s + i
  jump B5
B5:
  i = i + 1
  jump B2
B6:
  ret s

Reaching definitions in reverse postorder B1, B2, B6, B3, B4, B5 settle in 2 passes, and a third pass changes nothing. Since OUTOUT starts at GENGEN, i = i + 1 reaches the loop header B2 along B5→B2B5 \to B2 already in the first pass. s = s + i in B4 gets there only in the second pass, after the first pass has carried it into OUT[B5]OUT[B5]. The chains, as du-chains:

definition uses it reaches
n (parameter) t1 = i < n in B2
i = 0 in B1 the reads of i in B2, B3, B4 and B5
i = i + 1 in B5 the reads of i in B2, B3, B4 and B5
s = 0 in B1 s = s + i in B4, ret s in B6
s = s + i in B4 s = s + i in B4, ret s in B6
t1 in B2 br t1 in B2
t2 in B3 br t2 in B3

There are 15 links. Read as ud-chains, the use of s in ret s has two definitions, s = 0 and s = s + i, so s is not a constant there. The definition s = s + i reaches its own read through the loop. Each ti has one definition and one use, so a compiler could fold the comparison into the branch. The program returns 9 for n=6n = 6.

Correctness

The proof file shows three things. First, the sets "definitions that reach the start of bb" and "definitions that reach the end of bb" are the least solution of the equations of lines L5 and L6: they solve them, by cutting a path at its last entry into bb, and every solution contains them, by induction on the length of the path. Second, the iteration starts below this least solution, stays below it and only grows, so it stops, and when a pass changes nothing it has reached the least solution; at most BD+1B D + 1 passes are needed, for BB blocks and DD definition sites. Third, during the scan of a block, live[x]live[x] is always the set of definitions of xx that reach the current instruction, because the only way into instruction i+1i + 1 is through instruction ii. So each use is linked to exactly the definitions that reach it. The proof covers names only. A store through a pointer writes a variable without naming it, and the chains do not see it.

Proof: The reaching-definitions iteration and the block scan build exactly the def-use chainsfull

Setting. A program has blocks with instructions and one terminator each, and an entry block. A point is (b,i)(b, i) for 0≤i≤nb0 \le i \le n_b, where nbn_b is the number of instructions of bb: for i<nbi < n_b it is instruction ii of bb, and (b,nb)(b, n_b) is the terminator. The point graph has the edges (b,i)→(b,i+1)(b, i) \to (b, i + 1) for i<nbi < n_b and (b,nb)→(c,0)(b, n_b) \to (c, 0) for every successor cc of bb. Add a start point σ\sigma with the single edge σ→(entry,0)\sigma \to (\mathit{entry}, 0). A definition site is a point that defines a name xx, written d=(b,i,x)d = (b, i, x); a parameter xx is the site (entry,−1,x)(\mathit{entry}, -1, x), placed at σ\sigma. The point after dd is (b,i+1)(b, i + 1), or (entry,0)(\mathit{entry}, 0) for a parameter. A phi instruction at a point defines its name there, like any other instruction.

Definition. A path π\pi of points is clear for xx if no point of π\pi except possibly its last one defines xx. The definition dd of xx reaches a point qq if some path clear for xx goes from the point after dd to qq, with qq itself allowed to define xx. It reaches the end of a block pp if it reaches (p,np)(p, n_p); the terminator defines nothing. The chains are the pairs (d,u)(d, u) for a use uu of xx such that:

  • u=(b,i,x)u = (b, i, x) where point (b,i)(b, i) is not a phi and reads xx, and dd reaches (b,i)(b, i); or
  • u=(b,i,x)u = (b, i, x) where point (b,i)(b, i) is a phi whose operand for the predecessor pp is xx, and dd reaches the end of pp.

The function returns du[d]du[d], the uses uu with (d,u)(d, u) a chain, and ud[u]ud[u], the definitions dd with (d,u)(d, u) a chain. So dudu and udud are the same relation read in two directions, and it is enough to show that the set of pairs is right.

Block summaries. For a block bb, GEN[b]GEN[b] holds, for each name defined in bb, the site of its last definition in bb, and KILL[b]KILL[b] is the set of names defined in bb. PP is the set of parameter sites. Let RIN[b]RIN[b] be the set of definitions that reach (b,0)(b, 0) and ROUT[b]ROUT[b] the set that reach the end of bb. Write name(d)name(d) for the name that dd defines.

Lemma 1 (the equations). RINRIN and ROUTROUT satisfy

IN[b]=[b=entry] P  ∪⋃p∈pred(b)OUT[p],OUT[b]=GEN[b]∪{d∈IN[b]:name(d)∉KILL[b]},IN[b] = [b = \mathit{entry}]\,P \;\cup \bigcup_{p \in pred(b)} OUT[p], \qquad OUT[b] = GEN[b] \cup \{d \in IN[b] : name(d) \notin KILL[b]\},

and every other solution (IN,OUT)(IN, OUT) has RIN[b]⊆IN[b]RIN[b] \subseteq IN[b] and ROUT[b]⊆OUT[b]ROUT[b] \subseteq OUT[b] for all bb. So they are the least solution.

Proof. They are a solution. The points with an edge into (b,0)(b, 0) are the ends of the predecessors of bb, and σ\sigma if bb is the entry. A path clear for xx from the point after dd to (b,0)(b, 0) either has length 0, which happens only for a parameter and b=entryb = \mathit{entry}, or its last but one point is the end of a predecessor pp, and the part up to it is a path clear for xx that ends at a point defining nothing. This gives RIN[b]=[b=entry] P∪⋃pROUT[p]RIN[b] = [b = \mathit{entry}]\,P \cup \bigcup_p ROUT[p], and the converse direction is the same argument read backwards. For ROUT[b]ROUT[b], a path clear for xx to (b,nb)(b, n_b) from the point after dd either starts inside bb, after d=(b,i,x)d = (b, i, x), and then no later point of bb defines xx, so d∈GEN[b]d \in GEN[b]; or it passes through (b,0)(b, 0), its part up to (b,0)(b, 0) shows d∈RIN[b]d \in RIN[b], and then the whole block is passed without a definition of xx, so x∉KILL[b]x \notin KILL[b]. Conversely each such dd gives such a path. (A path that starts inside bb and later passes (b,0)(b, 0) falls under the second case; the first case uses its last visit to bb.)

They are the least solution. Let (IN,OUT)(IN, OUT) be a solution. We show by induction on the number of points of the path that if a path clear for xx goes from the point after dd to (b,0)(b, 0) then d∈IN[b]d \in IN[b], and if it goes to (b,nb)(b, n_b) then d∈OUT[b]d \in OUT[b]. For (b,0)(b, 0): the path has length 0 and d∈P⊆IN[entry]d \in P \subseteq IN[\mathit{entry}], or its part up to the end of a predecessor pp is shorter, so d∈OUT[p]⊆IN[b]d \in OUT[p] \subseteq IN[b]. For (b,nb)(b, n_b): look at the last time the path is at (b,0)(b, 0). If there is none, the path lies in bb after dd, and d∈GEN[b]⊆OUT[b]d \in GEN[b] \subseteq OUT[b]. Otherwise the part up to that point is shorter, so d∈IN[b]d \in IN[b], and the rest crosses bb without a definition of xx, so name(d)∉KILL[b]name(d) \notin KILL[b] and d∈OUT[b]d \in OUT[b]. □\square

Lemma 2 (the iteration). Lines L2 to L7 stop, and when they stop, IN=RININ = RIN and OUT=ROUTOUT = ROUT. The number of passes is at most B⋅D+1B \cdot D + 1, where BB is the number of blocks and DD the number of definition sites.

Proof. Let FF be the map that takes the OUTOUT sets to new ININ and OUTOUT sets by the equations. It is monotone: larger OUTOUT sets give larger ININ sets and then larger OUTOUT sets. Two invariants hold at all times.

(i) OUT[b]⊆ROUT[b]OUT[b] \subseteq ROUT[b] for all bb. At the start OUT[b]=GEN[b]OUT[b] = GEN[b], and GEN[b]⊆ROUT[b]GEN[b] \subseteq ROUT[b], because the last definition of xx in bb reaches the end of bb along the rest of bb. An update computes IN[b]IN[b] and OUT[b]OUT[b] from sets that lie below (RIN,ROUT)(RIN, ROUT), and (RIN,ROUT)(RIN, ROUT) is a fixed point of the equations, so by monotonicity the new sets lie below it too.

(ii) The OUTOUT sets never shrink. The first value of OUT[b]OUT[b] is GEN[b]GEN[b], and every later value is GEN[b]∪…⊇GEN[b]GEN[b] \cup \ldots \supseteq GEN[b]. After that, each new value of OUT[b]OUT[b] is computed from OUTOUT sets that are at least as large as at the previous update of bb, so by monotonicity it is at least the previous value.

A pass that sets changedchanged adds at least one site to some OUTOUT set, and by (i) the sets are bounded by the finite ROUTROUT sets, which have at most B⋅DB \cdot D elements in total. So at most B⋅DB \cdot D passes change something, and the loop stops after at most one more pass. In the last pass no OUTOUT set changed, so each IN[b]IN[b] was computed from the final OUTOUT sets, and each final OUT[b]OUT[b] equals the right side of its equation. So the final sets are a solution, by (i) they lie below the least solution, and by Lemma 1 they are the least solution. □\square

Lemma 3 (the block scan). In lines L8 to L12, just before point (b,i)(b, i) is handled, live[x]live[x] is the set of definitions of xx that reach (b,i)(b, i), for every name xx.

Proof. By induction on ii. For i=0i = 0, line L9 sets livelive from IN[b]=RIN[b]IN[b] = RIN[b] by Lemma 2. For i+1≤nbi + 1 \le n_b: the only edge into (b,i+1)(b, i + 1) comes from (b,i)(b, i). A path clear for xx to (b,i+1)(b, i + 1) is either the path of length 0 from the point after d=(b,i,x)d = (b, i, x), or a path clear for xx to (b,i)(b, i) followed by one step, and then (b,i)(b, i) must not define xx, because it is not the last point. So if point (b,i)(b, i) defines xx, the set for xx at (b,i+1)(b, i + 1) is {(b,i,x)}\{(b, i, x)\}, and otherwise it is the set at (b,i)(b, i). Line L12 makes exactly this change, and does it after the uses of point (b,i)(b, i) have been read. □\square

Theorem. chains returns exactly the chains of the definition.

Proof. For a use at a point that is not a phi, including a terminator, line L11 links it to live[x]live[x], which by Lemma 3 is the set of definitions that reach the point. For a phi operand xx from the predecessor pp, the code links the use to the definitions of xx in OUT[p]=ROUT[p]OUT[p] = ROUT[p], the definitions that reach the end of pp. These are the two cases of the definition. Each pair is added to both dudu and udud. □\square

Cost. Let EE be the number of edges of the control flow graph, II the number of instructions and CC the number of chains. With bit vectors of DD bits, one pass costs O((B+E) D/w)O((B + E)\, D / w) word operations on a machine with ww-bit words, and by Lemma 2 there are at most BD+1B D + 1 passes. The scan costs O(I+C)O(I + C) set operations plus the cost of reading the ININ sets. The bound on the passes is crude. Kam and Ullman showed that for problems of this kind, round-robin iteration in reverse postorder needs at most k+2k + 2 passes, where kk is the loop connectedness of the graph; that result is cited, not proved here.

What is proved and what is measured. Lemmas 1 to 3 and the theorem are proved here, for the chains of the definition above. They say nothing about stores through pointers: a store *p = a writes a variable without naming it, so a program that takes the address of a name can read a value that no chain explains. The tests compare the result with a graph search from each definition over the point graph, with the union over all paths of acyclic programs, and with random walks on programs with loops. The pass counts in the tests are measurements.

Complexity

Let BB be the number of blocks, EE the number of edges, II the number of instructions, DD the number of definition sites, UU the number of use sites and CC the number of links.

part time space
GEN and KILL (line L1) O(I)O(I) O(BD/w)O(B D / w) words as bit vectors
one pass of lines L4 to L6 O((B+E) D/w)O((B + E)\, D / w) word operations
the scan (lines L8 to L12) O(I+C)O(I + C) set operations plus reading the IN sets
the chains Θ(C)\Theta(C), with C≤D⋅UC \le D \cdot U

Proved. At most BD+1B D + 1 passes, in the proof file. The number of links can be quadratic: kk blocks that each set x and jump to one join block, followed by kk reads of x and ret x, give k(k+1)k (k + 1) links, because each of the k+1k + 1 uses is reached by all kk definitions. In SSA form the join gets one phi with kk operands and the count is 2k+12k + 1: kk links into the phi and k+1k + 1 out of it.

Cited, not proved. For bit-vector problems such as reaching definitions, round-robin iteration in reverse postorder needs at most the loop connectedness plus 2 passes (Kam-Ullman bound). Structured programs have small loop connectedness, so a few passes are usual.

Measured, not proved. Over 3,000 seeded random toy programs with loops and up to 9 blocks, the iteration took 1 pass on 46 programs, 2 on 2,571, 3 on 363 and 4 on 20. On one random program with 400 blocks it took 13 passes and built 19,451 links; on one with 1,600 blocks, 12 passes and 348,930 links, which shows how fast the chains grow on large functions.

Variants

  • Static single assignment form. Rename each definition so that every name has one, and put phi-functions at joins. Then the ud-chain of each use has exactly one element, the du-chain of a name is its list of uses, and the size is linear in the program. Most modern compilers keep this form instead of chains.
  • Webs. A web is a maximal set of du-chains of one name that share uses. Each web becomes one live range in Chaitin-style register allocation, and different webs of the same name can get different registers.
  • Data dependence edges. In a program dependence graph, the data edges are the def-use chains, next to the control dependence edges.
  • Only one direction. Some passes need only ud-chains, for example constant propagation, which asks "what can this use see". Others need only du-chains, for example dead code elimination, which asks "is this value read".
  • Pointers and calls. With pointer analysis, a store *p = a becomes a possible definition of each variable that p may point to. Such a definition does not kill the earlier ones, because the store may write somewhere else.
  • Sparse analyses. Constant propagation and similar analyses can run over the chains instead of over the blocks, so that they only visit places where a value can flow. Sparse conditional constant propagation does this on SSA form.

When to use it

Use def-use chains when an analysis or optimization asks again and again which definitions a use can see, or which uses a definition feeds, and the program is not in SSA form: in a simple compiler, in a debugger or program analysis tool that works on the original variables, or in a register allocator that builds webs. For a full optimizing compiler, SSA form gives the same information in linear size and is easier to keep up to date when the code changes.

Pitfalls

  • Phi operands. A phi operand from predecessor pp is a use at the end of pp, not at the top of the join block. Treating it as a use at the join links it to definitions that come in on other edges.
  • Pointers. If a variable's address is taken, a store through a pointer can change it, and chains built from names alone miss that definition. Either treat such stores as possible definitions or leave address-taken variables out.
  • Uninitialized variables. A ud-chain lists the definitions that reach a use, but it does not say whether some path reaches the use with no definition at all. Add a dummy definition of every name at the entry to find such paths.
  • Unreachable code. A definition in a block that the entry does not reach still has paths to later uses, and the iteration counts it. Delete unreachable blocks first if this matters.
  • Size. The number of links can grow with the square of the number of definitions of a name. Large generated functions can make the chains much bigger than the code.
  • Stale chains. A transformation that moves, copies or deletes an instruction changes the chains. Rebuild them or update them, or the next pass works on wrong facts.

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.

def_use_chains.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/def-use-chains/. The authors are listed in prov/XZ8C52.jsonl.
"""Def-use and use-def chains for a toy IR program.

A definition site is a tuple (label, i, x): instruction i of block label
defines the name x. A parameter x is the site (entry, -1, x): it is defined
on the way into the program, before the first instruction of the entry
block. A use site is (label, i, x): instruction i of block label reads x,
where i = len(instrs) stands for the terminator.

chains(prog) returns (du, ud). du maps every definition site to the sorted
list of use sites it reaches, and ud maps every use site to the sorted list
of definition sites that reach it. A definition d of x reaches a use u of x
if some path in the control flow graph goes from just after d to u and
does not define x again on the way. A phi operand that comes from the
predecessor p is used at the end of p. A store *p = a defines no name, so
names whose address is taken get incomplete chains (see the page).

reaching(prog) returns the sets IN and OUT of reaching definitions per
block, found by round-robin iteration in reverse postorder.
"""

import toyir


def _order(prog):
    """The labels in reverse postorder from the entry, then the labels that
    the entry does not reach, in program order."""
    seen = {prog.entry}
    post = []
    stack = [(prog.entry, iter(toyir.succs(prog, prog.entry)))]
    while stack:
        v, it = stack[-1]
        w = next(it, None)
        if w is None:
            post.append(v)
            stack.pop()
        elif w not in seen:
            seen.add(w)
            stack.append((w, iter(toyir.succs(prog, w))))
    rest = [lab for lab in prog.blocks if lab not in seen]
    return post[::-1] + rest


def reaching(prog):
    """Return (IN, OUT, passes): dicts from label to a frozenset of
    definition sites, and the number of passes of the iteration."""
    entry = prog.entry
    preds = toyir.preds(prog)
    gen = {}
    kill = {}
    for lab, block in prog.blocks.items():  # @line L1
        last = {}
        for i, ins in enumerate(block.instrs):
            x = toyir.defs(ins)
            if x is not None:
                last[x] = (lab, i, x)
        gen[lab] = frozenset(last.values())
        kill[lab] = frozenset(last)
    params = frozenset((entry, -1, x) for x in prog.params)
    out = {lab: gen[lab] for lab in prog.blocks}  # @line L2
    into = {}
    order = _order(prog)
    passes = 0
    changed = True
    while changed:  # @line L3
        changed = False
        passes += 1
        for lab in order:  # @line L4
            s = set(params) if lab == entry else set()  # @line L5
            for p in preds[lab]:
                s |= out[p]
            into[lab] = frozenset(s)
            new = gen[lab] | frozenset(d for d in s if d[2] not in kill[lab])  # @line L6
            if new != out[lab]:
                out[lab] = new
                changed = True  # @line L7
    return into, out, passes


def chains(prog):
    into, out, _ = reaching(prog)
    preds = toyir.preds(prog)
    du = {}
    ud = {}
    for x in prog.params:
        du[(prog.entry, -1, x)] = set()
    for lab, block in prog.blocks.items():
        for i, ins in enumerate(block.instrs):
            x = toyir.defs(ins)
            if x is not None:
                du[(lab, i, x)] = set()

    def link(defs, use):
        ud.setdefault(use, set()).update(defs)
        for d in defs:
            du[d].add(use)

    for lab, block in prog.blocks.items():  # @line L8
        live = {}
        for d in into[lab]:  # @line L9
            live.setdefault(d[2], set()).add(d)
        n = len(block.instrs)
        for i in range(n + 1):  # @line L10
            if i == n:
                for x in toyir.term_uses(block.term):
                    link(live.get(x, ()), (lab, i, x))
                break
            ins = block.instrs[i]
            if ins[0] == "phi":
                for p, a in ins[2].items():
                    if p not in preds[lab]:
                        raise ValueError("phi in %s names %r, which is not a predecessor" % (lab, p))
                    if isinstance(a, str):
                        link([d for d in out[p] if d[2] == a], (lab, i, a))
            else:
                for x in toyir.uses(ins):
                    link(live.get(x, ()), (lab, i, x))  # @line L11
            x = toyir.defs(ins)
            if x is not None:
                live[x] = {(lab, i, x)}  # @line L12
    du = {d: sorted(us) for d, us in du.items()}  # @line L13
    ud = {u: sorted(ds) for u, ds in ud.items()}
    return du, ud
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_def_use_chains.py 289 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/def-use-chains/. The authors are listed in prov/XZ8C52.jsonl.

import random

import pytest

import toyir
from def_use_chains import chains, reaching

ODD_SUM = """
B1:
  i = 0
  s = 0
  jump B2
B2:
  t1 = i < n
  br t1 B3 B6
B3:
  t2 = i % 2
  br t2 B4 B5
B4:
  s = s + i
  jump B5
B5:
  i = i + 1
  jump B2
B6:
  ret s
"""

PHI = """
B0:
  br c B1 B2
B1:
  x1 = 1
  jump B3
B2:
  x2 = 2
  jump B3
B3:
  x3 = phi [B1: x1, B2: x2]
  y = x3 + c
  ret y
"""


def brute_chains(prog):
    """The chains by the definition, one graph search per definition over
    the graph of program points. Point (lab, i) is instruction i of block
    lab, and (lab, len(instrs)) is its terminator. A phi operand from p is
    a use at the end of p."""
    du = {}
    starts = {}
    for x in prog.params:
        starts[(prog.entry, -1, x)] = (prog.entry, 0)
    for lab, block in prog.blocks.items():
        for i, ins in enumerate(block.instrs):
            x = toyir.defs(ins)
            if x is not None:
                starts[(lab, i, x)] = (lab, i + 1)
    for d, start in starts.items():
        x = d[2]
        found = set()
        seen = {start}
        stack = [start]
        while stack:
            lab, i = stack.pop()
            block = prog.blocks[lab]
            if i < len(block.instrs):
                ins = block.instrs[i]
                if ins[0] != "phi" and x in toyir.uses(ins):
                    found.add((lab, i, x))
                if toyir.defs(ins) == x:
                    continue
                nxt = [(lab, i + 1)]
            else:
                if x in toyir.term_uses(block.term):
                    found.add((lab, i, x))
                nxt = []
                for s in toyir.succs(prog, lab):
                    for k, ins in enumerate(prog.blocks[s].instrs):
                        if ins[0] == "phi" and ins[2].get(lab) == x:
                            found.add((s, k, x))
                    nxt.append((s, 0))
            for q in nxt:
                if q not in seen:
                    seen.add(q)
                    stack.append(q)
        du[d] = sorted(found)
    return du


def path_pairs(prog, path):
    """The (definition, use) pairs that one run along the block path shows:
    each use is linked to the last definition of its name before it."""
    last = {x: (prog.entry, -1, x) for x in prog.params}
    pairs = set()
    prev = None
    for lab in path:
        block = prog.blocks[lab]
        incoming = []
        for i, ins in enumerate(block.instrs):
            if ins[0] == "phi":
                a = ins[2].get(prev)
                if isinstance(a, str) and a in last:
                    pairs.add((last[a], (lab, i, a)))
                incoming.append((ins[1], (lab, i, ins[1])))
                continue
            for x, site in incoming:
                last[x] = site
            incoming = []
            for x in toyir.uses(ins):
                if x in last:
                    pairs.add((last[x], (lab, i, x)))
            x = toyir.defs(ins)
            if x is not None:
                last[x] = (lab, i, x)
        for x, site in incoming:
            last[x] = site
        for x in toyir.term_uses(block.term):
            if x in last:
                pairs.add((last[x], (lab, len(block.instrs), x)))
        prev = lab
    return pairs


def as_pairs(du):
    return {(d, u) for d, us in du.items() for u in us}


def all_uses(prog):
    out = set()
    for lab, block in prog.blocks.items():
        for i, ins in enumerate(block.instrs):
            names = ins[2].values() if ins[0] == "phi" else toyir.uses(ins)
            for x in names:
                if isinstance(x, str):
                    out.add((lab, i, x))
        for x in toyir.term_uses(block.term):
            out.add((lab, len(block.instrs), x))
    return out


def test_odd_sum_chains():
    prog = toyir.parse(ODD_SUM)
    du, ud = chains(prog)
    assert du[("B1", 0, "i")] == [("B2", 0, "i"), ("B3", 0, "i"), ("B4", 0, "i"), ("B5", 0, "i")]
    assert du[("B5", 0, "i")] == du[("B1", 0, "i")]
    assert du[("B1", 1, "s")] == [("B4", 0, "s"), ("B6", 0, "s")]
    assert du[("B4", 0, "s")] == [("B4", 0, "s"), ("B6", 0, "s")]
    assert du[("B1", -1, "n")] == [("B2", 0, "n")]
    assert ud[("B6", 0, "s")] == [("B1", 1, "s"), ("B4", 0, "s")]
    assert ud[("B2", 1, "t1")] == [("B2", 0, "t1")]
    assert sum(len(us) for us in du.values()) == 15
    assert reaching(prog)[2] == 3
    assert toyir.run(prog, [6]) == ("ret", 9)


def test_phi_operands_are_used_at_the_predecessor():
    prog = toyir.parse(PHI)
    du, ud = chains(prog)
    assert du[("B1", 0, "x1")] == [("B3", 0, "x1")]
    assert du[("B2", 0, "x2")] == [("B3", 0, "x2")]
    assert ud[("B3", 1, "x3")] == [("B3", 0, "x3")]
    assert du == brute_chains(prog)
    with pytest.raises(ValueError):
        chains(toyir.parse("A:\n  x = phi [Z: 1]\n  ret x\n"))


def test_du_and_ud_are_inverse():
    rng = random.Random(71)
    for _ in range(200):
        prog = toyir.random_program(rng, 4, rng.randint(1, 8), rng.random() < 0.5)
        du, ud = chains(prog)
        assert as_pairs(du) == {(d, u) for u, ds in ud.items() for d in ds}
        assert set(ud) == all_uses(prog)


def test_undefined_and_unreachable():
    prog = toyir.parse("""
# params: a
A:
  br a B C
B:
  y = 1
  jump C
C:
  z = y + a
  ret z
D:
  y = 7
  jump C
""")
    du, ud = chains(prog)
    # On the path A, C no definition of y comes first; the chain lists only B.
    # D is unreachable, but a path from its definition to the use exists.
    assert ud[("C", 0, "y")] == [("B", 0, "y"), ("D", 0, "y")]
    assert ud[("C", 0, "a")] == [("A", -1, "a")]
    assert du == brute_chains(prog)


def test_loop_back_to_the_entry():
    prog = toyir.parse("""
# params: n
E:
  t = n < 3
  n = n + 1
  br t E X
X:
  ret n
""")
    du, ud = chains(prog)
    assert ud[("E", 0, "n")] == [("E", -1, "n"), ("E", 1, "n")]
    assert ud[("X", 0, "n")] == [("E", 1, "n")]
    assert du == brute_chains(prog)


def test_random_programs_match_the_definition():
    rng = random.Random(73)
    for _ in range(300):
        prog = toyir.random_program(rng, 4, rng.randint(1, 8), rng.random() < 0.4)
        du, _ = chains(prog)
        assert du == brute_chains(prog)


def test_acyclic_programs_match_all_paths():
    rng = random.Random(79)
    for _ in range(300):
        prog = toyir.random_program(rng, 4, rng.randint(1, 8), True)
        du, _ = chains(prog)
        seen = set()
        for path in toyir.paths(prog):
            seen |= path_pairs(prog, path)
        assert as_pairs(du) == seen


def test_random_walks_stay_inside_the_chains():
    rng = random.Random(83)
    for _ in range(300):
        prog = toyir.random_program(rng, 4, rng.randint(2, 8), False)
        pairs = as_pairs(chains(prog)[0])
        for _ in range(5):
            path = [prog.entry]
            while toyir.succs(prog, path[-1]) and len(path) < 40:
                path.append(rng.choice(toyir.succs(prog, path[-1])))
            assert path_pairs(prog, path) <= pairs


def test_passes_bound_on_reducible_programs():
    # Reaching definitions in reverse postorder: random programs are
    # reducible, so their loop connectedness is small.
    rng = random.Random(89)
    worst = 0
    for _ in range(300):
        prog = toyir.random_program(rng, 4, rng.randint(1, 9), False)
        worst = max(worst, reaching(prog)[2])
    assert 2 <= worst <= 4


def join_program(k):
    lines = ["T1:"]
    for i in range(1, k + 1):
        lines.append("T%d:" % i if i > 1 else "")
        nxt = "T%d" % (i + 1) if i < k else "D%d" % i
        lines.append("  br c D%d %s" % (i, nxt))
    for i in range(1, k + 1):
        lines += ["D%d:" % i, "  x = %d" % i, "  jump J"]
    lines.append("J:")
    for j in range(k):
        lines.append("  y%d = x + %d" % (j, j))
    lines.append("  ret x")
    return toyir.parse("\n".join(line for line in lines if line))


def test_k_definitions_and_k_uses_give_k_squared_chains():
    for k in (2, 5, 20):
        prog = join_program(k)
        du, _ = chains(prog)
        links = sum(len(us) for d, us in du.items() if d[2] == "x")
        assert links == k * (k + 1)
        assert du == brute_chains(prog)


def test_bigger_program():
    rng = random.Random(97)
    prog = toyir.random_program(rng, 6, 60, False)
    du, _ = chains(prog)
    assert du == brute_chains(prog)

History

Reaching definitions was among the first global data-flow problems that optimizing compilers solved, in the work of Allen and Cocke at IBM in the late 1960s and 1970s, and the chains were the usual way to keep its answer per use. Kennedy's paper of 1978 described use-definition chains and many optimizations built on them. Textbooks of the 1980s and 1990s, among them the dragon book and Muchnick, presented du-chains, ud-chains and webs as the standard tools of global optimization. Static single assignment form, from Cytron, Ferrante, Rosen, Wegman and Zadeck (1991), made each ud-chain a single definition and replaced explicit chains in most compilers.

References

  1. Ken Kennedy, Use-definition chains with applications, Computer Languages 3(3), 1978, pages 163-179, use-definition chains, how to compute them from reaching definitions, and their use in program optimization
  2. Alfred V. Aho, Monica S. Lam, Ravi Sethi and Jeffrey D. Ullman, Compilers, Principles, Techniques, and Tools, second edition, Addison-Wesley, 2007, Section 9.2.4 (reaching definitions, with gen and kill sets per block and the iterative solution)
  3. Steven S. Muchnick, Advanced Compiler Design and Implementation, Morgan Kaufmann, 1997, Chapter 8 (Data-Flow Analysis), the section on du-chains, ud-chains and webs
  4. Keith D. Cooper and Linda Torczon, Engineering a Compiler, third edition, Morgan Kaufmann, 2022, Chapter 9 (Data-Flow Analysis), iterative data-flow analysis and static single-assignment form

Where this leads

About this page

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

LadderLevelWhat the next level needs
Human proofH2 full proof
  • correctness: no review record reviews/XZ8C52/proof-correctness.yaml
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)
WritingW4 complete
  • a review of the text: no review record reviews/XZ8C52/text.yaml