Algorithm Search⌘K

Algorithmcore

Slicing by dependence graph reachability

Also called Ottenstein PDG slicing.

Computes a backward slice as the set of nodes that reach the criterion in the program dependence graph, in linear time in its size.

Time
O(n + e) worst
Space
O(n) extra
Where
e = the number of control and data edges of the program dependence graph; n = the number of statements
Properties
deterministicnot executable resultofflineiterative
Origin
Karl J. Ottenstein, Linda M. Ottenstein, 1984

Slicing by dependence graph reachability solves the program slicing problem with one backward search. Build the program dependence graph (PDG), whose edges go from each statement to the statements that use its values or that it decides to run. The slice for a criterion is the set of nodes from which the criterion can be reached along these edges. Karl and Linda Ottenstein proposed this in 1984. Once the graph is built, each slice costs time linear in the size of the graph, and slices for other criteria, forward slices and chops come from the same graph. The result is a set of statements, not a program: to run it, the jumps and the block structure must be put back.

In plain words

First draw a map of the program. Each line is a dot. Draw an arrow from one line to another when the second line uses a value that the first line wrote, or when the first line is a test that decides whether the second line runs. To slice, start at the chosen line and walk the arrows backward. Every dot you can reach is in the slice. Each arrow is walked at most once, so the walk is fast, even if the map took some time to draw. One map serves every slice of the same program. The dots you reach tell you which lines matter, but they do not say how to jump between them. To run the slice, you still have to put the jumps back.

The problem

Programs are in the toy IR, with the conventions of the program slicing page: a statement (ℓ,i)(\ell, i) is instruction ii of block ℓ\ell, or its terminator; DEFDEF and REFREF are the variables written and read; every block reaches a ret. The input is a program PP and a criterion ⟨p,V⟩\langle p, V \rangle, the values of the variables of VV just before statement pp. The output is the dependence slice: the least set of instructions and branches that contains the definitions of VV that reach pp and the branches that pp is control dependent on, and that is closed under data and control dependence.

The graph is the PDG of the program dependence graph page. Its nodes are the statements and a node ENTRY, which stands for the start of the run and the values of the parameters. A data edge s→ts \to t labeled xx means that ss defines xx, tt reads xx, and some path in the control flow graph goes from just after ss to tt with no other definition of xx (data dependence, from reaching definitions). A control edge b→tb \to t means that the block of tt is control dependent on the branch bb in the sense of Ferrante, Ottenstein and Warren; the blocks that run on every run get a control edge from ENTRY.

The algorithm

The criterion is not a node, so the search starts from its parents: the definitions of the variables of VV that reach pp, and the control parents of pp. This is the same as adding a node at pp that reads VV.

  1. PDG-SLICE(P, p, V)
  2. 1G <- the PDG of P, unless it is already built
  3. 2W <- the statements s such that a definition of some x in V by s reaches p
  4. 3W <- W union the control parents of p; remove ENTRY from W
  5. 4S <- W
  6. 5while W is not empty do
  7. 6remove a node z from W
  8. 7for each control or data edge x -> z of G do
  9. 8if x is not ENTRY and x is not in S then add x to S and to W
  10. 9return S

Lines L5 to L8 are a graph search over the reversed edges; any order of the work list gives the same set. ENTRY is left out of the result because it is not a statement.

To get a program that runs, build the projection of the problem page: keep the statements of SS, keep every jump, turn each branch outside SS into a jump to the immediate post-dominator of its block (or ret 0 when that is the exit), and let a ret a keep aa only when it is the statement pp and a∈Va \in V. In the implementation, build_pdg builds the graph with the walk of Ferrante, Ottenstein and Warren up the post-dominator tree and with reaching definitions, pdg_slice is the search, executable_slice builds the projection, and observe runs a program and records the values of VV at a point.

Example

Take the program of the problem page, which sums the odd numbers up to nn in ss and computes p=n!p = n!.

B1:
  i = 1
  s = 0
  p = 1
  jump B2
B2:
  t = i <= n
  br t B3 B6
B3:
  p = p * i
  u = i % 2
  br u B4 B5
B4:
  s = s + i
  jump B5
B5:
  i = i + 1
  jump B2
B6:
  ret s

The control edges: ENTRY controls B1, B2 and B6, which run on every run; br t B3 B6 controls B2, B3 and B5 (B2 because the test runs again after each trip); br u B4 B5 controls B4. The data edges into the statements that matter here:

statement data parents control parents
t = i <= n i = 1, i = i + 1, ENTRY for nn ENTRY, br t
br t B3 B6 t = i <= n ENTRY, br t
p = p * i i = 1, i = i + 1, p = 1, p = p * i br t
i = i + 1 i = 1, i = i + 1 br t
p = 1, i = 1 none ENTRY

For the criterion ⟨(B6,0),{p}⟩\langle (B6, 0), \{p\} \rangle, the definitions of pp that reach B6 are p = 1 and p = p * i, and B6 has only ENTRY as control parent. So the search starts from these two. One order of the search:

removed added to SS
start p = 1, p = p * i
p = p * i i = 1, i = i + 1, br t B3 B6
br t B3 B6 t = i <= n
t = i <= n, i = i + 1, i = 1, p = 1 nothing new

The slice has 6 statements, the same as Weiser's algorithm finds: i = 1, p = 1, t = i <= n, br t B3 B6, p = p * i and i = i + 1. None of the jumps is in it, because a jump writes nothing and decides nothing. For ⟨(B6,0),{s}⟩\langle (B6, 0), \{s\} \rangle the same graph gives 8 statements, and for the value of ii just before i = i + 1 it gives i = 1, t = i <= n, br t B3 B6 and i = i + 1.

Where the jumps matter. The next program counts the numbers from 1 to nn that are not multiples of 3. Block B4 is a continue: it jumps back to the loop test.

