Algorithm Search⌘K

Algorithmcore

Aggressive dead code elimination

Also called ADCE, mark-sweep dead code elimination.

Marks instructions with side effects as live, then marks what they depend on through data and control dependence, and deletes the rest.

Time
O(b^2 n + n^2) worst
Space
O(n^2 + b^2) extra
Where
b = the number of blocks; n = the number of statements (instructions and terminators)
Properties
deterministicofflineiterative

Aggressive dead code elimination treats every statement as useless until it is shown to be useful. It starts from the statements whose effect someone can see, such as returns, stores, calls and operations that may trap. Then it marks the statements they depend on: the definitions that reach the names they read, and the branches that decide whether they run. Everything left unmarked is deleted, and an unmarked branch becomes a jump. Unlike dead code elimination based on liveness, it removes values that only feed themselves around a loop, branches with no useful code behind them, and whole loops that compute nothing. The marking resembles the mark phase of a mark-and-sweep garbage collector, but it is not garbage collection: it works on the statements of a program at compile time, not on objects in memory at run time.

In plain words

Start from the lines of the program that matter on their own: a line that returns the answer, writes to memory, calls a function, or can crash. Mark them. Then ask, for each marked line, which earlier lines computed the numbers it reads, and which tests decide whether it runs. Mark those too, and ask the same about them. When nothing new gets marked, every line without a mark is useless, so delete it. A test that guards nothing marked is useless too. The program jumps straight to the next place where marked work happens. The method assumes that a loop which does nothing useful also ends, because it deletes such loops.

The problem

The input is a program of the toy IR of three-address code without phi-functions, in which every block reaches a ret. The output is a program that has the same outcome on every input on which the input program ends: the same return value or the same trap. It should contain as few statements as possible. A statement is an instruction or a terminator.

Deciding which statements can really affect the outcome is undecidable (see the full employment theorem). The algorithm gives a safe approximation through two kinds of dependence. A statement SS is data dependent on a definition DD if DD defines a name that SS reads and DD reaches SS, in the sense of reaching definitions. A block YY is control dependent on a block CC if YY post-dominates a successor of CC but does not strictly post-dominate CC: one way out of CC forces YY to run, and another can skip it. Post-dominance is computed with a virtual exit node after every ret block.

The algorithm

A statement is critical if it is a ret, a store, a call, an alloc, an operation that may trap (/ or % by a divisor that may be zero, a shift by a count that may be outside 0 to 63), or a definition of an address-taken name, which a load or a call can read through a pointer. A block is useful if it holds a marked statement.

  1. AggressiveDeadCode(P)
  2. 1compute the post-dominator tree with a virtual exit, the control dependences and the reaching definitions of P
  3. 2Marked <- empty; Work <- empty
  4. 3for each statement S of a reachable block do
  5. 4if S is critical then mark S and add S to Work
  6. 5while Work is not empty do
  7. 6take a statement S out of Work
  8. 7for each definition D that reaches S and defines a name that S reads do
  9. 8if D is not marked then mark D and add D to Work
  10. 9for each block C on which the block of S is control dependent do
  11. 10if the branch of C is not marked then mark it and add it to Work
  12. 11for each reachable block B do
  13. 12delete the unmarked instructions of B
  14. 13if the terminator of B is a branch that is not marked then
  15. 14N <- ipdom(B); while N is not useful do N <- ipdom(N)
  16. 15replace the branch by jump N
  17. 16delete the blocks that the entry no longer reaches
  18. 17return P

Lines L2 to L10 are the mark phase and lines L11 to L16 the sweep. A jump is never marked and never deleted. Line L9 uses the control dependences, which are the reverse dominance frontier: the blocks in the dominance frontier of YY in the reverse graph. The implementation finds them as Ferrante, Ottenstein and Warren do. For each branch block CC and each successor ss, it walks up the post-dominator tree from ss to ipdom(C)\mathrm{ipdom}(C), and every block on the way, without ipdom(C)\mathrm{ipdom}(C), is control dependent on CC.

Line L14 is the subtle step. A branch that is not marked decides nothing that matters, so the program may go straight to the first useful block that every path from BB reaches, the nearest useful post-dominator. Footnote 11 of Cytron and others says that a dead branch can become a jump "to any one of its prior targets". That is wrong for a branch that closes a useless loop: jumping back to the top of the loop never ends. Cooper and Torczon jump to the nearest marked post-dominator, as here.

Example

The parameters are a and b.

entry:
  s = 0
  i = 0
  q = a / b
  jump h
h:
  t = i < 3
  br t body done
body:
  s = s + i
  k = s & 1
  br k odd even
odd:
  s = s + 1
  jump join
