Algorithm Search⌘K

Algorithmadvanced

System dependence graph slicing

Also called Horwitz-Reps-Binkley slicing, interprocedural slicing.

Slices across procedures with a system dependence graph and summary edges, in two passes that respect calling context.

Time
O(N + E) worst
Space
O(N + E) extra
Where
E = the number of its edges including summary edges; N = the number of nodes of the system dependence graph
Properties
context sensitivedeterministicnot executable resultofflineiterative
Origin
Susan Horwitz, Thomas Reps, David Binkley, 1988

System dependence graph slicing solves the program slicing problem for programs with procedures. Horwitz, Reps and Binkley (1988) joined the program dependence graphs of all procedures into one system dependence graph (SDG), with edges for calls, for passing arguments in and for passing results out. A plain backward search in this graph is wrong in a useful way: it enters a procedure from one call site and leaves it through another, so it mixes calling contexts and gives slices that are too large. The fix has two parts. Summary edges at each call site record which arguments the result depends on. Then the slice is two searches: the first never descends into a callee and the second never climbs to a caller. The result is exactly the set of nodes that reach the criterion along paths whose calls and returns match.

In plain words

Each procedure has its own map of which line feeds which line. Join the maps: draw arrows from each call to the procedure it calls, from each argument to the parameter it fills, and from the returned value back to the call. Now walk the arrows backward from the line you care about. The danger is that you go into a procedure through one call and come out through another call, which no run can do. So first find, for every call, which arguments the result needs, and draw a short arrow for that. Then walk in two rounds. In the first round, climb out to callers and use the short arrows, but never go down into a procedure. In the second round, go down into procedures, but never climb out. Nothing you reach comes from a mixed-up path.

The problem

A system is a set of procedures in the toy IR, one of them main. A procedure has parameters, uses x = k, x = y, x = a op b and x = call f(a, b, ...), and ends each path with a ret. Arguments are passed by value and the only result of a call is the value its callee returns. A criterion is ⟨P,p,V⟩\langle P, p, V \rangle: the values of the variables of VV just before statement pp of procedure PP, in every activation of PP. The output is the set of statements of all procedures that can affect those values through data and control dependence along paths that a run could follow, that is, paths in which each return goes back to the call site that made the call.

The SDG has, for each procedure QQ, the nodes of its program dependence graph and:

  • an entry node, the ENTRY of the PDG of QQ;
  • one formal-in node per parameter, control dependent on entry, which defines that parameter;
  • one formal-out node for the returned value, with a data edge from each ret statement.

Each call statement is a call node with one actual-in node per argument and one actual-out node for the result. These are control dependent on the call node. An actual-in reads its argument, so it has data edges from the definitions that reach the call. The actual-out defines the target of the call, so the later uses have data edges from it. Between procedures:

  • a call edge from the call node to the entry of the callee;
  • a parameter-in edge from actual-in kk to formal-in kk of the callee;
  • a parameter-out edge from the formal-out of the callee to the actual-out.

A summary edge goes from actual-in kk to the actual-out of the same call site when, inside the callee, a path with matched calls and returns goes from formal-in kk to the formal-out.

The algorithm

Mark each call or parameter-in edge at site cc as an open parenthesis (c(_c and each parameter-out edge at cc as a close )c)_c. A path is realizable if no close meets an open of another site and no unmatched close comes after an unmatched open. It is same-level if all of its parentheses match. SUMMARY-EDGES is the method of Reps, Horwitz, Sagiv and Rosay (1994). A path edge (v,w)(v, w) records that a same-level path goes from vv to the formal-out ww of the procedure of vv.

  1. SDG-SLICE(G, C)
  2. 1W <- the parents of the criterion C; S <- W
  3. 2while W is not empty do (pass 1: climb to callers)
  4. 3remove a node n from W
  5. 4for each edge m -> n of G that is not a parameter-out edge do
  6. 5if m is not in S then add m to S and to W
  7. 6W <- S (pass 2: go down into callees)
  8. 7while W is not empty do
  9. 8remove a node n from W
  10. 9for each edge m -> n of G that is not a parameter-in edge or a call edge do
  11. 10if m is not in S then add m to S and to W
  12. 11return S
  13. SUMMARY-EDGES(G)
  14. 12for each formal-out node w do PROPAGATE(w, w)
  15. 13while the work list is not empty do
  16. 14remove a path edge (v, w) from the work list
  17. 15if v is the formal-in node for parameter k of procedure Q then
  18. 16for each call site c of Q, with actual-in a for parameter k and actual-out o do
  19. 17if a -> o is not a summary edge then add it, and PROPAGATE(a, x) for each path edge (o, x)
  20. 18else for each intraprocedural edge or summary edge x -> v do PROPAGATE(x, w)
  21. 19return the summary edges
  22. PROPAGATE(v, w): if (v, w) is not a path edge then make it one and put it in the work list

The parents of the criterion in line L1 are the definitions of VV that reach pp, with the actual-out node standing for a call that defines a variable and a formal-in node for a parameter, and the control parents of pp. Lines L2 to L5 can climb from a callee to every caller, because the criterion holds in every calling context. They cross calls only by summary edges. Lines L7 to L10 go down from each actual-out to the formal-out of the callee and on into it, and they cross deeper calls again only by summary edges, never climbing back out.

In the implementation, build_sdg builds the graph with the per-procedure parts of the PDG slicing page, summary_edges is lines L12 to L19, sdg_slice is lines L1 to L11, and reachability_slice is the naive search, kept for comparison.

Example

The procedure add(a, b) returns a+ba + b. main(n) uses it twice per loop trip: once to add ii to the sum ss and once to step ii.

main(n):                         add(a, b):
B1:                              B1:
  s = 0                            r = a + b
  i = 0                            ret r
  jump B2