B1:
  i = 0
  c = 0
  jump B2
B2:
  t = i < n
  br t B3 B6
B3:
  i = i + 1
  r = i % 3
  br r B5 B4
B4:
  jump B2
B5:
  c = c + 1
  jump B2
B6:
  ret c

For ⟨(B6,0),{c}⟩\langle (B6, 0), \{c\} \rangle the slice is every statement except the jumps and the ret. The projection keeps jump B2 in B4 and gives c=4c = 4 for n=6n = 6, like the program. If the slice is turned back into source code by deleting the statements outside it, the continue disappears, control falls into c = c + 1, and the result is 6.

Correctness

The full proof is in the proof file. Its steps:

  1. The search finds the dependence slice. The start set holds exactly the statements of the first two rules of the problem page, the search adds only parents, and it stops with a set closed under all parents. So it returns the least closed set.
  2. Relevant names. For a set SS closed in this way, call a variable relevant at a statement if some path from there carries it, with no new definition, to a use in SS or to VV at pp. A dropped instruction never writes a relevant variable, because the reader would make it a data parent of a statement of SS.
  3. Dropped branches. The blocks that a dropped branch decides, up to its immediate post-dominator, are in the transitive closure of its control dependences, so none of them holds a statement of SS or pp.
  4. The projection keeps the values. A simulation relates the two runs when their environments agree on the relevant variables. It gives the slicing theorem of Reps and Yang (1989): on every input on which the program returns, the projection returns, and the values of VV at pp form the same sequence. More generally, each statement of the slice runs as many times with the same operand values.
Proof: The PDG slice is the dependence slice, and its projection keeps the criterion values on every run that returnsfull

Setting. PP is a toy IR program with instructions x = k, x = y and x = a op b and terminators jump, br and ret, in which every block reaches a ret. Statements, the successor relation n→mn \to m, DEFDEF and REFREF are as on the page. The criterion is C=⟨p,V⟩C = \langle p, V \rangle. Post-dominance is taken on blocks with a virtual EXIT after every ret; dℓd_\ell is the immediate post-dominator of block ℓ\ell. Block yy is control dependent on block xx, written y∈CD(x)y \in CD(x), if some successor ss of xx is post-dominated by yy (y=sy = s allowed) and yy does not strictly post-dominate xx.

The graph. We use the two facts proved on the program dependence graph page and checked by the tests against brute force: the control parents of a statement in block yy are the branches of the blocks xx with y∈CD(x)y \in CD(x), plus ENTRY for some blocks; and the data parents of tt are the pairs (s,x)(s, x) with x∈REF(t)x \in REF(t), x∈DEF(s)x \in DEF(s) and a path from the successor of ss to tt with no definition of xx before tt, plus pairs (ENTRY,x)(\text{ENTRY}, x) for parameters. The reaching definitions at pp are the pairs (s,x)(s, x) with such a path from the successor of ss to pp.

1. The search finds the dependence slice

Let K∗K^\ast be the dependence slice of program slicing: the least set of instructions and branches that contains (rule 1) every ss that defines some x∈Vx \in V with a path from the successor of ss to pp free of definitions of xx, (rule 2) every branch on which pp is control dependent, and (rule 3) every instruction or branch on which a member is data or control dependent.

Lemma 1. PDG-SLICE stops and returns K∗K^\ast.

Proof. Lines L2 and L3 put into the start set exactly the statements of rules 1 and 2 (ENTRY is left out, and it is not a statement). The loop adds a node only if it is not yet in SS, and there are finitely many statements, so it stops. Every node it adds is a parent of a node of SS, so by induction on the order of addition every node of SS is in K∗K^\ast (rule 3). When the loop stops, every node of SS has been removed from the work list once and all its parents other than ENTRY are in SS, so SS is closed under rule 3 and contains the sets of rules 1 and 2. Hence K∗⊆SK^\ast \subseteq S, by the leastness of K∗K^\ast. □\square

Each node enters the work list at most once and each edge is read once, so the search costs O(n+e)O(n + e) for nn statements and ee edges.

2. Relevant names of the slice

From here on, SS is any set of instructions and branches that contains the statements of rules 1 and 2 and is closed under rule 3. Lemma 1 shows that the PDG slice is one. For a statement nn, let R(n)R(n) be the set of names xx such that some path n=n0→n1→⋯→nkn = n_0 \to n_1 \to \cdots \to n_k, k≥0k \ge 0, has no definition of xx among n0,…,nk−1n_0, \ldots, n_{k-1} and ends either at nk=pn_k = p with x∈Vx \in V, or at some nk∈Sn_k \in S with x∈REF(nk)x \in REF(n_k).

Lemma 2. For every statement nn and successor mm:

  • (F1) if n∈Sn \in S, then REF(n)⊆R(n)REF(n) \subseteq R(n); in all cases R(m)∖DEF(n)⊆R(n)R(m) \setminus DEF(n) \subseteq R(n);
  • (F2) if nn is an instruction not in SS, then DEF(n)∩R(m)=∅DEF(n) \cap R(m) = \emptyset, so R(m)⊆R(n)R(m) \subseteq R(n);
  • (F3) if nn is a terminator, then R(m)⊆R(n)R(m) \subseteq R(n);
  • (F4) V⊆R(p)V \subseteq R(p);
  • (F5) for a ret statement rr, R(r)=VR(r) = V if r=pr = p and R(r)=∅R(r) = \emptyset otherwise.

Proof. F1: a path of length 0 for the first part; for the second, put nn in front of the path for xx from mm, which is allowed since nn does not define xx. F2: let x∈DEF(n)∩R(m)x \in DEF(n) \cap R(m) by a path from mm. If it ends at pp with x∈Vx \in V, then nn satisfies rule 1. If it ends at u∈Su \in S that reads xx, then uu is data dependent on nn, and rule 3 puts nn in SS. Both contradict n∉Sn \notin S. The second part follows from F1. F3: a terminator defines nothing, so F1 applies. F4: a path of length 0. F5: a ret has no successor, so only paths of length 0 count, and a ret is never in SS, because SS holds only instructions and branches. □\square