even:
  s = s - 1
  jump join
join:
  i = i + 1
  jump h
done:
  r = a + i
  ret r

The critical statements are q = a / b, which may trap, and ret r. The return reads r, so r = a + i is marked, then i = 0 and i = i + 1, the definitions of i that reach it. join is now useful. It post-dominates body, a successor of h, but not h itself, because h can go to done. So join is control dependent on h, and the branch of h is marked, and with it t = i < 3. Nothing marks s, k, the branch of body, or the blocks odd and even.

The sweep deletes the unmarked instructions. The branch of body becomes a jump to join, its immediate post-dominator, which is useful. Then odd and even are unreachable and go away.

entry:
  i = 0
  q = a / b
  jump h
h:
  t = i < 3
  br t body done
body:
  jump join
join:
  i = i + 1
  jump h
done:
  r = a + i
  ret r

For a=5a = 5, b=2b = 2 both programs return 8. The first one executes 35 statements and the second 22. For b=0b = 0 both trap at the division. Dead code elimination based on liveness removes nothing from s here: s = s + i reads s around the back edge, so s stays live, and the branch of body reads k.

Correctness

The full proof is in the proof file. It assumes that no name is read before it is defined and that every block reaches a ret, and it compares runs of the input that end.

  1. The marks are closed. At the end, every critical statement is marked. Every definition that reaches a name read by a marked statement is marked. And every branch on which a useful block is control dependent is marked.
  2. An unmarked branch leads to its nearest useful post-dominator. Let BB end with an unmarked branch, and follow any path from BB to the first useful block YY after it. If YY did not strictly post-dominate BB, then YY would be control dependent on BB or on a block between them, and that block's branch would be marked, which makes it useful. So YY strictly post-dominates BB, and a short argument on the post-dominator tree shows that YY is the nearest useful one, the target NN of line L14.
  3. The same marked statements run. Follow the old and the new program from block to block. They agree at the start of each block that both visit. Inside it, the old program runs every instruction and the new one only the marked ones, and the unmarked ones cannot trap and write no memory. At an unmarked branch the old program wanders through blocks with no marked statement and arrives at NN, where the new one jumps.
  4. They read the same values. A marked statement reads a name whose last write in the old run was a definition that reaches it, and so is marked, or a store or call, which is critical. By induction that write ran in the new program too, with the same value, and nothing in between changed the name.

So on every input on which the old program ends, the new one ends in the same way and runs at most as many statements. On a run that loops forever inside a loop with no marked statement, the new program may end. This is the termination assumption of the algorithm.

Proof: Aggressive dead code elimination keeps the outcome of every run that endsfull

Setting. PP is a program of the toy IR with no phi-functions, and P′P' is the program that aggressive dead code elimination returns. A statement is an instruction or a terminator. We assume three things:

  1. every block that the entry reaches also reaches a ret block;
  2. no run of PP reads a name before it is defined;
  3. only runs of PP that end are compared: runs that return a value or trap.

Assumption 1 is checked by the implementation, which raises an error otherwise. Assumption 3 is the termination assumption of the algorithm. A loop with no marked statement disappears, so a run of PP that loops forever inside such a loop can end in P′P'. At the end we show that this is the only difference.

Definitions. Add a virtual exit node with an edge from every ret block. A node YY post-dominates XX if every path from XX to the exit passes through YY. It strictly post-dominates XX if also Y≠XY \ne X. By assumption 1 every block has post-dominators, and they form a tree with the exit as its root: ipdom(X)\mathrm{ipdom}(X) is the parent of XX. The strict post-dominators of XX are the nodes on the tree path from ipdom(X)\mathrm{ipdom}(X) to the root. A block YY is control dependent on a block CC if YY post-dominates a successor of CC and YY does not strictly post-dominate CC.

The implementation finds the control dependences on CC by walking, for each successor ss of CC, up the tree from ss to ipdom(C)\mathrm{ipdom}(C), without ipdom(C)\mathrm{ipdom}(C) itself. This gives exactly the definition. ipdom(C)\mathrm{ipdom}(C) post-dominates ss or equals it, so it lies on the tree path from ss to the root. A node YY on that path post-dominates ss. It strictly post-dominates CC exactly when it is ipdom(C)\mathrm{ipdom}(C) or above it, because the strict post-dominators of CC are the nodes from ipdom(C)\mathrm{ipdom}(C) to the root.

A block is useful if it holds a marked statement. Every ret is marked, so every ret block is useful. When the loop of line L5 stops, the marked set has three closure properties:

  • (M1) every critical statement is marked: ret, store, call, alloc, an operation that may trap, and a definition of an address-taken name;
  • (M2) if SS is marked and reads a name uu, every definition of uu that reaches SS is marked;
  • (M3) if a useful block YY is control dependent on CC, the branch of CC is marked.