B2:
  t = i < n
  br t B3 B4
B3:
  s = call add(s, i)
  i = call add(i, 1)
  jump B2
B4:
  ret i

Summary edges. In add, both formal-ins reach the formal-out through r = a + b and ret r. So each of the two call sites gets two summary edges, from the actual-in of each argument to its actual-out.

The slice for ⟨main,(B4,0),{i}⟩\langle main, (B4, 0), \{i\} \rangle. The definitions of ii that reach B4 are i = 0 and the actual-out of the second call; B4 runs on every run, so its control parent is the entry of main.

pass node reached through
1 actual-in i and actual-in 1 of i = call add(i, 1) summary edges into its actual-out
1 call node i = call add(i, 1) control edge to its actual-in and actual-out
1 br t B3 B4, t = i < n, formal-in n control and data edges
2 formal-out of add, ret r, r = a + b, formal-ins a and b parameter-out edge of the second call, then data edges

Pass 2 stops at the formal-ins of add: it does not climb along the parameter-in edges. So the slice is i = 0, t = i < n, br t B3 B4 and i = call add(i, 1) in main, and r = a + b and ret r in add. The statements of ss are not in it.

A plain backward search over all edges reaches formal-in a of add and then follows both parameter-in edges into it. The one from the first call leads to actual-in s, then to s = 0 and to s = call add(s, i). That path enters add from the second call and leaves it through the first, which no run does. The naive slice has 8 statements, the SDG slice 6.

Correctness

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

  1. Path edges are sound. Each pair that SUMMARY-EDGES adds has a same-level path behind it, by induction on the order of addition.
  2. Path edges are complete. By induction on the length of a same-level path from vv to the formal-out: the first edge is either intraprocedural, or a parameter-in or call edge whose matching return is at the same site. In the second case the callee part gives a summary edge, and the work list adds the pair whichever of the two facts comes first.
  3. Summary edges are exact. A summary edge exists if and only if a same-level path joins the formal-in to the formal-out of the callee.
  4. Two passes are exact. Pass 1 reaches the nodes with a path made of opens, summary edges and intraprocedural edges; pass 2 adds the nodes with a path of closes and summary edges to one of them. Replacing summary edges by same-level paths shows each such node has a realizable path. Conversely, cut a realizable path after its last unmatched close and replace each matched pair by a summary edge (or by the control edge from the call node to the actual-out): the tail becomes a pass-1 path and the head a pass-2 path.

So the slice is the set of nodes with a realizable path to the criterion. That is not the same as minimal: a realizable path may still be one that no input follows.

Proof: Summary edges are exact, and the two passes find exactly the nodes on realizable paths to the criterionfull

Setting. The system and its graph are as on the page. Edges go from a parent to a child. The edge kinds are: intraprocedural (control and data edges inside one procedure, including entry to formal-in, entry to formal-out, call node to actual-in and actual-out, and ret statement to formal-out); call edges from a call node at site cc to the entry of the callee; parameter-in edges from actual-in kk at cc to formal-in kk of the callee; parameter-out edges from the formal-out of the callee to the actual-out at cc; and summary edges. Each procedure has exactly one formal-out node, for its return value. The criterion is a virtual node γ\gamma in procedure PP, with an intraprocedural edge from each start node of line L1.