3. Influence and control dependence

For a block ℓ\ell that ends in a branch, let INFL(ℓ)INFL(\ell) be the set of blocks reachable from a successor of ℓ\ell by a path that does not enter d=dℓd = d_\ell. Two standard facts about post-dominance: (PD1) if aa and bb post-dominate each other, then a=ba = b; (PD2) the strict post-dominators of a block form a chain under post-dominance, and the immediate one is post-dominated by all the others.

Lemma 3. Every y∈INFL(ℓ)y \in INFL(\ell) is in CD+(ℓ)CD^+(\ell), the transitive closure of control dependence from ℓ\ell. Also, dd strictly post-dominates every y∈INFL(ℓ)y \in INFL(\ell), and INFL(ℓ)INFL(\ell) holds no ret block when d≠d \ne EXIT.

Proof. (KF) y≠dy \ne d by definition. Take any path from yy to EXIT and put in front of it the path from ℓ\ell to yy that avoids dd after ℓ\ell. The result runs from ℓ\ell to EXIT, so it meets dd, and only in the part after yy. So dd strictly post-dominates yy. If yy were a ret block, the path y→y \to EXIT would avoid d≠d \ne EXIT.

Now let ℓ=s0,s1,…,sk=y\ell = s_0, s_1, \ldots, s_k = y, k≥1k \ge 1, be a path with s1,…,sk≠ds_1, \ldots, s_k \ne d. Induction on kk. Let jj be the largest index in 0,…,k−10, \ldots, k - 1 such that yy does not post-dominate sjs_j. If jj exists, yy post-dominates sj+1s_{j+1} (for j+1=kj + 1 = k trivially), so y∈CD(sj)y \in CD(s_j). For j=0j = 0 this gives y∈CD(ℓ)y \in CD(\ell). For j≥1j \ge 1, sj∈INFL(ℓ)s_j \in INFL(\ell) by a shorter path, so sj∈CD+(ℓ)s_j \in CD^+(\ell) by induction, and y∈CD+(ℓ)y \in CD^+(\ell). If jj does not exist, yy post-dominates ℓ\ell and s1s_1. If y=ℓy = \ell, then y∈CD(ℓ)y \in CD(\ell) through s1s_1, since a block does not strictly post-dominate itself. If y≠ℓy \ne \ell, then yy and dd both strictly post-dominate ℓ\ell, so yy post-dominates dd by PD2, and dd post-dominates yy by KF, so y=dy = d by PD1, which is false. □\square

Lemma 4. If the branch bb at the end of ℓ\ell is not in SS, then no block of INFL(ℓ)INFL(\ell) holds a statement of SS or the point pp.

Proof. Suppose y∈INFL(ℓ)y \in INFL(\ell) holds u∈Su \in S or holds pp. By Lemma 3 there is a chain ℓ=x0,x1,…,xr=y\ell = x_0, x_1, \ldots, x_r = y with xi+1∈CD(xi)x_{i+1} \in CD(x_i) and r≥1r \ge 1. Each xix_i with i<ri < r ends in a branch bib_i, since a block with one successor ss has ss as its immediate post-dominator and so has no control dependents. The statement uu or pp is control dependent on br−1b_{r-1}, so br−1∈Sb_{r-1} \in S by rule 3 or rule 2. Each statement of xi+1x_{i+1}, in particular bi+1b_{i+1}, is control dependent on bib_i, so going down from i=r−2i = r - 2 to 00, rule 3 gives bi∈Sb_i \in S. So b=b0∈Sb = b_0 \in S, a contradiction. □\square

4. The projection

Let QQ be the projection of PP on SS: instructions of SS stay, all jumps stay, a branch of SS stays, a branch b∉Sb \notin S at the end of ℓ\ell becomes jump dℓd_\ell, or ret 0 if dℓd_\ell is EXIT, and a ret a keeps aa only when it is the statement pp and a∈Va \in V (by F5, exactly when a∈Ra \in R there). For n=(ℓ,i)n = (\ell, i), let π(n)=(ℓ,j)\pi(n) = (\ell, j) with jj the number of instructions of SS in ℓ\ell before position ii; it is the place in QQ of the first kept statement of ℓ\ell at or after nn, and pQ=π(p)p_Q = \pi(p).

Consider a run of PP that reads no undefined name. Say (n,σ)∼(q,τ)(n, \sigma) \sim (q, \tau) when q=π(n)q = \pi(n) and, for each x∈R(n)x \in R(n), σ(x)\sigma(x) and τ(x)\tau(x) are both undefined or both defined and equal.

Lemma 5 (one step). Let (n,σ)∼(q,τ)(n, \sigma) \sim (q, \tau).

  1. nn an instruction not in SS that does not trap: PP moves to (m,σ′)(m, \sigma'), QQ stays, and (m,σ′)∼(q,τ)(m, \sigma') \sim (q, \tau).
  2. nn an instruction in SS: PP traps at nn if and only if QQ traps at qq; otherwise both move and the relation holds after the step.
  3. nn a jump or a branch in SS: both move to the start of the same block with unchanged environments, and the relation holds there.
  4. nn a ret: both runs return, with the same value if QQ kept the operand.