(M2) and (M3) hold because every marked statement goes through the work list once, and lines L7 to L10 mark what it needs.

Lemma 1: an unmarked branch leads to its nearest useful post-dominator

Let BB be a block whose terminator is an unmarked branch. Take a path B=v0,v1,…,vkB = v_0, v_1, \ldots, v_k in the graph with k≥1k \ge 1, vkv_k useful and v1,…,vk−1v_1, \ldots, v_{k-1} not useful. Then:

(a) vkv_k strictly post-dominates BB;

(b) BB has a useful strict post-dominator, so the walk of line L14 stops at a block NN and never reaches the virtual exit;

(c) vk=Nv_k = N.

Proof of (a). Write Y=vkY = v_k. Let jj be the largest index in 0,…,k−10, \ldots, k-1 such that YY does not strictly post-dominate vjv_j, and suppose that such a jj exists. YY post-dominates vj+1v_{j+1}: if j+1=kj + 1 = k then vj+1v_{j+1} is YY, and otherwise YY strictly post-dominates it by the choice of jj. So YY is control dependent on vjv_j, and by (M3) the branch of vjv_j is marked. If j=0j = 0, this is the branch of BB, which is not marked. If j≥1j \ge 1, then vjv_j is useful, but v1,…,vk−1v_1, \ldots, v_{k-1} are not. Both cases are impossible. So no such jj exists, and in particular YY strictly post-dominates v0=Bv_0 = B.

Proof of (b). By assumption 1 there is a path from BB to a ret block, which is useful and is not BB, since BB ends with a branch. Cut the path at the first useful block after BB. By (a) that block strictly post-dominates BB.

Proof of (c). By (a), Y=vkY = v_k is a useful strict post-dominator of BB. NN is the nearest one, so if Y≠NY \ne N, then YY lies above NN on the tree path to the root, and NN does not appear among v0,…,vkv_0, \ldots, v_k: v0=B≠Nv_0 = B \ne N, the blocks v1,…,vk−1v_1, \ldots, v_{k-1} are not useful, and vk=Yv_k = Y. If some path from YY to the exit avoids NN, then the path from BB through YY to the exit avoids NN, which is impossible, because NN post-dominates BB. So NN post-dominates YY. Also YY post-dominates NN, because it is above NN in the tree. Two nodes that post-dominate each other are equal, so Y=NY = N, which is a contradiction. □\square

Lemma 2: the same marked statements run, with the same values

Fix an input on which the run of PP ends. A step of a run is marked if it executes a marked statement.

Claim. The run of P′P' executes the same marked statements as the run of PP, in the same order, each reading the same values and writing the same values. Between two of them P′P' executes only jumps. P′P' ends in the same way as PP.

Proof. We follow both runs from one meeting point to the next. A meeting point is a moment at which both runs are at the start of the same block XX, with the same values in every name and cell that a marked statement can read next. The runs start at a meeting point, the entry. At a meeting point:

  1. PP runs all instructions of XX, and P′P' runs the marked ones, in the same order. The unmarked ones cannot trap, because every operation that may trap is critical, and they write only names, never memory.
  2. Then PP runs the terminator of XX:
    • a ret is marked, and both programs return;
    • a jump is the same in P′P', and both runs go to the same block;
    • a marked branch reads the same value in both runs, and both go to the same block;
    • an unmarked branch goes to some successor in PP, while P′P' jumps to NN, the nearest useful post-dominator of XX. The run of PP ends, and it ends in a useful block: at a ret, or at a trap, which only a marked operation can cause. So after XX the run of PP reaches some useful block, and by Lemma 1 the first useful block it reaches is NN. On the way it runs only statements of blocks that are not useful, so no marked statement.

In each case both runs next meet at the start of the same block, and PP runs no marked statement between the two meetings that P′P' does not run. Each step of this argument uses at least one block visit of the finite run of PP, so P′P' also reaches the end.

It remains to show that each marked statement reads the same values in both runs. We use induction over the marked steps in their common order. Let SS be a marked statement that reads the name uu.

  • If uu is address-taken, every statement that can write uu is marked: the definitions of uu by (M1), and the stores and calls, which are critical. So the writes to uu before SS are the same marked steps in both runs. By induction they write the same values in the same order, and P′P' runs no other write. So uu has the same value at SS.
  • If uu is not address-taken, only definitions of uu by name write it, because a pointer in the toy IR points to a heap cell or to an address-taken name. In the run of PP, let WW be the last definition of uu before SS. The part of the run from WW to SS is a path with no other definition of uu, so WW reaches SS, and by (M2) WW is marked. By induction WW writes the same value in P′P'. Between WW and SS, P′P' runs only marked statements that PP also runs there, and none of them defines uu. If no definition of uu comes before SS, then uu is a parameter, and the same argument shows that P′P' does not change it either.