Words of paths. Give each call or parameter-in edge at site cc the symbol (c(_c, each parameter-out edge at cc the symbol )c)_c, and every other edge no symbol. The word of a path is the sequence of its symbols. Match brackets with a stack, from left to right: a close )c)_c is matched if the top of the stack is (c(_c, which it pops; otherwise it is unmatched (if the stack is empty) or mismatched. Opens left on the stack at the end are unmatched. A path without summary edges is realizable if no close is mismatched and no unmatched close comes after an unmatched open. It is same-level if every bracket is matched. The text between a matched pair is balanced, so a path segment from a matched open to its close is same-level inside, and an unmatched close never lies strictly between the two edges of a matched pair.

The slice over realizable paths is the set of nodes nn with a realizable path from nn to γ\gamma. In the paths below, an edge into an entry node is always a call edge and an edge into a formal-in node from outside the procedure is always a parameter-in edge; the only intraprocedural parent of a formal-in or formal-out is the entry node of its procedure, plus the ret statements for the formal-out.

1. Path edges

SUMMARY-EDGES keeps a set PEPE of path edges (v,w)(v, w). Every ww it handles is a formal-out node.

Lemma 1 (soundness). If (v,w)∈PE(v, w) \in PE, then vv and ww are in the same procedure, ww is its formal-out, and there is a same-level path from vv to ww. If (a,o)(a, o) is a summary edge at site cc for argument kk, there is a same-level path from aa to oo through formal-in kk and the formal-out of the callee.

Proof. By induction on the order in which pairs and summary edges are added. Line L12 adds (w,w)(w, w), the empty path. Line L18 adds (x,w)(x, w) when (v,w)∈PE(v, w) \in PE and x→vx \to v is intraprocedural (no symbol, same procedure) or a summary edge already added (same-level by induction); prefix the edge or path to the path from vv. Line L17 adds the summary edge (a,o)(a, o) when (fk,wQ)∈PE(f_k, w_Q) \in PE for formal-in fkf_k of the callee QQ; the path a→fk⇝wQ→oa \to f_k \leadsto w_Q \to o has the word (c u )c(_c \, u \, )_c with uu balanced, so it is same-level. Line L17 then adds (a,x)(a, x) for (o,x)∈PE(o, x) \in PE; prefix that path with a⇝oa \leadsto o. □\square

Lemma 2 (completeness). Let vv be a node that is not an entry node, in procedure QQ with formal-out ww. If a same-level path without summary edges runs from vv to ww, then (v,w)(v, w) is added to PEPE.

Proof. By induction on the length of the path π\pi. If it is 00, v=wv = w and line L12 adds it. Otherwise let v→v′v \to v' be the first edge. It is not a close, since a close at the start is unmatched.

Case 1: v→v′v \to v' is intraprocedural. Then v′v' is not an entry node (entries have only call parents) and not a formal-in (its only intraprocedural parent is the entry, and vv is not one). The rest of π\pi is shorter and same-level, so (v′,w)∈PE(v', w) \in PE by induction. When it is taken from the work list, line L18 reads the edge v→v′v \to v' and adds (v,w)(v, w).

Case 2: v→v′v \to v' is a parameter-in edge at site cc, so v=akv = a_k is actual-in kk at cc and v′=fkv' = f_k is formal-in kk of the callee RR. Its match is a close )c)_c, a parameter-out edge wR→ocw_R \to o_c into the actual-out at cc. The part from fkf_k to wRw_R is same-level and shorter, so (fk,wR)∈PE(f_k, w_R) \in PE, and when it is taken from the work list, lines L15 to L17 add the summary edge (ak,oc)(a_k, o_c). The part from oco_c to ww is same-level and shorter, so (oc,w)∈PE(o_c, w) \in PE. If (oc,w)(o_c, w) is in PEPE when the summary edge is added, line L17 adds (ak,w)(a_k, w). If not, (oc,w)(o_c, w) is added later and taken from the work list later still; line L18 then reads the summary edge into oco_c and adds (ak,w)(a_k, w).

Case 3: v→v′v \to v' is a call edge at site cc, so vv is the call node. As in case 2 the match is the edge into the actual-out oco_c, and (oc,w)∈PE(o_c, w) \in PE by induction. The edge v→ocv \to o_c is an intraprocedural control edge, so line L18 adds (v,w)(v, w) when (oc,w)(o_c, w) is taken from the work list. □\square

Theorem 1 (summary edges). SUMMARY-EDGES adds the summary edge (ak,oc)(a_k, o_c) at site cc if and only if a same-level path runs from formal-in kk of the callee of cc to its formal-out.

Proof. Only line L17 adds summary edges, and it does so when (fk,wR)∈PE(f_k, w_R) \in PE, which by Lemma 1 gives the path. Conversely, such a path gives (fk,wR)∈PE(f_k, w_R) \in PE by Lemma 2, and when the pair is taken from the work list, line L16 visits every call site of RR, including cc. □\square

Termination and cost. Every pair in PEPE has as second node the formal-out of the procedure of its first node, so ∣PE∣≤N|PE| \le N, the number of nodes. Each pair enters the work list once. Taking (v,w)(v, w) costs the number of parents of vv, or, for a formal-in, the number of call sites of its procedure times the number of pairs (o,x)(o, x) in PEPE with first node oo, which is at most one. Each summary edge is added once. The total is O(N+E)O(N + E), where EE counts all edges including summary edges. With several formal-outs per procedure (global variables, reference parameters), the same count gives O(g(N+E))O(g (N + E)) for at most gg formal-outs per procedure.

2. The two passes

Let S1S_1 be the set after the first loop (lines L1 to L5) and SS the set returned (line L11). The first loop starts from the parents of γ\gamma and follows every edge but parameter-out edges, backward; the second starts from S1S_1 and follows every edge but call and parameter-in edges. Both loops add each node at most once and read each of its parent edges once, so they stop after O(N+E)O(N + E) steps.

Lemma 3. n∈S1n \in S_1 if and only if a path from nn to γ\gamma uses only intraprocedural, summary, call and parameter-in edges. n∈Sn \in S if and only if a path from nn to some node of S1S_1 uses only intraprocedural, summary and parameter-out edges.

Proof. This is backward reachability under the stated edge kinds, as in the PDG slice. □\square

Lemma 4. Replace each summary edge of a path by the same-level path that Theorem 1 gives for it. The result has the same first and last nodes, and its word is the old word with balanced words put in.

Theorem 2. SS is exactly the set of nodes nn with a realizable path from nn to γ\gamma.

Proof. (⊆\subseteq) Let n∈S1n \in S_1. Lemma 3 gives a path to γ\gamma with intraprocedural, summary, call and parameter-in edges; after Lemma 4 its word has opens and balanced inserts only, so no close is mismatched and no close is unmatched. It is realizable. Let n∈S∖S1n \in S \setminus S_1. Lemma 3 gives a path to some m∈S1m \in S_1 with intraprocedural, summary and parameter-out edges; after Lemma 4 its word has closes and balanced inserts only, so its opens are all matched. Join it to the path from mm to γ\gamma. Every bracket of the second part that was matched or unmatched in that part stays so, since the first part leaves the stack empty; the closes of the first part are matched or unmatched and come before every unmatched open. The joined path is realizable.

(⊇\supseteq) Let π\pi be a realizable path from nn to γ\gamma without summary edges. If π\pi has an unmatched close, let ee be the last one, π1\pi_1 the part up to and including ee, and π2\pi_2 the rest; otherwise π1\pi_1 is empty and π2=π\pi_2 = \pi. No matched pair has its open in π1\pi_1 and its close in π2\pi_2, since ee cannot lie inside a matched pair. So in π2\pi_2 the unmatched brackets are opens, and in π1\pi_1 they are closes.

Rewrite each maximal matched pair in π2\pi_2. The open is at some site cc, and the matching close is the parameter-out edge wR→ocw_R \to o_c of the same site. If the open is a parameter-in edge ak→fka_k \to f_k, the part from fkf_k to wRw_R is same-level, so Theorem 1 gives the summary edge ak→oca_k \to o_c; put it in place of the pair and what lies between. If the open is a call edge from the call node cc, put the control edge c→occ \to o_c in its place. The first node of π2\pi_2 is the first node of the new path, because no pair of π2\pi_2 starts before it. The new path uses only intraprocedural, summary, call and parameter-in edges, so by Lemma 3 its first node mm is in S1S_1. Rewrite π1\pi_1 the same way: the new path from nn to mm uses only intraprocedural, summary and parameter-out edges, so n∈Sn \in S by Lemma 3. If π1\pi_1 is empty, n=m∈S1⊆Sn = m \in S_1 \subseteq S. □\square

Remark (what the tests check). For a system without recursion, clone each procedure once per calling context, the string of call sites from main. A call or parameter-in edge goes from a callee copy to the caller copy one site shorter, and a parameter-out edge goes from the caller copy into the copy one site longer. Every realizable path of the SDG that ends at γ\gamma lifts to a path of this graph that ends at a copy of γ\gamma: walk it backward, push the site at each parameter-out edge, and pop at each call or parameter-in edge; an unmatched open walked backward needs a copy of γ\gamma whose context ends with that site, and such a copy exists because every procedure is called from main. Every path of the expanded graph projects to a realizable path. So by Theorem 2 the slice equals backward reachability from all copies of γ\gamma in the expanded graph, which the tests compute directly.

The slice is exact for realizable paths of the graph, not for runs. A realizable path need not be feasible, as in the intraprocedural case on the program slicing page, so the slice is not minimal in general.

Complexity

Proved, for the model here. Each procedure has one formal-out, so a path edge is determined by its first node and there are at most NN of them. Each enters the work list once and costs the number of edges into its first node, or for a formal-in the number of call sites of its procedure. Summary edges are added once. So SUMMARY-EDGES takes O(N+E)O(N + E), and each pass of SDG-SLICE takes O(N+E)O(N + E) like any graph search. With gg formal-outs per procedure, for global variables or reference parameters, the same count gives O(g(N+E))O(g (N + E)) for the summary edges.

Building the graph. The per-procedure parts cost what the program dependence graph costs: post-dominators, control dependence and reaching definitions, and the data edges can be quadratic in the size of a procedure. The summary edges are built once and serve every slice.

Compared. Horwitz, Reps and Binkley built summary edges from a linkage grammar, an attribute grammar whose productions are the calls. Reps, Horwitz, Sagiv and Rosay (1994) replaced it with the work-list method above, which is asymptotically faster and was also faster on their test programs. Inlining every call and slicing one big graph also respects context, but it grows exponentially with the depth of calls and fails for recursion.

Properties

  • Context-sensitive. No path in the slice enters a procedure at one call site and returns to another. This holds with recursion too, because summary edges are a fixed point, not an unrolling.
  • Exact for the graph. The slice is exactly the set of nodes on realizable paths to the criterion, as the tests check against a graph with one copy of each procedure per calling context, and against the PDG slice of the program with every call inlined.
  • One graph, many slices. Summary edges depend only on the program, not on the criterion.
  • Not a program. As with the PDG slice, the result is a set of nodes. Across procedures there is one more problem, parameter mismatch: the slice of a procedure can need an argument at one call site that another call site in the slice does not pass.
  • Static. It holds for every input and every calling context; a dynamic slice holds for one run.

Variants and improvements

  • Executable slices. Binkley (1993) adds to the slice the actual-in nodes, and the statements they depend on, that a callee needs at every kept call site, so that each kept call passes every parameter that the sliced callee reads.
  • Faster summary edges. The path-edge work list of Reps, Horwitz, Sagiv and Rosay replaced the linkage grammar. The same idea, tabulating same-level paths per procedure, is the core of the IFDS framework.
  • As CFL-reachability. Reps (1998) states the problem as CFL-reachability with the matched parentheses of a Dyck language, the form used by many later analyses.
  • Forward slices and chops. The same graph and summary edges give forward slices by searching along the edges, and precise interprocedural chops between two statements, studied by Reps and Rosay.
  • Specialization slicing. When one procedure needs different parts at different call sites, a slicer can make one copy of the procedure per needed part instead of taking the union.

When to use it

Use it for slicing programs with procedures when the slice must not mix calling contexts: debuggers, program understanding tools, change impact analysis and integration of program versions. The context-insensitive search is simpler and enough when procedures are small or called from one place. When the slice must run, add Binkley's step. When one run matters and not all inputs, use dynamic slicing.

Pitfalls

  • Searching the joined graph in one pass. It enters a procedure at one call and leaves at another, and the slice grows with statements no run connects to the criterion, like the statements of ss in the example.
  • Climbing in pass 2. If pass 2 follows parameter-in or call edges, it walks out of the callee into every caller and the context sensitivity is lost.
  • Forgetting the call node in pass 2. The actual-out depends on the call node, so the call statement is in the slice whenever its result is. Without that control edge the call disappears and the callee code in the slice never runs.
  • Slicing an inlined program with loops. If a call sits in a loop and is inlined, the locals of the callee must be killed at each inlined entry, or the dependence of one activation leaks into the next and the slice grows.
  • Expecting a runnable program. The slice can call a procedure that needs an argument the slice does not compute at that call site. Binkley's extension fixes this.
  • Reading the slice as minimal. Realizable paths can still be infeasible, so the slice can contain statements that no run needs.

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.

system_dependence_graph_slicing.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/system-dependence-graph-slicing/. The authors are listed in prov/6EV9PV.jsonl.
"""Interprocedural slicing with the system dependence graph of Horwitz,
Reps and Binkley, with summary edges built by the method of Reps, Horwitz,
Sagiv and Rosay.

A system is a dict from procedure name to a toy IR Program; "main" is the
procedure where runs start. Procedures use x = k, x = y, x = a op b and
x = call f(a, b, ...), with jump, br and ret. Parameters are passed by
value and the only result of a call is the value of its ret. Recursion is
allowed; the tests use systems without it, so that they can compare with
inlining.

Nodes of the SDG are tuples:

    ("s", P, lab, i)        statement i of block lab of P (the terminator
                            when i == len(instrs)); for a call this is the
                            call node
    ("entry", P)            the entry node of P
    ("fin", P, k)           formal-in node of parameter k of P
    ("fout", P)             formal-out node: the value that P returns
    ("ain", P, lab, i, k)   actual-in node of argument k of a call site
    ("aout", P, lab, i)     actual-out node: the value the call site gets

build_sdg(system) returns the graph as a dict from node to a list of
(kind, parent) pairs, where kind is "control", "data", "call" (call node
to entry), "pin" (actual-in to formal-in), "pout" (formal-out to
actual-out) or "summary". sdg_slice(system, crit) returns the set of nodes
of the slice; statements_of maps that set to statements (P, lab, i).
"""

import toyir

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


# --------------------------------------------- one procedure, as on the PDG page


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
    if i < len(prog.blocks[lab].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", "call"):
        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 instr_at(prog, node):
    lab, i = node
    b = prog.blocks[lab]
    return b.instrs[i] if i < len(b.instrs) else None


def ipdom(prog):
    """Immediate post-dominator of each block, with a virtual EXIT after
    every ret."""
    labels = list(prog.blocks)
    succ = {lab: (toyir.succs(prog, lab) or [EXIT]) for lab in labels}
    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
    if any(EXIT not in pdom[lab] for lab in labels):
        raise ValueError("every block must reach a ret")
    return {lab: max(pdom[lab] - {lab}, key=lambda x: len(pdom[x])) for lab in labels}


def block_control_deps(prog, ip):
    """For each block, the branch blocks it is control dependent on, plus
    ENTRY for the blocks that every run of the procedure passes."""
    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]
    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), with d a statement or ENTRY
    (for a parameter x)."""
    nodes = statements(prog)
    IN = {n: set() for n in nodes}
    IN[(prog.entry, 0)] = {(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


# ------------------------------------------------------------------ the SDG


def call_sites(system):
    """Dict from procedure name to the list of call sites (P, lab, i)."""
    sites = {f: [] for f in system}
    for P, prog in system.items():
        for n in statements(prog):
            ins = instr_at(prog, n)
            if ins is not None and ins[0] == "call":
                if ins[2] not in system:
                    raise ValueError("unknown procedure %r" % ins[2])
                if len(ins[3]) != len(system[ins[2]].params):
                    raise ValueError("wrong number of arguments at %r" % ((P,) + n,))
                sites[ins[2]].append((P,) + n)
    return sites


def _def_node(P, prog, d, x):
    """The SDG node that stands for definition d of x."""
    if d == ENTRY:
        return ("fin", P, prog.params.index(x))
    ins = instr_at(prog, d)
    if ins[0] == "call":
        return ("aout", P) + d
    return ("s", P) + d


def build_sdg(system, summaries=True):
    """The SDG of the system: a dict from node to a list of (kind, parent)."""
    par = {}
    procs = {}

    def add(n, kind, m):
        par.setdefault(n, []).append((kind, m))

    for P, prog in system.items():
        ip = ipdom(prog)
        cd = block_control_deps(prog, ip)
        rd = reaching_definitions(prog)
        procs[P] = {"ipdom": ip, "rd": rd}
        entry = ("entry", P)
        par.setdefault(entry, [])
        for k in range(len(prog.params)):
            add(("fin", P, k), "control", entry)
        add(("fout", P), "control", entry)
        for n in statements(prog):
            node = ("s", P) + n
            par.setdefault(node, [])
            for a in cd[n[0]]:
                add(node, "control", entry if a == ENTRY else ("s", P, a, len(prog.blocks[a].instrs)))
            ins = instr_at(prog, n)
            if ins is not None and ins[0] == "call":
                for k, arg in enumerate(ins[3]):
                    ain = ("ain", P) + n + (k,)
                    add(ain, "control", node)
                    for (d, x) in rd[n]:
                        if x == arg:
                            add(ain, "data", _def_node(P, prog, d, x))
                add(("aout", P) + n, "control", node)
            else:
                refs = REF(prog, n)
                for (d, x) in rd[n]:
                    if x in refs:
                        add(node, "data", _def_node(P, prog, d, x))
                if ins is None and prog.blocks[n[0]].term[0] == "ret":
                    add(("fout", P), "data", node)
    for f, sites in call_sites(system).items():
        for (P, lab, i) in sites:
            add(("entry", f), "call", ("s", P, lab, i))
            for k in range(len(system[f].params)):
                add(("fin", f, k), "pin", ("ain", P, lab, i, k))
            add(("aout", P, lab, i), "pout", ("fout", f))
    if summaries:
        for (a, o) in summary_edges(system, par):
            add(o, "summary", a)
    return par


def summary_edges(system, par):
    """Pairs (actual-in, actual-out) such that a same-level realizable path
    runs from the matching formal-in to the formal-out of the callee. The
    work list holds path edges (v, w): w is the formal-out of the procedure
    of v and a same-level realizable path runs from v to w."""
    sites = call_sites(system)
    path = set()
    targets = {}  # v -> set of w with (v, w) in path
    work = []
    summary = set()
    sum_par = {}  # actual-out -> actual-ins with a summary edge to it

    def propagate(v, w):
        if (v, w) not in path:
            path.add((v, w))
            targets.setdefault(v, set()).add(w)
            work.append((v, w))

    for P in system:
        propagate(("fout", P), ("fout", P))  # @line L12
    while work:  # @line L13
        v, w = work.pop()  # @line L14
        if v[0] == "fin":  # @line L15
            Q, k = v[1], v[2]
            for (P, lab, i) in sites[Q]:  # @line L16
                a, o = ("ain", P, lab, i, k), ("aout", P, lab, i)
                if (a, o) not in summary:  # @line L17
                    summary.add((a, o))
                    sum_par.setdefault(o, []).append(a)
                    for x in list(targets.get(o, ())):
                        propagate(a, x)
        else:
            for kind, x in par.get(v, []):  # @line L18
                if kind in ("control", "data"):
                    propagate(x, w)
            for x in sum_par.get(v, []):
                propagate(x, w)
    return summary  # @line L19


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


def start_nodes(system, crit, sdg=None):
    """The parents of the criterion: the definitions of the names of V that
    reach the point, and the control parents of the statement there."""
    P, lab, i, V = crit
    prog = system[P]
    rd = reaching_definitions(prog)
    start = {_def_node(P, prog, d, x) for (d, x) in rd[(lab, i)] if x in V}
    if sdg is None:
        sdg = build_sdg(system)
    start |= {m for kind, m in sdg[("s", P, lab, i)] if kind == "control"}
    return start


def sdg_slice(system, crit, sdg=None):
    """The two passes of Horwitz, Reps and Binkley. crit is (P, lab, i, V):
    the values of V just before statement (lab, i) of procedure P, in every
    calling context."""
    if sdg is None:
        sdg = build_sdg(system)
    work = list(start_nodes(system, crit, sdg))  # @line L1
    S = set(work)
    while work:  # @line L2
        n = work.pop()  # @line L3
        for kind, m in sdg[n]:  # @line L4
            if kind != "pout" and m not in S:  # @line L5
                S.add(m)
                work.append(m)
    work = list(S)  # @line L6
    while work:  # @line L7
        n = work.pop()  # @line L8
        for kind, m in sdg[n]:  # @line L9
            if kind not in ("pin", "call") and m not in S:  # @line L10
                S.add(m)
                work.append(m)
    return S  # @line L11


def reachability_slice(system, crit, sdg=None):
    """Plain backward reachability over every edge but the summary edges.
    This ignores calling context and can be larger than sdg_slice."""
    if sdg is None:
        sdg = build_sdg(system)
    work = list(start_nodes(system, crit, sdg))
    S = set(work)
    while work:
        n = work.pop()
        for kind, m in sdg[n]:
            if kind != "summary" and m not in S:
                S.add(m)
                work.append(m)
    return S


def statements_of(S):
    """The statements (P, lab, i) among the nodes of S."""
    return {n[1:] for n in S if n[0] == "s"}
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_system_dependence_graph_slicing.py 366 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/system-dependence-graph-slicing/. The authors are listed in prov/6EV9PV.jsonl.

import random

import toyir
from system_dependence_graph_slicing import (
    DEF,
    ENTRY,
    REF,
    block_control_deps,
    build_sdg,
    call_sites,
    ipdom,
    reachability_slice,
    reaching_definitions,
    sdg_slice,
    start_nodes,
    statements,
    statements_of,
    summary_edges,
)

MAIN = """
# params: n
B1:
  s = 0
  i = 0
  jump B2