Proof. (1) π(m)=π(n)\pi(m) = \pi(n) because nn is not kept, and by F2 nn writes no name of R(m)⊆R(n)R(m) \subseteq R(n). (2) QQ runs the same instruction on operands that agree, by F1, so both trap or both compute the same value for x=DEF(n)x = DEF(n); π(m)\pi(m) is the next statement of QQ, and R(m)⊆R(n)∪{x}R(m) \subseteq R(n) \cup \{x\} by F1. (3) The branch reads names of R(n)R(n) by F1, so it goes the same way; R(m)⊆R(n)R(m) \subseteq R(n) by F3. (4) If the operand is kept, it is in R(n)R(n) by F5. □\square

Lemma 6 (a dropped branch). Let (n,σ)∼(q,τ)(n, \sigma) \sim (q, \tau) with nn a branch b∉Sb \notin S at the end of ℓ\ell, and d=dℓd = d_\ell. QQ makes one step to the start of dd, or returns 0 if dd is EXIT. Until PP first enters dd, it stays in blocks of INFL(ℓ)INFL(\ell), makes no observation and does not return if d≠d \ne EXIT; when it enters dd, its configuration is related to QQ's.

Proof. By the definition of INFLINFL and Lemma 3. By Lemma 4 the blocks visited hold no statement of SS and not pp, so every step there is case 1 of Lemma 5 or a terminator, and by F2 and F3 the sets RR shrink along the run and no relevant name of the later points is written. So the environment of PP at the start of dd agrees with τ\tau on RR there. □\square

Theorem (Reps and Yang). For every input II on which the run of PP reads no undefined name and reaches a ret, the run of QQ reaches a ret and obsQ(I,⟨pQ,V⟩)=obsP(I,⟨p,V⟩)\mathrm{obs}_Q(I, \langle p_Q, V \rangle) = \mathrm{obs}_P(I, \langle p, V \rangle). If the run of PP traps or does not end, obsP\mathrm{obs}_P is a prefix of obsQ\mathrm{obs}_Q.

Proof. At the start the relation holds. Lemmas 5 and 6 cut the run of PP into pieces, each matched with at most one step of QQ, and keep the relation at the end of each piece. The block of pp is never inside a dropped region (Lemma 4), so the visits of the two runs to it match one to one. In a visit, QQ reaches π(p)\pi(p) when PP reaches its last kept statement before pp, or the block start, and the statements of PP between there and pp are dropped instructions, which keep the relation. So at each observation, the environments agree on R(p)⊇VR(p) \supseteq V (F4), and the tuples are equal. If PP returns, QQ returns at the matching moment (Lemma 5 case 4, or Lemma 6 with dd = EXIT), and neither observes again. If PP traps at a dropped instruction, QQ may go on and observe more; at a kept one, QQ traps too. If PP does not end, each of its observations is matched in order. □\square

Corollary. Since the PDG slice SS contains the data and control parents of each of its statements, the hypotheses of section 2 also hold for the criterion ⟨t,REF(t)⟩\langle t, REF(t) \rangle for every t∈St \in S. The projections for the two criteria differ only in the operands of ret, which change no observation before the return. So on every run of PP that returns, QQ reaches each statement tt of the slice as many times as PP does, with the same values of REF(t)REF(t) each time. This is the form in which Reps and Yang stated their slicing theorem for terminating runs.

Complexity

Proved. Each node enters the work list at most once, and each edge is read once when its target is removed. So the search takes O(n+e)O(n + e) time, where nn is the number of statements and ee the number of control and data edges. It needs O(n)O(n) extra space for SS and the work list.

Building the graph. The graph itself costs more, and it can have Θ(n2)\Theta(n^2) edges, for example kk definitions of one variable that all reach kk uses. The program dependence graph page gives the cost: control edges in O(m+c)O(m + c) after post-dominators, and data edges from reaching definitions. The graph is built once and serves every slice of the program, so the cost of building it is shared among all the slices.

Compared. Weiser's algorithm needs no graph but solves dataflow equations again for each criterion, up to c+1c + 1 times for cc branches. Both give the same set of statements.

Properties

  • Same set as Weiser. For one procedure, the reachable set is exactly the dependence slice, which is also the set of Weiser's algorithm.
  • Not a program. The result is a set of nodes. Jumps never appear in it, and a branch outside it must be rerouted to its post-dominator before the slice runs.
  • Many slices from one graph. After the graph is built, each backward slice, each forward slice (the same search over the edges in their own direction) and each chop costs linear time.
  • Static. The slice holds for every input. It can contain statements that no run needs.
  • Deterministic. The order of the work list changes the order of the visits, not the set.

Variants and improvements

  • Forward slices and chops. Search along the edges instead of against them to find what a statement can affect. Intersect a forward and a backward slice to get the chop between two statements.
  • Across procedures. Joining the PDGs of the procedures with call and parameter edges and searching naively mixes calling contexts. System dependence graph slicing of Horwitz, Reps and Binkley adds summary edges and searches in two phases.
  • Unstructured jumps. Ball and Horwitz (1993) and Agrawal (1994) give methods that add to the slice the goto, break and continue statements that a source-level slice needs.
  • Dynamic dependence graphs. Built from one run instead of from the program text, the same search gives dynamic slices.
  • Dead code. With all outputs as the criterion, the statements outside the slice are dead; aggressive dead code elimination works this way.

When to use it

Use it when many slices of the same program are needed: in a debugger or an editor that shows slices on demand, in tools for program understanding, in change impact analysis with forward slices, and in program integration. Build the graph once and answer each query with one search. For a single slice where an executable program is wanted and no graph is at hand, Weiser's algorithm is simpler.

