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.
- Solves
- Program slicing
- 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
- Model
- Word RAM
- Properties
- deterministicnot executable resultofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 is instruction of block , or its terminator; and are the variables written and read; every block reaches a ret. The input is a program and a criterion , the values of the variables of just before statement . The output is the dependence slice: the least set of instructions and branches that contains the definitions of that reach and the branches that 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 labeled means that defines , reads , and some path in the control flow graph goes from just after to with no other definition of (data dependence, from reaching definitions). A control edge means that the block of is control dependent on the branch 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 that reach , and the control parents of . This is the same as adding a node at that reads .
PDG-SLICE(P, p, V)- 1
G <- the PDG of P, unless it is already built - 2
W <- the statements s such that a definition of some x in V by s reaches p - 3
W <- W union the control parents of p; remove ENTRY from W - 4
S <- W - 5
while W is not empty do - 6
remove a node z from W - 7
for each control or data edge x -> z of G do - 8
if x is not ENTRY and x is not in S then add x to S and to W - 9
return 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 , keep every jump, turn each branch outside 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 only when it is the statement and . 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 at a point.
Example
Take the program of the problem page, which sums the odd numbers up to in and computes .
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 |
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 , the definitions of 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 |
|---|---|
| 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 the same graph gives 8 statements, and for the value of 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 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 the slice is every statement except the jumps and the ret. The projection keeps jump B2 in B4 and gives for , 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:
- 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.
- Relevant names. For a set 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 or to at . A dropped instruction never writes a relevant variable, because the reader would make it a data parent of a statement of .
- 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 or .
- 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 at 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. 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 , and are as on the page. The criterion is . Post-dominance is taken on blocks with a virtual EXIT after every ret; is the immediate post-dominator of block . Block is control dependent on block , written , if some successor of is post-dominated by ( allowed) and does not strictly post-dominate .
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 are the branches of the blocks with , plus ENTRY for some blocks; and the data parents of are the pairs with , and a path from the successor of to with no definition of before , plus pairs for parameters. The reaching definitions at are the pairs with such a path from the successor of to .
1. The search finds the dependence slice
Let be the dependence slice of program slicing: the least set of instructions and branches that contains (rule 1) every that defines some with a path from the successor of to free of definitions of , (rule 2) every branch on which 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 .
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 , and there are finitely many statements, so it stops. Every node it adds is a parent of a node of , so by induction on the order of addition every node of is in (rule 3). When the loop stops, every node of has been removed from the work list once and all its parents other than ENTRY are in , so is closed under rule 3 and contains the sets of rules 1 and 2. Hence , by the leastness of .
Each node enters the work list at most once and each edge is read once, so the search costs for statements and edges.
2. Relevant names of the slice
From here on, 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 , let be the set of names such that some path , , has no definition of among and ends either at with , or at some with .
Lemma 2. For every statement and successor :
- (F1) if , then ; in all cases ;
- (F2) if is an instruction not in , then , so ;
- (F3) if is a terminator, then ;
- (F4) ;
- (F5) for a
retstatement , if and otherwise.
Proof. F1: a path of length 0 for the first part; for the second, put in front of the path for from , which is allowed since does not define . F2: let by a path from . If it ends at with , then satisfies rule 1. If it ends at that reads , then is data dependent on , and rule 3 puts in . Both contradict . 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 , because holds only instructions and branches.
3. Influence and control dependence
For a block that ends in a branch, let be the set of blocks reachable from a successor of by a path that does not enter . Two standard facts about post-dominance: (PD1) if and post-dominate each other, then ; (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 is in , the transitive closure of control dependence from . Also, strictly post-dominates every , and holds no ret block when EXIT.
Proof. (KF) by definition. Take any path from to EXIT and put in front of it the path from to that avoids after . The result runs from to EXIT, so it meets , and only in the part after . So strictly post-dominates . If were a ret block, the path EXIT would avoid EXIT.
Now let , , be a path with . Induction on . Let be the largest index in such that does not post-dominate . If exists, post-dominates (for trivially), so . For this gives . For , by a shorter path, so by induction, and . If does not exist, post-dominates and . If , then through , since a block does not strictly post-dominate itself. If , then and both strictly post-dominate , so post-dominates by PD2, and post-dominates by KF, so by PD1, which is false.
Lemma 4. If the branch at the end of is not in , then no block of holds a statement of or the point .
Proof. Suppose holds or holds . By Lemma 3 there is a chain with and . Each with ends in a branch , since a block with one successor has as its immediate post-dominator and so has no control dependents. The statement or is control dependent on , so by rule 3 or rule 2. Each statement of , in particular , is control dependent on , so going down from to , rule 3 gives . So , a contradiction.
4. The projection
Let be the projection of on : instructions of stay, all jumps stay, a branch of stays, a branch at the end of becomes jump , or ret 0 if is EXIT, and a ret a keeps only when it is the statement and (by F5, exactly when there). For , let with the number of instructions of in before position ; it is the place in of the first kept statement of at or after , and .
Consider a run of that reads no undefined name. Say when and, for each , and are both undefined or both defined and equal.
Lemma 5 (one step). Let .
- an instruction not in that does not trap: moves to , stays, and .
- an instruction in : traps at if and only if traps at ; otherwise both move and the relation holds after the step.
- a jump or a branch in : both move to the start of the same block with unchanged environments, and the relation holds there.
- a
ret: both runs return, with the same value if kept the operand.
Proof. (1) because is not kept, and by F2 writes no name of . (2) runs the same instruction on operands that agree, by F1, so both trap or both compute the same value for ; is the next statement of , and by F1. (3) The branch reads names of by F1, so it goes the same way; by F3. (4) If the operand is kept, it is in by F5.
Lemma 6 (a dropped branch). Let with a branch at the end of , and . makes one step to the start of , or returns 0 if is EXIT. Until first enters , it stays in blocks of , makes no observation and does not return if EXIT; when it enters , its configuration is related to 's.
Proof. By the definition of and Lemma 3. By Lemma 4 the blocks visited hold no statement of and not , so every step there is case 1 of Lemma 5 or a terminator, and by F2 and F3 the sets shrink along the run and no relevant name of the later points is written. So the environment of at the start of agrees with on there.
Theorem (Reps and Yang). For every input on which the run of reads no undefined name and reaches a ret, the run of reaches a ret and . If the run of traps or does not end, is a prefix of .
Proof. At the start the relation holds. Lemmas 5 and 6 cut the run of into pieces, each matched with at most one step of , and keep the relation at the end of each piece. The block of is never inside a dropped region (Lemma 4), so the visits of the two runs to it match one to one. In a visit, reaches when reaches its last kept statement before , or the block start, and the statements of between there and are dropped instructions, which keep the relation. So at each observation, the environments agree on (F4), and the tuples are equal. If returns, returns at the matching moment (Lemma 5 case 4, or Lemma 6 with = EXIT), and neither observes again. If traps at a dropped instruction, may go on and observe more; at a kept one, traps too. If does not end, each of its observations is matched in order.
Corollary. Since the PDG slice contains the data and control parents of each of its statements, the hypotheses of section 2 also hold for the criterion for every . 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 that returns, reaches each statement of the slice as many times as does, with the same values of 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 time, where is the number of statements and the number of control and data edges. It needs extra space for and the work list.
Building the graph. The graph itself costs more, and it can have edges, for example definitions of one variable that all reach uses. The program dependence graph page gives the cost: control edges in 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 times for 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,breakandcontinuestatements 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,breakorcontinuecan change where control goes, as thecontinueexample shows. - Starting at the criterion node. The node of itself and its own data parents are the slice of the statement with . For another set , start from the definitions of that reach and the control parents of .
- 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.
# 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
- 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
- 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 8QKCJ8 Edit this page History Report an error Markdown