B2:
  t = i < n
  br t B3 B4
B3:
  s = call add(s, i)
  i = call add(i, 1)
  jump B2
B4:
  ret i
"""

ADD = """
# params: a, b
B1:
  r = a + b
  ret r
"""


def page_system():
    return {"main": toyir.parse(MAIN), "add": toyir.parse(ADD)}


def test_page_example():
    system = page_system()
    for n in range(0, 6):
        assert toyir.run(system["main"], [n], funcs=system) == ("ret", n)
    crit = ("main", "B4", 0, {"i"})
    S = statements_of(sdg_slice(system, crit))
    assert S == {
        ("main", "B1", 1), ("main", "B2", 0), ("main", "B2", 1), ("main", "B3", 1),
        ("add", "B1", 0), ("add", "B1", 1),
    }
    # Without calling context, the slice also takes the statements of s.
    R = statements_of(reachability_slice(system, crit))
    assert R == S | {("main", "B1", 0), ("main", "B3", 0)}
    # The summary edges of the page: each argument reaches the result.
    sdg = build_sdg(system)
    summ = {(m, n) for n, ps in sdg.items() for kind, m in ps if kind == "summary"}
    assert summ == {
        (("ain", "main", "B3", j, k), ("aout", "main", "B3", j)) for j in (0, 1) for k in (0, 1)
    }


# ------------------------------------------------------------ random systems


def random_system(rng, nprocs):
    """F0 is main. Each Fj with j >= 1 gets one or two call sites in
    procedures Fi with i < j, so there is no recursion and every procedure
    is called from main."""
    names = ["F%d" % j for j in range(nprocs)]
    system = {}
    for f in names:
        system[f] = toyir.random_program(rng, rng.randint(2, 4), rng.randint(1, 4), rng.random() < 0.5)
    for j in range(1, nprocs):
        for _ in range(rng.randint(1, 2)):
            prog = system[names[rng.randrange(j)]]
            xs = [x for x in sorted({ins[1] for b in prog.blocks.values() for ins in b.instrs}) if x.startswith("x")]
            xs = sorted(set(xs) | set(prog.params))
            lab = rng.choice(list(prog.blocks))
            b = prog.blocks[lab]
            # In the entry block, the call goes after the definitions of the locals.
            lo = len(b.instrs) if lab == prog.entry else 0
            pos = rng.randint(lo, len(b.instrs))
            args = [rng.choice(xs) if rng.random() < 0.8 else rng.randint(-2, 5) for _ in range(2)]
            b.instrs.insert(pos, ("call", rng.choice(xs), names[j], args))
    main = system.pop("F0")
    return dict([("main", main)] + list(system.items()))


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


def test_random_systems_run():
    rng = random.Random(11)
    ok = 0
    for _ in range(100):
        system = random_system(rng, rng.randint(2, 4))
        out = toyir.run(system["main"], [rng.randint(-3, 6), rng.randint(-3, 6)], funcs=system)
        assert out[0] in ("ret", "trap")
        ok += out[0] == "ret"
    assert ok > 50


# --------------------------- reference 1: the graph with one copy per context


def contexts_of(system):
    """For each procedure, its calling contexts: strings of call sites from
    main."""
    sites = call_sites(system)
    out = {f: [] for f in system}

    def walk(f, ctx):
        out[f].append(ctx)
        for g in system:
            for site in sites[g]:
                if site[0] == f:
                    walk(g, ctx + (site,))

    walk("main", ())
    return out


def context_step(sdg, n, ctx):
    """Parents of the copy of n in context ctx, in the expanded graph."""
    for kind, m in sdg[n]:
        if kind == "summary":
            continue
        if kind in ("call", "pin"):
            # Up from the callee, only to the call site on top of ctx.
            if ctx and m[1:4] == ctx[-1]:
                yield m, ctx[:-1]
        elif kind == "pout":
            # Down into the callee at the call site of n.
            yield m, ctx + (n[1:4],)
        else:
            yield m, ctx


def expanded_slice(system, crit):
    """Backward reachability from every copy of the criterion in the graph
    that has one copy of each procedure per calling context. Its paths are
    the realizable paths of the SDG."""
    sdg = build_sdg(system, summaries=False)
    st = start_nodes(system, crit, sdg)
    seen = {(m, ctx) for ctx in contexts_of(system)[crit[0]] for m in st}
    stack = list(seen)
    while stack:
        n, ctx = stack.pop()
        for nxt in context_step(sdg, n, ctx):
            if nxt not in seen:
                seen.add(nxt)
                stack.append(nxt)
    return {n for (n, _) in seen}


def test_slice_equals_realizable_paths():
    rng = random.Random(7)
    for trial in range(150):
        system = random_system(rng, rng.randint(2, 4))
        sdg = build_sdg(system)
        for _ in range(3):
            crit = random_criterion(rng, system)
            assert sdg_slice(system, crit, sdg) == expanded_slice(system, crit)


def test_context_matters():
    """On many random systems the plain reachability slice is larger."""
    rng = random.Random(8)
    larger = 0
    for trial in range(150):
        system = random_system(rng, rng.randint(2, 4))
        sdg = build_sdg(system)
        crit = random_criterion(rng, system)
        S = sdg_slice(system, crit, sdg)
        R = reachability_slice(system, crit, sdg)
        assert S <= R
        larger += statements_of(S) < statements_of(R)
    assert larger > 0


# ----------------------------------------- reference 2: inline the program text


def inline(system):
    """Inline every call. Returns (prog, origin, chain, points, prefix):
    origin maps each statement of prog to the statement (P, lab, i) it comes
    from, chain maps it to the call sites of its context, points maps
    (statement, context) to its first statement in prog, and prefix maps a
    context to the prefix of the names of that copy."""
    blocks = {}
    origin, chain, points, prefix = {}, {}, {}, {}
    count = [0]

    def emit(P, pre, ctx, ret_to):
        prog = system[P]
        prefix[ctx] = pre

        def ren(a):
            return a if isinstance(a, int) else pre + a

        def mov(x, a):
            return ("const", x, a) if isinstance(a, int) else ("copy", x, a)

        def close(label, ins_list, orig_list, term, term_orig):
            blocks[label] = toyir.Block(ins_list, term)
            for k, o in enumerate(orig_list + [term_orig]):
                origin[(label, k)] = o
                chain[(label, k)] = ctx
                points.setdefault((o, ctx), (label, k))

        for L, b in prog.blocks.items():
            cur = pre + L
            instrs, orig = [], []
            for i, ins in enumerate(b.instrs):
                s = (P, L, i)
                if ins[0] == "call":
                    _, x, f, args = ins
                    count[0] += 1
                    q = "k%d." % count[0]
                    callee = system[f]
                    for pname, a in zip(callee.params, args):
                        instrs.append(mov(q + pname, ren(a)))
                        orig.append(s)
                    # Each activation has fresh locals. A loop around the
                    # call must not carry them from one activation to the
                    # next, so the copy kills them first. These kills have
                    # no origin: they are not statements of the system.
                    locs = {ins2[1] for b2 in callee.blocks.values() for ins2 in b2.instrs}
                    for v in sorted(locs - set(callee.params)):
                        instrs.append(("const", q + v, 0))
                        orig.append(None)
                    post = "%s+%d" % (cur, i)
                    close(cur, instrs, orig, ("jump", q + callee.entry), s)
                    emit(f, q, ctx + (s,), (post, q + "$ret"))
                    cur, instrs, orig = post, [("copy", ren(x), q + "$ret")], [s]
                else:
                    if ins[0] == "const":
                        instrs.append(("const", ren(ins[1]), ins[2]))
                    elif ins[0] == "copy":
                        instrs.append(("copy", ren(ins[1]), ren(ins[2])))
                    else:
                        instrs.append(("op", ren(ins[1]), ins[2], ren(ins[3]), ren(ins[4])))
                    orig.append(s)
            t = b.term
            s = (P, L, len(b.instrs))
            if t[0] == "jump":
                close(cur, instrs, orig, ("jump", pre + t[1]), s)
            elif t[0] == "br":
                close(cur, instrs, orig, ("br", ren(t[1]), pre + t[2], pre + t[3]), s)
            elif ret_to is None:
                close(cur, instrs, orig, ("ret", ren(t[1])), s)
            else:
                instrs.append(mov(ret_to[1], ren(t[1])))
                orig.append(s)
                close(cur, instrs, orig, ("jump", ret_to[0]), s)

    emit("main", "", (), None)
    main = system["main"]
    ordered = {main.entry: blocks.pop(main.entry)}
    ordered.update(blocks)
    return toyir.Program(list(main.params), ordered), origin, chain, points, prefix


def intra_slice(prog, starts, skip):
    """Backward reachability in the PDG of one procedure, from a set of
    points (lab, i, V). The statements of skip kill definitions but are not
    nodes of the graph."""
    ip = ipdom(prog)
    cd = block_control_deps(prog, ip)
    rd = reaching_definitions(prog)
    out = {ENTRY} | skip

    def term(a):
        return (a, len(prog.blocks[a].instrs))

    K = set()
    for (lab, i, V) in starts:
        K |= {d for (d, x) in rd[(lab, i)] if x in V and d not in out}
        K |= {term(a) for a in cd[lab] if a != ENTRY}
    stack = list(K)
    while stack:
        n = stack.pop()
        ps = {term(a) for a in cd[n[0]] if a != ENTRY}
        ps |= {d for (d, x) in rd[n] if x in REF(prog, n) and d not in out}
        for m in ps:
            if m not in K:
                K.add(m)
                stack.append(m)
    return K


def test_slice_equals_slice_of_inlined_program():
    rng = random.Random(23)
    for trial in range(120):
        system = random_system(rng, rng.randint(2, 4))
        prog, origin, chain, points, prefix = inline(system)
        args = [rng.randint(-3, 6), rng.randint(-3, 6)]
        assert toyir.run(prog, args) == toyir.run(system["main"], args, funcs=system)
        sdg = build_sdg(system)
        for _ in range(3):
            crit = random_criterion(rng, system)
            P, lab, i, V = crit
            starts, ctxs = [], []
            for (o, ctx), (L, k) in points.items():
                if o == (P, lab, i):
                    starts.append((L, k, {prefix[ctx] + v for v in V}))
                    ctxs.append(ctx)
            K = intra_slice(prog, starts, {n for n, o in origin.items() if o is None})
            # A statement of a callee runs only if its call runs, so the
            # call sites of its context count as well.
            want = {origin[n] for n in K}
            for n in K:
                want |= set(chain[n])
            for ctx in ctxs:
                want |= set(ctx)
            assert statements_of(sdg_slice(system, crit, sdg)) == want


# ------------------------------------------------- summary edges, directly


def same_level_path(sdg, src, dst):
    """Is there a path from src to dst in which every call or parameter-in
    edge is matched by the parameter-out edge of the same call site?"""
    start = (dst, ())
    seen = {start}
    stack = [start]
    while stack:
        n, ctx = stack.pop()
        if n == src and ctx == ():
            return True
        for nxt in context_step(sdg, n, ctx):
            if nxt not in seen:
                seen.add(nxt)
                stack.append(nxt)
    return False


def test_summary_edges_match_same_level_paths():
    rng = random.Random(31)
    for trial in range(150):
        system = random_system(rng, rng.randint(2, 4))
        sdg = build_sdg(system, summaries=False)
        want = set()
        for f, sites in call_sites(system).items():
            for k in range(len(system[f].params)):
                if same_level_path(sdg, ("fin", f, k), ("fout", f)):
                    want |= {(("ain",) + s + (k,), ("aout",) + s) for s in sites}
        assert summary_edges(system, sdg) == want

History

Weiser's 1984 paper already sliced across procedures, by passing criteria from callers to callees and back, but it did not keep the calling contexts apart, so a procedure called from two places joined their slices. Horwitz, Reps and Binkley presented the system dependence graph and the two-pass slice at PLDI 1988, with summary edges built from a linkage grammar, and gave the full treatment in TOPLAS in 1990. Binkley (1993) showed how to make the slices run. Reps, Horwitz, Sagiv and Rosay (1994) gave the faster work-list method for summary edges, and Reps (1998) placed the method within CFL-reachability, next to interprocedural dataflow analysis and some pointer analyses. The PLDI paper was later chosen among the most influential papers of the first twenty years of the conference.

References

  1. Susan Horwitz, Thomas Reps and David Binkley, Interprocedural slicing using dependence graphs, Proceedings of the ACM SIGPLAN 1988 Conference on Programming Language Design and Implementation, ACM SIGPLAN Notices 23(7), 1988, pages 35-46, the system dependence graph, summary edges from a linkage grammar, and the two-pass slice
  2. 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, the journal version, with the calling-context problem, the graph, the two passes and their precision
  3. Thomas Reps, Susan Horwitz, Mooly Sagiv and Genevieve Rosay, Speeding up slicing, ACM SIGSOFT Software Engineering Notes 19(5) (FSE '94), 1994, pages 11-20, the work-list method with path edges that computes the summary edges, used here
  4. David Binkley, Precise executable interprocedural slices, ACM Letters on Programming Languages and Systems 2(1-4), 1993, pages 31-45, parameter mismatch, and how to extend the slice so that it runs
  5. Thomas Reps, Program analysis via graph reachability, Information and Software Technology 40(11-12), 1998, pages 701-726, interprocedural slicing as reachability along paths whose calls and returns match like parentheses
  6. Mark Weiser, Program slicing, IEEE Transactions on Software Engineering SE-10(4), 1984, pages 352-357, the first interprocedural slices, which do not keep apart the calling contexts of a procedure

About this page

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

LadderLevelWhat the next level needs
Human proofH2 full proof
  • correctness: no review record reviews/6EV9PV/proof-correctness.yaml
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example