Pitfalls

  • Expecting a runnable program. The slice is a set of nodes. It runs only after the jumps are kept and the branches outside it are rerouted to their immediate post-dominators. Deleting statements from source code with goto, break or continue can change where control goes, as the continue example shows.
  • Starting at the criterion node. The node of pp itself and its own data parents are the slice of the statement pp with V=REF(p)V = REF(p). For another set VV, start from the definitions of VV that reach pp and the control parents of pp.
  • Missing the edge from ENTRY. Without the control edges from ENTRY, the statements that run on every run have no control parent. This does not change the slice of a single procedure, but across procedures it loses the dependence of a callee on its call sites.
  • Using a weak control dependence. Some tools make the code after a loop depend on the loop test. That keeps non-termination, but it gives larger slices than the dependence slice of the problem page.
  • Reading a slice as minimal. Every path counts, including paths that no input takes, so the slice can be larger than needed. The smallest slice is not computable.

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.

pdg_slicing.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pdg-slicing/. The authors are listed in prov/8QKCJ8.jsonl.
"""Slicing by backward reachability in the program dependence graph.

A statement is a pair (label, i): instruction i of block label, or the
terminator of the block when i == len(instrs). A slicing criterion is
(label, i, V): the values of the names in V at the point just before
statement (label, i).

build_pdg(prog) returns the control and data parents of every statement.
The node ENTRY stands for the start of the program and for the definitions
of the parameters. pdg_slice(prog, crit) returns the set of statements that
reach the criterion in the graph. executable_slice turns that set into a
runnable toy IR program, and observe runs a program and records the values
of some names each time control reaches a point.

The programs use only x = k, x = y and x = a op b, with the terminators jump,
br and ret, and every block must reach a ret.
"""

import toyir

ENTRY = "<entry>"
EXIT = "<exit>"


# ------------------------------------------------------------ statements


def statements(prog):
    return [(lab, i) for lab, b in prog.blocks.items() for i in range(len(b.instrs) + 1)]


def stmt_succs(prog, node):
    lab, i = node
    b = prog.blocks[lab]
    if i < len(b.instrs):
        return [(lab, i + 1)]
    return [(s, 0) for s in toyir.succs(prog, lab)]


def DEF(prog, node):
    lab, i = node
    b = prog.blocks[lab]
    if i == len(b.instrs):
        return set()
    ins = b.instrs[i]
    if ins[0] not in ("const", "copy", "op"):
        raise ValueError("unsupported instruction: %r" % (ins,))
    return {ins[1]}


def REF(prog, node):
    lab, i = node
    b = prog.blocks[lab]
    if i == len(b.instrs):
        return set(toyir.term_uses(b.term))
    return set(toyir.uses(b.instrs[i]))


def terminator(prog, lab):
    return (lab, len(prog.blocks[lab].instrs))


# ------------------------------------------------------- post-dominators


def postdominators(prog):
    """Post-dominator sets of the blocks, with a virtual EXIT after every
    ret, by the iterative set method."""
    labels = list(prog.blocks)
    succ = {lab: (toyir.succs(prog, lab) or [EXIT]) for lab in labels}
    reach = {EXIT}
    changed = True
    while changed:
        changed = False
        for lab in labels:
            if lab not in reach and any(s in reach for s in succ[lab]):
                reach.add(lab)
                changed = True
    if len(reach) != len(labels) + 1:
        raise ValueError("every block must reach a ret")
    full = set(labels) | {EXIT}
    pdom = {lab: set(full) for lab in labels}
    pdom[EXIT] = {EXIT}
    changed = True
    while changed:
        changed = False
        for lab in reversed(labels):
            new = {lab} | set.intersection(*(pdom[s] for s in succ[lab]))
            if new != pdom[lab]:
                pdom[lab] = new
                changed = True
    return pdom


def ipdom(prog):
    """Immediate post-dominator of each block (EXIT for a ret block)."""
    pdom = postdominators(prog)
    return {lab: max(pdom[lab] - {lab}, key=lambda x: len(pdom[x])) for lab in prog.blocks}


# -------------------------------------------------------------- the PDG


def block_control_deps(prog, ip=None):
    """For each block, the blocks whose branch it is control dependent on,
    plus ENTRY for the blocks that run on every run. This is the walk of
    Ferrante, Ottenstein and Warren up the post-dominator tree."""
    if ip is None:
        ip = ipdom(prog)
    cd = {lab: set() for lab in prog.blocks}
    for a in prog.blocks:
        if prog.blocks[a].term[0] != "br":
            continue
        for b in toyir.succs(prog, a):
            y = b
            while y != ip[a]:
                cd[y].add(a)
                y = ip[y]
    # The edges START -> entry and START -> EXIT: ipdom(START) is EXIT.
    y = prog.entry
    while y != EXIT:
        cd[y].add(ENTRY)
        y = ip[y]
    return cd


def reaching_definitions(prog):
    """IN set of every statement: pairs (d, x) where d is a statement that
    defines x, or ENTRY for a parameter x, and some path from just after d
    reaches the statement with no other definition of x."""
    nodes = statements(prog)
    IN = {n: set() for n in nodes}
    first = (prog.entry, 0)
    IN[first] = {(ENTRY, x) for x in prog.params}
    work = list(nodes)
    while work:
        n = work.pop()
        d = DEF(prog, n)
        out = {(s, x) for (s, x) in IN[n] if x not in d} | {(n, x) for x in d}
        for m in stmt_succs(prog, n):
            if not out <= IN[m]:
                IN[m] |= out
                work.append(m)
    return IN


def build_pdg(prog):
    """Control parents and data parents of every statement."""
    ip = ipdom(prog)
    cd = block_control_deps(prog, ip)
    rd = reaching_definitions(prog)
    control, data = {}, {}
    for n in statements(prog):
        control[n] = {a if a == ENTRY else terminator(prog, a) for a in cd[n[0]]}
        data[n] = {(s, x) for (s, x) in rd[n] if x in REF(prog, n)}
    return {"control": control, "data": data, "rd": rd, "ipdom": ip}


def parents(pdg, n):
    return pdg["control"][n] | {s for (s, _) in pdg["data"][n]}


# -------------------------------------------------------------- slicing