A load or a called function reads memory cells. They are written only by stores, which are marked, and by called functions, which run inside marked calls. Allocations are marked too, so both runs number the heap cells in the same way. By induction the memory is the same at every marked step.

So SS reads the same values, and it does the same thing in both runs: it writes the same value, takes the same branch, returns the same value, or traps. □\square

The theorem

Theorem. For every input on which the run of PP ends, the run of P′P' ends with the same outcome: the same return value, or a trap. P′P' also executes at most as many instructions and terminators as PP.

Proof. The outcome follows from Lemma 2. For the count: P′P' runs a subset of the instructions that PP runs, and each block that P′P' visits stands for a different visit of PP to a block, so it runs at most as many terminators. □\square

Runs that do not end. Suppose the run of PP never ends. If it executes marked statements forever, the meeting points of Lemma 2 go on forever, so the run of P′P' does not end either. Otherwise, after its last marked statement the run of PP stays forever in blocks that are not useful, and P′P' may jump past them and return. This is the case that assumption 3 excludes: the algorithm removes loops with no marked statement and so assumes that they end. A compiler for a language in which a loop with no effect may run forever must mark the branches of loops that it cannot prove to end.

Complexity

With nn statements and bb blocks, the implementation computes reaching definitions by iteration over sets of up to nn definitions, in O(b2n)O(b^2 n) time, and the definitions that reach each statement in O(n2)O(n^2). The post-dominator tree by the iterative algorithm of Cooper, Harvey and Kennedy and the control dependences by the tree walk take O(b2)O(b^2). Each statement enters the work list at most once and looks at its reaching definitions and its control dependences, which is O(n2+nb)O(n^2 + n b) in all. The sweep is O(n+b)O(n + b). On static single assignment form every use has one definition, so the data part of the marking is linear, and the whole algorithm runs in time linear in the program plus the size of the control dependences, as in Cytron and others.

Properties

  • Optimistic. Every statement is assumed dead until proven useful. This finds dead cycles, values that feed only themselves, which a pessimistic pass based on liveness cannot remove.
  • It removes control flow. Branches with nothing useful behind them become jumps, and whole loops that compute nothing disappear.
  • It never costs more on a run that ends. The new program runs a subset of the instructions of the old one, and no more terminators.
  • It needs post-dominators. Every block must reach an exit. A block in an infinite loop with no exit has no post-dominator; a compiler adds a fake edge from such a loop to the exit before it runs the algorithm.

Variants and improvements

  • On SSA form. Cytron and others run the algorithm on static single assignment form. Each use has one definition, and a phi-function is marked like any other statement. When a phi-function is marked, the branches that decide which of its operands arrives must stay too: they mark the last statement of each predecessor block of the phi.
  • Dependence graphs. The marking is a backward walk on the program dependence graph. The same walk from a chosen statement, not from all critical ones, is backward program slicing.
  • Keeping loops that may not end. A language in which an infinite loop without effects is a valid program needs a stronger rule: mark the branch of every loop that is not known to end.
  • With constant propagation. Sparse conditional constant propagation proves that some branches always go one way, and aggressive dead code elimination then removes the dead side and the values that only fed it.

When to use it

Use aggressive dead code elimination after transforms that leave behind computations and branches that no longer matter, such as constant propagation, inlining and copy propagation. It is more costly than a liveness pass because it needs post-dominators and control dependences, so compilers run the simple pass often and the aggressive one a few times. Do not use it where a loop that runs forever and does nothing is a valid behavior that must be kept, unless the loops it removes are known to end.

Pitfalls

  • The wrong jump target. Replacing an unmarked branch by a jump to one of its old targets can turn a loop that ends into one that does not. In w: j = j + 1; k = j < 5; br k w out, with j used nowhere else, jumping to w loops forever. The nearest useful post-dominator is out.
  • Loops that do not end. In h: i = i + 0; br a h done, nothing in h is useful, so the branch becomes a jump to done. For a≠0a \ne 0 the old program never ends and the new one returns. This is the price of the termination assumption.
  • Effects that are not stores. A trap is an outcome. An operation that may trap must be critical, or the pass deletes a division by zero. Volatile loads, input and output, and calls to functions that are not known to be pure are critical too.
  • Hidden reads through pointers. A load through a pointer can read an address-taken name without naming it, so no reaching definition connects them. Treat the definitions of such names as critical, or connect them through alias analysis.
  • Blocks with no exit. Without a virtual exit, or with a block that reaches no exit, post-dominance is not defined. Add the virtual exit, and add fake edges from infinite loops.

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.

aggressive_dead_code_elimination.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/aggressive-dead-code-elimination/. The authors are listed in prov/VFFWX5.jsonl.
"""Aggressive dead code elimination on the toy IR, for programs without
phi-functions.

adce(prog) starts from the critical statements (returns, stores, calls,
allocations, operations that may trap, and definitions of address-taken
names), marks
every definition that reaches a use in a marked statement, and marks every
branch on which a block with a marked statement is control dependent. Then
it deletes the unmarked instructions, replaces each unmarked branch by a jump
to the nearest post-dominator that holds a marked statement, and drops the
blocks that the entry no longer reaches. It returns a new program.

A statement is named by (label, i). For i < len(instrs) it is instruction
i of the block; i == len(instrs) is the terminator.

The result has the same outcome as the input on every run that ends. A run
that loops forever in code with no marked statement may end after the
transform: ADCE assumes that such loops end.
"""

import toyir

EXIT = "<exit>"  # the virtual exit node; no label of the toy IR looks like this


def may_trap(ins):
    """True if the operation can trap in the toy IR: a division or remainder
    by a divisor that may be zero, or a shift by a count that may be outside
    0 to 63."""
    if ins[0] != "op":
        return False
    op, b = ins[2], ins[4]
    if op in ("/", "%"):
        return not (isinstance(b, int) and b != 0)
    if op in ("<<", ">>"):
        return not (isinstance(b, int) and 0 <= b <= 63)
    return False


def address_taken(prog):
    return {ins[2] for blk in prog.blocks.values() for ins in blk.instrs if ins[0] == "addr"}


def critical(ins, taken):
    """A statement that must stay whatever the rest of the program does."""
    if ins[0] in ("store", "call"):
        return True
    if ins[0] == "alloc":
        # The toy IR numbers heap cells in the order of the allocations, so
        # deleting one would rename the cells that later allocations get.
        return True
    if may_trap(ins):
        return True
    # A load or a call can read an address-taken name through a pointer,
    # which no reaching definition shows.
    return ins[1] in taken


def reachable(prog):
    seen = {prog.entry}
    stack = [prog.entry]
    while stack:
        v = stack.pop()
        for w in toyir.succs(prog, v):
            if w not in seen:
                seen.add(w)
                stack.append(w)
    return seen


def postdominators(prog, labels):
    """The immediate post-dominator of each block of labels, with a virtual
    exit EXIT after every ret block. Uses the iterative algorithm of Cooper,
    Harvey and Kennedy on the reverse graph."""
    # Successors in the reverse graph: the predecessors, and for EXIT the
    # ret blocks.
    rsucc = {b: [] for b in labels}
    rsucc[EXIT] = []
    for b in labels:
        ss = toyir.succs(prog, b)
        if not ss:
            rsucc[EXIT].append(b)
        for s in ss:
            rsucc[s].append(b)
    order = []
    seen = {EXIT}
    stack = [(EXIT, iter(rsucc[EXIT]))]
    while stack:
        v, it = stack[-1]
        w = next(it, None)
        if w is None:
            order.append(v)
            stack.pop()
        elif w not in seen:
            seen.add(w)
            stack.append((w, iter(rsucc[w])))
    missing = [b for b in labels if b not in seen]
    if missing:
        raise ValueError("block %r reaches no ret; ADCE needs every block to reach an exit" % missing[0])
    num = {v: i for i, v in enumerate(order)}  # postorder numbers
    rpo = order[::-1]
    ipdom = {EXIT: EXIT}

    def intersect(a, b):
        while a != b:
            while num[a] < num[b]:
                a = ipdom[a]
            while num[b] < num[a]:
                b = ipdom[b]
        return a

    changed = True
    while changed:
        changed = False
        for v in rpo:
            if v is EXIT:
                continue
            new = None
            # The reverse-graph predecessors of v are its CFG successors.
            for p in toyir.succs(prog, v) or [EXIT]:
                if p in ipdom:
                    new = p if new is None else intersect(p, new)
            if ipdom.get(v) != new:
                ipdom[v] = new
                changed = True
    return ipdom


def control_dependence(prog, labels, ipdom):
    """cd[y] is the set of blocks c whose branch y is control dependent on:
    y post-dominates a successor of c and does not strictly post-dominate c.
    This is the reverse dominance frontier of y."""
    cd = {b: set() for b in labels}
    for c in labels:
        ss = toyir.succs(prog, c)
        if len(ss) < 2:
            continue
        for s in ss:
            runner = s
            while runner != ipdom[c]:
                cd[runner].add(c)
                runner = ipdom[runner]
    return cd