def pdg_slice(prog, crit, pdg=None):
    """The statements that reach the criterion in the PDG. The criterion
    acts as a node at the point p that reads the names of V."""
    if pdg is None:
        pdg = build_pdg(prog)  # @line L1
    lab, i, V = crit
    p = (lab, i)
    start = {s for (s, x) in pdg["rd"][p] if x in V}  # @line L2
    start |= pdg["control"][p]  # @line L3
    start.discard(ENTRY)
    S = set(start)  # @line L4
    work = list(start)
    while work:  # @line L5
        z = work.pop()  # @line L6
        for x in parents(pdg, z):  # @line L7
            if x != ENTRY and x not in S:  # @line L8
                S.add(x)
                work.append(x)
    return S  # @line L9


def executable_slice(prog, crit, S, ip=None):
    """The projection of the program on S: instructions outside S are
    deleted, a branch outside S becomes a jump to its immediate
    post-dominator (or ret 0 when that is EXIT), jumps stay, and a ret keeps
    its operand only at the criterion point for a name of V."""
    if ip is None:
        ip = ipdom(prog)
    plab, pi, V = crit
    blocks = {}
    for lab, b in prog.blocks.items():
        n = len(b.instrs)
        instrs = [ins for i, ins in enumerate(b.instrs) if (lab, i) in S]
        t = b.term
        if t[0] == "br" and (lab, n) not in S:
            t = ("ret", 0) if ip[lab] == EXIT else ("jump", ip[lab])
        elif t[0] == "ret" and isinstance(t[1], str) and not ((lab, n) == (plab, pi) and t[1] in V):
            t = ("ret", 0)
        blocks[lab] = toyir.Block(instrs, t)
    return toyir.Program(list(prog.params), blocks)


def slice_point(prog, crit, S):
    """The criterion point in the executable slice."""
    lab, i, _ = crit
    return (lab, sum(1 for j in range(i) if (lab, j) in S))


# --------------------------------------------------------------- running


class _Trap(Exception):
    pass


def _binop(op, a, b):
    if op in ("/", "%"):
        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 in ("<<", ">>"):
        if b < 0 or b > 63:
            raise _Trap()
        return a << b if op == "<<" else a >> b
    return {
        "+": lambda: a + b, "-": lambda: a - b, "*": lambda: a * b,
        "&": lambda: a & b, "|": lambda: a | b, "^": lambda: a ^ b,
        "<": lambda: int(a < b), "<=": lambda: int(a <= b),
        "==": lambda: int(a == b), "!=": lambda: int(a != b),
    }[op]()


def observe(prog, args, point, names, fuel=10000):
    """Run prog like toyir.run. Return (outcome, obs), where obs has one
    tuple of the values of names (None if undefined) for each time control
    is about to run the statement at point."""
    env = dict(zip(prog.params, args))
    plab, pi = point
    obs = []

    def val(a):
        if isinstance(a, int):
            return a
        if a not in env:
            raise toyir.UndefinedName(a)
        return env[a]

    lab = prog.entry
    while True:
        b = prog.blocks[lab]
        n = len(b.instrs)
        for i in range(n + 1):
            if lab == plab and i == pi:
                obs.append(tuple(env.get(v) for v in names))
            if fuel <= 0:
                return ("fuel",), obs
            fuel -= 1
            if i == n:
                break
            ins = b.instrs[i]
            if ins[0] == "const":
                env[ins[1]] = ins[2]
            elif ins[0] == "copy":
                env[ins[1]] = val(ins[2])
            else:
                try:
                    env[ins[1]] = _binop(ins[2], val(ins[3]), val(ins[4]))
                except _Trap:
                    return ("trap",), obs
        t = b.term
        if t[0] == "jump":
            lab = t[1]
        elif t[0] == "br":
            lab = t[2] if val(t[1]) != 0 else t[3]
        else:
            return ("ret", val(t[1])), obs
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_pdg_slicing.py 349 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pdg-slicing/. The authors are listed in prov/8QKCJ8.jsonl.

import random

import toyir
from pdg_slicing import (
    DEF,
    ENTRY,
    REF,
    EXIT,
    build_pdg,
    executable_slice,
    ipdom,
    observe,
    pdg_slice,
    slice_point,
    statements,
    stmt_succs,
    terminator,
)

# The sum and product program of the page.
PAGE = """
B1:
  i = 1
  s = 0
  p = 1
  jump B2
B2:
  t = i <= n
  br t B3 B6
B3:
  p = p * i
  u = i % 2
  br u B4 B5
B4:
  s = s + i
  jump B5
B5:
  i = i + 1
  jump B2
B6:
  ret s
"""

# A loop with a "continue": B4 is the jump back to the loop test.
CONTINUE = """
B1:
  i = 0
  c = 0
  jump B2
B2:
  t = i < n
  br t B3 B6
B3:
  i = i + 1
  r = i % 3
  br r B5 B4
B4:
  jump B2
B5:
  c = c + 1
  jump B2
B6:
  ret c
"""


def test_page_example():
    prog = toyir.parse(PAGE)
    pdg = build_pdg(prog)
    assert pdg["control"][("B3", 0)] == {("B2", 1)}
    assert pdg["control"][("B2", 0)] == {ENTRY, ("B2", 1)}
    assert pdg["control"][("B4", 0)] == {("B3", 2)}
    assert pdg["data"][("B3", 0)] == {(("B1", 0), "i"), (("B5", 0), "i"), (("B1", 2), "p"), (("B3", 0), "p")}
    assert pdg["data"][("B2", 0)] == {(("B1", 0), "i"), (("B5", 0), "i"), (ENTRY, "n")}
    S = pdg_slice(prog, ("B6", 0, {"p"}), pdg)
    assert S == {("B1", 0), ("B1", 2), ("B2", 0), ("B2", 1), ("B3", 0), ("B5", 0)}
    S2 = pdg_slice(prog, ("B6", 0, {"s"}), pdg)
    assert len(S2) == 8 and ("B1", 2) not in S2 and ("B3", 0) not in S2
    # The slice of a statement used as the criterion node itself.
    S3 = pdg_slice(prog, ("B5", 0, {"i"}), pdg)
    assert S3 == {("B1", 0), ("B2", 0), ("B2", 1), ("B5", 0)}
    sl = executable_slice(prog, ("B6", 0, {"p"}), S)
    point = slice_point(prog, ("B6", 0, {"p"}), S)
    for n in range(-2, 9):
        assert observe(prog, [n], ("B6", 0), ["p"])[1] == observe(sl, [n], point, ["p"])[1]