def reaching_uses(prog, labels):
    """For each statement (label, i), the set of statements (label, j) that
    define a name it reads and reach it along some path with no other
    definition of that name. Parameters have no defining statement."""
    sites = {}
    for b in labels:
        for i, ins in enumerate(prog.blocks[b].instrs):
            x = toyir.defs(ins)
            if x is not None:
                sites.setdefault(x, set()).add((b, i))
    gen, kill = {}, {}
    for b in labels:
        last = {}
        for i, ins in enumerate(prog.blocks[b].instrs):
            x = toyir.defs(ins)
            if x is not None:
                last[x] = (b, i)
        gen[b] = set(last.values())
        kill[b] = set().union(*(sites[x] for x in last)) if last else set()
    allpred = toyir.preds(prog)
    pred = {b: [p for p in allpred[b] if p in labels] for b in labels}
    inn = {b: set() for b in labels}
    out = {b: set(gen[b]) for b in labels}
    changed = True
    while changed:
        changed = False
        for b in labels:
            i = set().union(*(out[p] for p in pred[b])) if pred[b] else set()
            o = gen[b] | (i - kill[b])
            inn[b] = i
            if o != out[b]:
                out[b] = o
                changed = True
    result = {}
    for b in labels:
        blk = prog.blocks[b]
        cur = {}
        for d in inn[b]:
            x = toyir.defs(prog.blocks[d[0]].instrs[d[1]])
            cur.setdefault(x, set()).add(d)
        for i, ins in enumerate(blk.instrs):
            r = set()
            for u in toyir.uses(ins):
                r |= cur.get(u, set())
            result[(b, i)] = r
            x = toyir.defs(ins)
            if x is not None:
                cur[x] = {(b, i)}
        r = set()
        for u in toyir.term_uses(blk.term):
            r |= cur.get(u, set())
        result[(b, len(blk.instrs))] = r
    return result


def mark(prog):
    """The marked statements, and the analysis results the sweep needs."""
    for blk in prog.blocks.values():
        for ins in blk.instrs:
            if ins[0] == "phi":
                raise ValueError("this ADCE works on programs without phi-functions")
    labels = [b for b in prog.blocks if b in reachable(prog)]
    ipdom = postdominators(prog, labels)  # @line L1
    cd = control_dependence(prog, labels, ipdom)
    reach = reaching_uses(prog, labels)
    taken = address_taken(prog)
    marked = set()  # @line L2
    work = []
    for b in labels:  # @line L3
        blk = prog.blocks[b]
        for i, ins in enumerate(blk.instrs):
            if critical(ins, taken):  # @line L4
                marked.add((b, i))
                work.append((b, i))
        if blk.term[0] == "ret":
            marked.add((b, len(blk.instrs)))
            work.append((b, len(blk.instrs)))
    while work:  # @line L5
        s = work.pop()  # @line L6
        for d in reach[s]:  # @line L7
            if d not in marked:  # @line L8
                marked.add(d)
                work.append(d)
        for c in cd[s[0]]:  # @line L9
            t = (c, len(prog.blocks[c].instrs))
            if t not in marked:  # @line L10
                marked.add(t)
                work.append(t)
    return marked, labels, ipdom


def adce(prog):
    marked, labels, ipdom = mark(prog)
    useful = {b for (b, _) in marked}
    blocks = {}
    for b in labels:  # @line L11
        blk = prog.blocks[b]
        instrs = [ins for i, ins in enumerate(blk.instrs) if (b, i) in marked]  # @line L12
        term = blk.term
        if term[0] == "br" and (b, len(blk.instrs)) not in marked:  # @line L13
            n = ipdom[b]  # @line L14
            while n not in useful:
                if n is EXIT:
                    raise AssertionError("an unmarked branch has no useful post-dominator")
                n = ipdom[n]
            term = ("jump", n)  # @line L15
        blocks[b] = toyir.Block(instrs, term)
    out = toyir.Program(list(prog.params), blocks)
    live = reachable(out)  # @line L16
    out.blocks = {b: blk for b, blk in out.blocks.items() if b in live}
    return out  # @line L17
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_aggressive_dead_code_elimination.py 276 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/aggressive-dead-code-elimination/. The authors are listed in prov/VFFWX5.jsonl.

import random

import toyir
from aggressive_dead_code_elimination import adce, mark, may_trap

PAGE = """
# params: a, b
entry:
  s = 0
  i = 0
  q = a / b
  jump h
h:
  t = i < 3
  br t body done
body:
  s = s + i
  k = s & 1
  br k odd even
odd:
  s = s + 1
  jump join
even:
  s = s - 1
  jump join
join:
  i = i + 1
  jump h
done:
  r = a + i
  ret r
"""