def _postdominates(prog, y, x):
    if x == y:
        return True
    seen = {x}
    stack = [x]
    while stack:
        a = stack.pop()
        s = toyir.succs(prog, a)
        if not s:
            return False
        for b in s:
            if b != y and b not in seen:
                seen.add(b)
                stack.append(b)
    return True


def _control_deps(prog):
    labels = list(prog.blocks)
    return {
        x: {
            y
            for y in labels
            for s in toyir.succs(prog, x)
            if _postdominates(prog, y, s) and not (y != x and _postdominates(prog, y, x))
        }
        for x in labels
    }


def _def_clear_reach(prog, start, x, target):
    seen = set()
    stack = [start]
    while stack:
        n = stack.pop()
        if n == target:
            return True
        if n in seen or x in DEF(prog, n):
            continue
        seen.add(n)
        stack.extend(stmt_succs(prog, n))
    return False


def _brute_parents(prog):
    """Data and control parents straight from the definitions."""
    nodes = statements(prog)
    cd = _control_deps(prog)
    first = (prog.entry, 0)
    out = {}
    for n in nodes:
        ps = set()
        for s in nodes:
            for x in DEF(prog, s) & REF(prog, n):
                if any(_def_clear_reach(prog, m, x, n) for m in stmt_succs(prog, s)):
                    ps.add(s)
        for x in prog.blocks:
            if n[0] in cd[x]:
                ps.add(terminator(prog, x))
        out[n] = ps
        # Parameters: defined at ENTRY, before the first statement.
        params = {x for x in REF(prog, n) & set(prog.params) if _def_clear_reach(prog, first, x, n)}
        out[n, "params"] = params
    return out


def _brute_slice(prog, crit, par):
    lab, i, V = crit
    p = (lab, i)
    nodes = statements(prog)
    cd = _control_deps(prog)
    K = set()
    for s in nodes:
        for x in DEF(prog, s) & V:
            if any(_def_clear_reach(prog, m, x, p) for m in stmt_succs(prog, s)):
                K.add(s)
    for x in prog.blocks:
        if lab in cd[x]:
            K.add(terminator(prog, x))
    stack = list(K)
    while stack:
        n = stack.pop()
        for s in par[n]:
            if s not in K:
                K.add(s)
                stack.append(s)
    return K


def _random_criterion(rng, prog):
    nodes = statements(prog)
    lab, i = rng.choice(nodes)
    names = sorted({v for n in nodes for v in DEF(prog, n)} | set(prog.params))
    return (lab, i, set(rng.sample(names, rng.randint(1, min(2, len(names))))))


def test_pdg_edges_match_definitions():
    rng = random.Random(3)
    for trial in range(150):
        prog = toyir.random_program(rng, rng.randint(2, 4), rng.randint(1, 7), trial % 2 == 0)
        pdg = build_pdg(prog)
        par = _brute_parents(prog)
        cd = _control_deps(prog)
        ip = ipdom(prog)
        always = set()
        y = prog.entry
        while y != EXIT:
            always.add(y)
            y = ip[y]
        for n in statements(prog):
            data = {s for (s, _) in pdg["data"][n] if s != ENTRY}
            ctrl = pdg["control"][n] - {ENTRY}
            assert data | ctrl == par[n]
            assert ctrl == {terminator(prog, x) for x in prog.blocks if n[0] in cd[x]}
            assert {x for (s, x) in pdg["data"][n] if s == ENTRY} == par[n, "params"]
            # ENTRY controls exactly the blocks that every run passes.
            assert (ENTRY in pdg["control"][n]) == (n[0] in always)


def test_slice_equals_bruteforce_reachability():
    rng = random.Random(5)
    for trial in range(250):
        prog = toyir.random_program(rng, rng.randint(2, 4), rng.randint(1, 7), trial % 2 == 0)
        par = _brute_parents(prog)
        for _ in range(3):
            crit = _random_criterion(rng, prog)
            assert pdg_slice(prog, crit) == _brute_slice(prog, crit, par)