PAGE_AFTER = """
# params: a, b
entry:
  i = 0
  q = a / b
  jump h
h:
  t = i < 3
  br t body done
body:
  jump join
join:
  i = i + 1
  jump h
done:
  r = a + i
  ret r
"""

# A loop with no marked statement. Its branch is replaced by a jump to the
# nearest useful post-dominator, out. Jumping back to w, one of the old
# targets, would loop forever.
USELESS_LOOP = """
# params: a
entry:
  j = 0
  jump w
w:
  j = j + 1
  k = j < 5
  br k w out
out:
  ret a
"""

# With a != 0 the input loops forever in code with no marked statement.
# ADCE assumes that such a loop ends, and the output returns 1.
ENDLESS = """
# params: a
entry:
  i = 0
  jump h
h:
  i = i + 0
  br a h done
done:
  ret 1
"""

# f adds v to the cell q points to and returns the new value.
FUNC_F = toyir.parse("# params: q, v\nentry:\n  w = *q\n  s = w + v\n  *q = s\n  ret s\n")


def steps(prog, args, funcs=None, limit=4096):
    """The number of instructions and terminators a run executes."""
    if toyir.run(prog, args, fuel=limit, funcs=funcs) == ("fuel",):
        return None
    lo, hi = 0, limit
    while lo < hi:
        mid = (lo + hi) // 2
        if toyir.run(prog, args, fuel=mid, funcs=funcs) == ("fuel",):
            lo = mid + 1
        else:
            hi = mid
    return lo


def size(prog):
    return sum(len(blk.instrs) + 1 for blk in prog.blocks.values())


def add_memory(rng, prog, nvars):
    """Insert memory operations: a heap cell p, a pointer r to x3, and stores,
    loads and calls of f at random places."""
    xs = ["x%d" % i for i in range(nvars)]
    entry = prog.blocks[prog.entry]
    entry.instrs += [("alloc", "p"), ("store", "p", 0), ("addr", "r", "x3")]
    for label, blk in prog.blocks.items():
        out = []
        start = len(blk.instrs) if label == prog.entry else 0
        for i, ins in enumerate(blk.instrs):
            out.append(ins)
            if label == prog.entry and i < start - 1:
                continue
            u = rng.random()
            if u < 0.12:
                out.append(("store", "p", rng.choice(xs)))
            elif u < 0.2:
                out.append(("load", rng.choice(xs), "p"))
            elif u < 0.26:
                out.append(("call", rng.choice(xs), "f", ["p", rng.choice(xs)]))
            elif u < 0.32:
                out.append(("store", "r", rng.choice(xs)))
            elif u < 0.38:
                out.append(("load", rng.choice(xs), "r"))
        blk.instrs = out
    return prog


def test_page_example():
    p = toyir.parse(PAGE)
    q = adce(p)
    assert toyir.show(q) == toyir.show(toyir.parse(PAGE_AFTER))
    for a in range(-4, 5):
        for b in (-2, 0, 3):
            assert toyir.run(p, [a, b]) == toyir.run(q, [a, b])
    assert toyir.run(q, [5, 0]) == ("trap",)
    assert toyir.run(q, [5, 2]) == ("ret", 8)
    assert (steps(p, [5, 2]), steps(q, [5, 2])) == (35, 22)


def test_useless_loop_jumps_to_useful_postdominator():
    p = toyir.parse(USELESS_LOOP)
    q = adce(p)
    assert q.blocks["w"].instrs == []
    assert q.blocks["w"].term == ("jump", "out")
    assert toyir.run(q, [4]) == toyir.run(p, [4]) == ("ret", 4)


def test_endless_useless_loop_is_assumed_to_end():
    p = toyir.parse(ENDLESS)
    q = adce(p)
    assert toyir.run(p, [1]) == ("fuel",)
    assert toyir.run(q, [1]) == ("ret", 1)
    assert toyir.run(p, [0]) == toyir.run(q, [0]) == ("ret", 1)


def test_branch_that_guards_a_store_is_kept():
    src = """
# params: a
entry:
  p = alloc
  *p = 0
  c = a < 3
  br c yes no
yes:
  *p = 7
  jump no
no:
  v = *p
  ret v
"""
    p = toyir.parse(src)
    q = adce(p)
    assert q.blocks["entry"].term == ("br", "c", "yes", "no")
    assert ("store", "p", 7) in q.blocks["yes"].instrs
    for a in range(0, 6):
        assert toyir.run(q, [a]) == toyir.run(p, [a])