def _dynamic_closure(prog, args, crit, ip, fuel=2000):
    """Statements that the criterion depends on in the run on args, by data
    dependence (the last write of each name read) and dynamic control
    dependence (the latest branch instance whose immediate post-dominator
    has not been entered since)."""
    plab, pi, V = crit
    env = dict(zip(prog.params, args))
    stmt_of = []  # instance -> statement
    deps = []  # instance -> parent instances
    last = {}
    open_br = []  # [instance, ipdom block, open]
    roots = set()
    lab = prog.entry
    ctrl = None
    while fuel > 0:
        b = prog.blocks[lab]
        n = len(b.instrs)
        for i in range(n + 1):
            fuel -= 1
            if (lab, i) == (plab, pi):
                roots |= {last[x] for x in V if x in last}
                if ctrl is not None:
                    roots.add(ctrl)
            node = (lab, i)
            par = {last[x] for x in REF(prog, node) if x in last}
            if ctrl is not None:
                par.add(ctrl)
            k = len(stmt_of)
            stmt_of.append(node)
            deps.append(par)
            if i < n:
                ins = b.instrs[i]
                vals = {x: env[x] for x in REF(prog, node)}
                if ins[0] == "const":
                    v = ins[2]
                elif ins[0] == "copy":
                    v = vals[ins[2]]
                else:
                    a = ins[3] if isinstance(ins[3], int) else vals[ins[3]]
                    c = ins[4] if isinstance(ins[4], int) else vals[ins[4]]
                    if ins[2] in ("/", "%") and c == 0 or ins[2] in ("<<", ">>") and not 0 <= c <= 63:
                        fuel = 0
                        break
                    v = toyir._binop(ins[2], a, c)
                env[ins[1]] = v
                last[ins[1]] = k
                continue
            t = b.term
            if t[0] == "ret":
                fuel = 0
                break
            if t[0] == "br":
                c = t[1] if isinstance(t[1], int) else env[t[1]]
                nxt = t[2] if c != 0 else t[3]
                open_br.append([k, ip[lab], True])
            else:
                nxt = t[1]
            for e in open_br:
                if e[1] == nxt:
                    e[2] = False
            live = [e[0] for e in open_br if e[2]]
            ctrl = live[-1] if live else None
            lab = nxt
    seen = set(roots)
    stack = list(roots)
    while stack:
        k = stack.pop()
        for q in deps[k]:
            if q not in seen:
                seen.add(q)
                stack.append(q)
    return {stmt_of[k] for k in seen}


def test_slice_contains_dynamic_dependences():
    rng = random.Random(17)
    smaller = 0
    for trial in range(300):
        prog = toyir.random_program(rng, rng.randint(2, 5), rng.randint(2, 8), trial % 2 == 0)
        ip = ipdom(prog)
        crit = _random_criterion(rng, prog)
        S = pdg_slice(prog, crit)
        for _ in range(4):
            args = [rng.randint(-5, 9), rng.randint(-5, 9)]
            dyn = _dynamic_closure(prog, args, crit, ip)
            assert dyn <= S
            smaller += dyn < S
    assert smaller > 0


def test_projection_keeps_criterion_values():
    rng = random.Random(2024)
    runs = 0
    for trial in range(300):
        prog = toyir.random_program(rng, rng.randint(2, 5), rng.randint(1, 8), trial % 2 == 0)
        crit = _random_criterion(rng, prog)
        S = pdg_slice(prog, crit)
        sl = executable_slice(prog, crit, S)
        point = slice_point(prog, crit, S)
        names = sorted(crit[2])
        for _ in range(8):
            args = [rng.randint(-5, 9), rng.randint(-5, 9)]
            o1, ob1 = observe(prog, args, crit[:2], names)
            assert o1 == toyir.run(prog, args)
            o2, ob2 = observe(sl, args, point, names)
            if o1[0] == "ret":
                assert o2[0] == "ret" and ob2 == ob1
            else:
                assert ob2[: len(ob1)] == ob1
            runs += 1
    assert runs == 2400


def test_jumps_are_not_in_the_slice():
    prog = toyir.parse(CONTINUE)
    crit = ("B6", 0, {"c"})
    S = pdg_slice(prog, crit)
    # Every statement but the jumps and the ret is in the slice.
    assert S == {n for n in statements(prog) if n not in {("B1", 2), ("B4", 0), ("B5", 1), ("B6", 0)}}
    sl = executable_slice(prog, crit, S)
    point = slice_point(prog, crit, S)
    # Deleting the "continue" as in source text: B4 falls into B5.
    broken = toyir.parse(CONTINUE)
    broken.blocks["B4"].term = ("jump", "B5")
    for n in range(0, 10):
        want = observe(prog, [n], ("B6", 0), ["c"])[1]
        assert observe(sl, [n], point, ["c"])[1] == want
        assert want == [(sum(1 for i in range(1, n + 1) if i % 3),)]
    assert observe(broken, [6], ("B6", 0), ["c"])[1] == [(6,)]
    assert observe(prog, [6], ("B6", 0), ["c"])[1] == [(4,)]

History

Karl and Linda Ottenstein proposed in 1984 that a software development environment keep programs as program dependence graphs, so that slices for debugging become linear-time searches. Ferrante, Ottenstein and Warren gave the general definition of the graph, with control dependence from post-dominators, in 1987. Reps and Yang (1989) proved that a dependence graph slice computes the same values as the program on every run that halts, and Horwitz, Reps and Binkley (1990) extended the method across procedures. Tip's survey of 1995 compares the graph method with Weiser's dataflow method.

References

  1. Karl J. Ottenstein and Linda M. Ottenstein, The program dependence graph in a software development environment, ACM SIGPLAN Notices 19(5) (Proceedings of the ACM SIGSOFT/SIGPLAN Software Engineering Symposium on Practical Software Development Environments), 1984, pages 177-184, the dependence graph as the internal form of the environment, and slices found by a linear-time walk over its edges
  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, pages 319-349, control dependence from the post-dominator tree, the definition of the graph used here
  3. Thomas Reps and Wuu Yang, The semantics of program slicing and program integration, TAPSOFT '89, Lecture Notes in Computer Science 352, Springer, 1989, pages 360-374, the Slicing Theorem (on every initial state on which the program halts, the slice computes the same sequence of values at each of its points) and the Termination Theorem
  4. Susan Horwitz, Thomas Reps and David Binkley, Interprocedural slicing using dependence graphs, ACM Transactions on Programming Languages and Systems 12(1), 1990, pages 26-60, slicing within one procedure as reachability in the dependence graph, the base case of the interprocedural method
  5. Frank Tip, A survey of program slicing techniques, Journal of Programming Languages 3(3), 1995, pages 121-189, the section on static slicing with dependence graphs, and the comparison with the dataflow method of Weiser

Where this leads

About this page

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

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