def test_stores_calls_and_traps_are_kept():
    src = """
# params: a, b
entry:
  p = alloc
  *p = a
  w = call f(p, b)
  d = a / b
  e = a << b
  z = a % 4
  u = a >> 2
  ret 0
"""
    p = toyir.parse(src)
    q = adce(p)
    kinds = [ins[0] for ins in q.blocks["entry"].instrs]
    assert kinds == ["alloc", "store", "call", "op", "op"]
    assert [ins[2] for ins in q.blocks["entry"].instrs[3:]] == ["/", "<<"]
    funcs = {"f": FUNC_F}
    assert toyir.run(q, [3, 0], funcs=funcs) == toyir.run(p, [3, 0], funcs=funcs) == ("trap",)
    assert toyir.run(q, [3, 70], funcs=funcs) == ("trap",)
    assert toyir.run(q, [3, 1], funcs=funcs) == ("ret", 0)


def test_address_taken_name_is_kept():
    src = """
# params: a
entry:
  x = a + 1
  r = &x
  y = *r
  ret y
"""
    p = toyir.parse(src)
    q = adce(p)
    assert ("op", "x", "+", "a", 1) in q.blocks["entry"].instrs
    assert toyir.run(q, [4]) == ("ret", 5)


def test_may_trap():
    assert may_trap(("op", "x", "/", "a", "b"))
    assert may_trap(("op", "x", "%", "a", 0))
    assert not may_trap(("op", "x", "/", "a", -3))
    assert may_trap(("op", "x", "<<", "a", 64))
    assert not may_trap(("op", "x", ">>", "a", 63))
    assert not may_trap(("op", "x", "+", "a", "b"))


def test_errors():
    for src in (
        "entry:\n  jump b\nb:\n  x = phi [entry: 1]\n  ret x\n",
        "entry:\n  jump l\nl:\n  jump l\n",
    ):
        try:
            adce(toyir.parse(src))
        except ValueError:
            continue
        raise AssertionError("expected ValueError")


def test_random_programs():
    rng = random.Random(2026)
    funcs = {"f": FUNC_F}
    removed = 0
    jumps = 0
    traps = 0
    for trial in range(240):
        nvars = 5
        p = toyir.random_program(rng, nvars, rng.randint(4, 8), acyclic=trial % 2 == 0)
        if trial % 3:
            add_memory(rng, p, nvars)
        q = adce(p)
        assert size(q) <= size(p)
        removed += size(p) - size(q)
        marked, _, _ = mark(p)
        jumps += sum(
            1
            for b, blk in p.blocks.items()
            if blk.term[0] == "br" and (b, len(blk.instrs)) not in marked
        )
        for _ in range(6):
            args = [rng.randint(-5, 5), rng.randint(-5, 5)]
            out = toyir.run(p, args, funcs=funcs)
            assert out != ("fuel",)
            assert toyir.run(q, args, funcs=funcs) == out
            traps += out == ("trap",)
            assert steps(q, args, funcs) <= steps(p, args, funcs)
    assert removed > 1000
    assert jumps > 50
    assert traps > 20

History

Dead code elimination by marking useful statements goes back to the optimizing compilers of the 1970s, and the name "aggressive" refers to its optimistic start. Ferrante, Ottenstein and Warren defined control dependence through post-dominance in 1987 and used it for the program dependence graph. Cytron, Ferrante, Rosen, Wegman and Zadeck gave the algorithm on SSA form in 1991, with control dependence computed as the dominance frontier of the reverse graph. Its footnote on how to replace a dead branch was later corrected: Cooper and Torczon jump to the nearest marked post-dominator.

References

  1. Ron Cytron, Jeanne Ferrante, Barry K. Rosen, Mark N. Wegman and F. Kenneth Zadeck, Efficiently computing static single assignment form and the control dependence graph, ACM Transactions on Programming Languages and Systems 13(4), 1991, 451-490, Section 7.1 (Dead Code Elimination), pp. 478-481 and Figure 17, the marking of live statements through definers and control dependence, and footnote 11 on the replacement of a dead branch
  2. Jeanne Ferrante, Karl J. Ottenstein and Joe D. Warren, The program dependence graph and its use in optimization, ACM Transactions on Programming Languages and Systems 9(3), 1987, 319-349, the definition of control dependence by post-dominance, and its computation by a walk up the post-dominator tree
  3. Keith D. Cooper and Linda Torczon, Engineering a Compiler, third edition, Morgan Kaufmann, 2022, Chapter 10 (Scalar Optimizations), the part on eliminating useless code, with the algorithms Mark and Sweep and the jump to the nearest marked post-dominator

About this page

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

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