Data structurecore
Program dependence graph
Also called PDG.
A graph of the statements of a procedure with edges for data and control dependences, used for slicing, vectorization and scheduling.
- Time
- O(m + c) control-edgesO(n (n + m) r) data-edgesO(n + c + d) slice
- Space
- O(n + m + c + d) total
- Where
- c = the number of control dependence edges; d = the number of flow dependence edges; m = the number of CFG edges; n = the number of instructions; r = the number of definitions
- Model
- Word RAM
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Jeanne Ferrante, Karl J. Ottenstein, Joe D. Warren, 1987
A program dependence graph (PDG) has one node for each instruction of a procedure and two kinds of edges. A data edge goes from an instruction that defines a variable to an instruction that may read that value. A control edge goes from a branch to an instruction whose execution the branch decides. The control flow graph fixes one order for the instructions; the PDG keeps only the order that the meaning of the program needs. So two instructions with no path between them in the PDG can be reordered or run in parallel, and the instructions that can affect a given one are its ancestors. Ferrante, Ottenstein and Warren (1987) built the control edges from post-dominance, and the PDG is the basis of program slicing, aggressive dead code elimination and dependence-based vectorization.
In plain words
A recipe is written as a list of steps, but many steps do not need the step before them. You can chop the onions while the water boils. The PDG draws only the real needs. An arrow from step A to step B means B uses something A made, or B happens only if a test in A came out a certain way. Any order that follows the arrows cooks the same dish. To find every step that can change the taste of the sauce, follow the arrows backward from the sauce.
The abstract type
The PDG of a procedure is a directed graph with these parts:
- Nodes. One node for each instruction, with the terminator of each block counted as an instruction, and one node ENTRY that stands for the start of the procedure and the definitions of the parameters.
- Control edges : instruction is control dependent on the branch through the edge of to the block . The label is the outcome of the branch that makes run. Instructions that run on every run of the procedure depend on ENTRY.
- Data edges : the definition of variable at reaches the instruction , which reads . These are the flow (true) dependences of data dependence. Anti and output dependences are added when the PDG is used to reorder memory operations, as described under Variants.
It supports these operations:
- BUILD(procedure): make the graph.
- CONTROL-PARENTS() and DATA-PARENTS(): the edges into .
- CHILDREN(): the edges out of .
- SLICE(): all nodes from which is reachable, the backward slice of .
Representation
Each node has two lists of incoming edges and two lists of outgoing edges, one of each for control and for data. An instruction node is a pair (block, index), where the index equal to the number of instructions in the block names the terminator. The block-level control dependences are kept as well: every instruction of a block has the same control parents, so the per-instruction control edges are the block edges copied to each instruction.
Ferrante, Ottenstein and Warren add region nodes. All instructions that have the same set of control parents with the same labels hang below one region node, and the region node carries the control edges. This saves space when many instructions share their conditions, and it gives a tree of regions that a code generator can walk to put the instructions back into a control flow graph.
Operations
BUILD(P) ▷ P: a procedure with blocks, an entry block, ret terminators- 1
G ← the CFG of P, with a node START, a node EXIT, an edge START → entry, an edge START → EXIT, and an edge to EXIT from every ret block- 2
ipdom ← immediate post-dominators of G ▷ dominators of the reverse of G, rooted at EXIT - 3
for each edge a → b of G with b ≠ ipdom(a) do - 4
y ← b - 5
while y ≠ ipdom(a) do - 6
src ← ENTRY if a = START, else the terminator of a - 7
for each instruction i of block y: add control edge (src, i, b) - 8
y ← ipdom(y) - 9
IN ← reaching definitions of P, with the parameters defined at ENTRY - 10
for each block B do - 11
cur ← IN[B], grouped by variable - 12
for each instruction u of B, in order, terminator last do - 13
for each variable v that u reads, each d in cur[v]: add data edge (d, u, v) - 14
if u defines v then cur[v] ← {u} SLICE(y)- 15
S ← {y}; stack ← [y] - 16
while stack is not empty do - 17
z ← pop(stack) - 18
for each control or data edge (x, z, ·) into z with x ∉ S: add x to S, push x - 19
return S
Control edges (L1 to L8). Line L1 builds the augmented CFG of control dependence. The edge START → EXIT makes the blocks that run on every run depend on START, which the PDG shows as ENTRY. Line L2 computes the post-dominator tree, for example with the Cooper-Harvey-Kennedy iteration on the transpose graph. Lines L3 to L8 are the walk of Ferrante, Ottenstein and Warren: for each edge , the blocks that depend on through it are the blocks on the post-dominator tree path from up to , with left out. A block whose terminator is jump has one successor, which is its immediate post-dominator, so only the terminators br get children. A block can depend on its own terminator when it is a loop test.
Data edges (L9 to L14). Line L9 solves reaching definitions, a forward gen-kill problem. Lines L10 to L14 then walk each block once. The set holds the definitions of that reach the current point. A definition inside the block replaces it, so a use after a definition in the same block gets one edge. These edges are the def-use chains of the procedure.
Slicing (L15 to L19). A backward slice is plain reachability over the reversed edges. It is the method of PDG slicing, and its result is a set of instructions that can affect .
Example
Take the toy IR program that adds the odd numbers below the parameter n:
B1:
i = 0
s = 0
jump B2
B2:
t1 = i < n
br t1 B3 B6
B3:
t2 = i % 2
br t2 B4 B5
B4:
s = s + i
jump B5
B5:
i = i + 1
jump B2
B6:
ret s
The PDG has 13 nodes: ENTRY and 12 instructions. The block-level control dependences, worked out on the control dependence page, are B1, B2 and B6 on START, B2, B3 and B5 on the branch of B2 with label B3, and B4 on the branch of B3 with label B4. Copied to the instructions, they give 14 control edges:
| from | to | label |
|---|---|---|
| ENTRY | i = 0, s = 0, jump B2 (B1), t1 = i < n, br t1 B3 B6 (B2), ret s (B6) |
B1 |
br t1 B3 B6 |
t1 = i < n, br t1 B3 B6 (B2), t2 = i % 2, br t2 B4 B5 (B3), i = i + 1, jump B2 (B5) |
B3 |
br t2 B4 B5 |
s = s + i, jump B5 (B4) |
B4 |
The 15 data edges are:
| definition | uses reached |
|---|---|
i = 0 and i = i + 1 |
t1 = i < n, t2 = i % 2, s = s + i, i = i + 1 (8 edges) |
s = 0 and s = s + i |
s = s + i, ret s (4 edges) |
ENTRY (parameter n) |
t1 = i < n |
t1 = i < n |
br t1 B3 B6 |
t2 = i % 2 |
br t2 B4 B5 |
The slice of ret s holds ENTRY and every instruction except the three jumps: the jumps define nothing and decide nothing. The slice of i = i + 1 is ENTRY, i = 0, i = i + 1, t1 = i < n and br t1 B3 B6, so the computation of s and the parity test do not affect i. The loop test is its own control parent, which is how the PDG shows that it runs again on each trip.
Correctness
The PDG is correct when its control edges are exactly the control dependences of Ferrante, Ottenstein and Warren, copied to the instructions, and its data edges are exactly the pairs (definition, use) joined by a path with no other definition of the same variable. The proof in proofs/correctness.md shows both. For the control edges it shows that the walk at an edge visits exactly the nodes that post-dominates and that do not strictly post-dominate . For the data edges it shows that the least solution of the reaching definitions equations holds exactly the definitions with such a definition-clear path, and that the scan of lines L10 to L14 adds the same pairs at instruction level. The tests compare the control edges with a brute-force search over the paths of the definition on random graphs, and the data edges with a search over instruction positions on random programs.
Proof: BUILD gives exactly the control dependences and the flow dependencesfull
We use the notation of the page. is the augmented CFG of line L1, is EXIT, and every node of reaches . Post-dominance and are taken in . The facts about the post-dominator tree that we use are those of the post-dominance page: the post-dominators of a node are exactly the ancestors of in the tree, with itself, and the strict post-dominators of are and its ancestors.
Part 1: the control edges
Definition. Block is control dependent on block through the edge if and does not strictly post-dominate . The control dependence page proves that this edge form is equivalent to the path form of Ferrante, Ottenstein and Warren.
Lemma 1. For every edge of , post-dominates .
Proof. The node has a successor, so and exists. Let be a path from to . Then followed by is a path from to , so it contains . Since , the node is on .
Lemma 2. For an edge , the set is the set of nodes on the tree path from up to , with left out. In particular it is empty when .
Proof. holds iff is or an ancestor of . strictly post-dominates iff is or an ancestor of it. By Lemma 1, is or an ancestor of . So the ancestors of (with ) fall into two parts: those strictly below on the path from , and with its ancestors. The first part is .
Claim 1. Lines L3 to L8 add the control edge for an instruction of block exactly when is control dependent on through , where is ENTRY if is START and the terminator of otherwise.
Proof. If , line L3 skips the edge, and is empty by Lemma 2. Otherwise the loop of lines L5 to L8 starts at and moves to the parent in the tree until it meets . It meets it, because is an ancestor of by Lemma 1, and each step moves one level up. So the loop body runs for exactly the nodes of , and line L7 adds the edges for all instructions of each of them. The node EXIT is never in for , since it strictly post-dominates every other node, so line L7 always finds a real block.
Every instruction of a block runs exactly when the block runs, so giving all of them the control parents of the block is the instruction-level form of the same relation.
Part 2: the data edges
A position is an instruction of a block, the terminator included. A definition of at a position, or of a parameter at ENTRY, reaches a position if there is a path in the CFG from just after to on which no position before defines . For ENTRY, the path starts at the first position of the entry block. The specification is: is a data edge iff reads and the definition of reaches .
The equations. For a block , let be the last definition in of each variable that defines, and the set of variables that defines. The code computes, by round-robin iteration from and ,
where is the set of parameter definitions at ENTRY if is the entry block and empty otherwise.
Lemma 3. The iteration stops, and then iff the definition of reaches the first position of .
Proof. The right-hand sides are monotone in the sets, the sets only grow from their start values, and they are subsets of a finite set of pairs, so the iteration stops. Let be the set of pairs such that reaches the first position of .
(.) Take with a witness path, and use induction on the number of blocks that the path enters after . If is a parameter and the path is empty, is the entry and . If is in block and the next block is , then is the last definition of in , because the path after to the end of has no definition of , so . Otherwise the path enters a block before and crosses all of it without defining . By induction , and , so . These inclusions hold at the fixpoint because it satisfies the equations.
(.) Every value that the iteration produces is in , by induction on the steps. The start values are empty or are , and a pair of reaches the start of every successor of . A pair that enters comes from , which is in , or from some with . A pair of is in , or it is in with , so its witness path extends through and the edge without a new definition of .
Claim 2. Lines L10 to L14 add iff reads and reaches .
Proof. Fix a block . The invariant of the loop of line L12 is: before position , the set is the set of definitions of that reach . Before the first position this is Lemma 3, because line L11 groups . If position does not define , a definition reaches the next position iff it reaches , since the path can be extended by one step and no new definition of is crossed. If defines , the only definition of that reaches the next position is itself, because every path from an earlier definition passes . Line L14 sets , which keeps the invariant. Line L13 runs before line L14, so a use of in an instruction that also defines , such as i = i + 1, gets the definitions that reach it from before. The loop adds exactly the triples of the claim at each position.
Claims 1 and 2 together say that the graph built by BUILD has exactly the control edges and the flow dependence edges of its definition. SLICE returns the nodes from which is reachable along these edges, by the usual argument for a graph search: every node it adds has a path to , and every node with a path to is added when the last edge of its path is examined.
Complexity
The model is the word RAM, and the unit step is one operation on a hash set or list with one element. Let be the number of instructions, the number of CFG edges, the number of control edges and the number of data edges.
- Post-dominators. The Cooper-Harvey-Kennedy iteration is fast in practice, and the Lengauer-Tarjan algorithm takes time.
- Control edges. Each step of the walk adds at least one new edge, so lines L3 to L8 take . The number can be : the control dependence page has a chain with back edges where blocks give dependences. Region nodes reduce the stored edges in common cases, but not in the worst case.
- Data edges. With definitions, each round of the reaching definitions iteration costs , and a round-robin iteration needs at most rounds, so the worst case is . Visiting the blocks in reverse postorder needs only a few rounds on usual code. The scan of lines L10 to L14 costs beyond that. The number can also be quadratic: definitions of one variable that all reach uses give edges.
- Space. .
- Queries. With adjacency lists, CONTROL-PARENTS and DATA-PARENTS cost per edge returned, and SLICE costs .
Variants
- Region nodes. As in the original paper, an extra node per set of equal control conditions.
- System dependence graph. Horwitz, Reps and Binkley (1990) join one PDG per procedure with call, parameter-in and parameter-out edges, plus summary edges, so that slicing across calls can respect calling context. See system dependence graph slicing.
- All data dependences. For reordering, the data edges must include anti dependences (a read before a write) and output dependences (two writes), and the dependences through memory, which need alias information. Loop-carried dependences with distance and direction vectors are the input of loop vectorization and parallelization.
- SSA-based PDG. On static single assignment form, each use has one reaching definition, so data edges are the SSA def-use edges and reaching definitions is not needed. The sea of nodes carries this idea further and drops the blocks.
- Weak control dependence. Some tools use the weak form of Podgurski and Clarke, so that code after a loop depends on the loop test, which keeps non-termination in slices.
When to use it
Use a PDG when the question is "what can affect this" or "what can move": slicing for debugging and program understanding, dead code removal that starts from the outputs and keeps only what they need, finding statements that can run in parallel, and vectorization, where cycles of dependences inside a loop decide which statements can be vectorized. For plain forward data flow analyses a CFG is simpler, and for most scalar optimizations SSA with def-use chains gives the data edges at lower cost.
Pitfalls
- Forgetting the edge START → EXIT. Without it, blocks that always run have no control parent, and a slice of them misses the dependence on the procedure being called at all.
- Several returns or no return. The post-dominator tree needs one exit, so add EXIT with an edge from each return. A loop that never exits leaves blocks that do not reach EXIT, and the walk then has no immediate post-dominator for them. Add a fake exit edge first.
- Flow edges are not enough to reorder. Two writes to the same variable have no flow edge between them, but they cannot be swapped. Add anti and output edges before reordering.
- Jumps disappear from slices. A slice is a set of instructions, not a program. To run a slice, the jumps and the block structure must be rebuilt, for example from the region tree.
- Memory. Data edges through loads and stores depend on alias analysis. An edge left out makes a slice or a reordering wrong.
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/program-dependence-graph/. The authors are listed in prov/AK2XM4.jsonl.
"""The program dependence graph of a toy IR procedure.
Control dependence follows Ferrante, Ottenstein and Warren (1987): the CFG
gets a node START with edges to the entry block and to a node EXIT, and an
edge from every ret block to EXIT. For each edge (a, b) where b is not the
immediate post-dominator of a, the walk from b up the post-dominator tree to
ipdom(a), not included, gives the nodes that are control dependent on a
through the edge (a, b). Data dependence is flow dependence: an edge from a
definition to each use that it reaches, found by reaching definitions.
A PDG node is ("ENTRY",) for START and the parameters, or (label, i): the
instruction i of the block, where i = len(instrs) is the terminator.
"""
import toyir
START = "START"
EXIT = "EXIT"
ENTRY = ("ENTRY",)
def idoms(nodes, succ, root):
"""Immediate dominators by the Cooper-Harvey-Kennedy iteration.
nodes: all nodes; succ: dict node -> list of nodes; root: the start.
Returns a dict from each node that root reaches to its immediate
dominator; root maps to itself.
"""
po, seen, stack = {}, {root}, [(root, iter(succ[root]))]
while stack:
v, it = stack[-1]
w = next(it, None)
if w is None:
po[v] = len(po)
stack.pop()
elif w not in seen:
seen.add(w)
stack.append((w, iter(succ[w])))
pred = {v: [] for v in nodes}
for v in nodes:
for w in succ[v]:
pred[w].append(v)
order = sorted(po, key=lambda v: -po[v])
dom = {root: root}
def intersect(a, b):
while a != b:
while po[a] < po[b]:
a = dom[a]
while po[b] < po[a]:
b = dom[b]
return a
changed = True
while changed:
changed = False
for b in order[1:]:
ps = [p for p in pred[b] if p in dom]
new = ps[0]
for p in ps[1:]:
new = intersect(p, new)
if dom.get(b) != new:
dom[b] = new
changed = True
return dom
def augmented_cfg(prog):
"""The CFG with START and EXIT, as (nodes, succ). The edge START -> EXIT
makes the blocks that run on every run control dependent on START."""
nodes = [START] + list(prog.blocks) + [EXIT]
succ = {START: [prog.entry, EXIT], EXIT: []}
for label in prog.blocks:
s = toyir.succs(prog, label)
succ[label] = s if s else [EXIT]
return nodes, succ
def post_dominator_tree(nodes, succ, exit_node):
"""ipdom as a dict: dominators of the reversed graph, rooted at the exit."""
rsucc = {v: [] for v in nodes}
for v in nodes:
for w in succ[v]:
rsucc[w].append(v)
return idoms(nodes, rsucc, exit_node)
def control_dependences(nodes, succ, exit_node):
"""The set of triples (x, y, s): y is control dependent on x through the
edge x -> s. Every node must reach exit_node."""
ipdom = post_dominator_tree(nodes, succ, exit_node)
out = set()
for a in nodes:
for b in succ[a]:
if b == ipdom.get(a):
continue
runner = b
while runner != ipdom[a]:
out.add((a, runner, b))
runner = ipdom[runner]
return out
def block_control_dependences(prog):
nodes, succ = augmented_cfg(prog)
return control_dependences(nodes, succ, EXIT)
def reaching_definitions(prog):
"""IN sets per block: sets of (node, var). The parameters are defined at
ENTRY."""
gen, kill_vars = {}, {}
for label, b in prog.blocks.items():
last = {}
for i, ins in enumerate(b.instrs):
d = toyir.defs(ins)
if d is not None:
last[d] = (label, i)
gen[label] = {(n, v) for v, n in last.items()}
kill_vars[label] = set(last)
preds = toyir.preds(prog)
inn = {label: set() for label in prog.blocks}
out = {label: set(gen[label]) for label in prog.blocks}
boundary = {(ENTRY, p) for p in prog.params}
changed = True
while changed:
changed = False
for label in prog.blocks:
s = set(boundary) if label == prog.entry else set()
for p in preds[label]:
s |= out[p]
inn[label] = s
o = gen[label] | {(n, v) for (n, v) in s if v not in kill_vars[label]}
if o != out[label]:
out[label] = o
changed = True
return inn
def data_dependences(prog):
"""The set of triples (d, u, v): the definition of v at node d reaches the
node u, which reads v."""
inn = reaching_definitions(prog) # @line L9
out = set()
for label, b in prog.blocks.items(): # @line L10
cur = {}
for n, v in inn[label]: # @line L11
cur.setdefault(v, set()).add(n)
items = list(b.instrs) + [b.term]
for i, ins in enumerate(items): # @line L12
used = toyir.term_uses(ins) if i == len(b.instrs) else toyir.uses(ins)
for v in used:
for d in cur.get(v, ()):
out.add((d, (label, i), v)) # @line L13
if i < len(b.instrs):
d = toyir.defs(ins)
if d is not None:
cur[d] = {(label, i)} # @line L14
return out
class PDG:
"""The nodes and the two kinds of edges.
block_cd: set of (x, y, s): block y is control dependent on x through the
CFG edge x -> s; x may be START.
control: set of (x, y, s): node y is control dependent on the branch
node x, through the CFG edge to block s; x is ENTRY for START.
data: set of (d, u, v), flow dependences.
"""
def __init__(self, prog):
self.prog = prog
self.nodes = [ENTRY]
for label, b in prog.blocks.items():
self.nodes += [(label, i) for i in range(len(b.instrs) + 1)]
nodes, succ = augmented_cfg(prog) # @line L1
ipdom = post_dominator_tree(nodes, succ, EXIT) # @line L2
self.block_cd, self.control = set(), set()
for a in nodes:
for b in succ[a]: # @line L3
if b == ipdom.get(a):
continue
y = b # @line L4
while y != ipdom[a]: # @line L5
src = ENTRY if a == START else (a, len(prog.blocks[a].instrs)) # @line L6
self.block_cd.add((a, y, b))
for i in range(len(prog.blocks[y].instrs) + 1):
self.control.add((src, (y, i), b)) # @line L7
y = ipdom[y] # @line L8
self.data = data_dependences(prog)
def control_parents(self, node):
return {(x, s) for x, y, s in self.control if y == node}
def data_parents(self, node):
return {(d, v) for d, u, v in self.data if u == node}
def slice(self, node):
"""The backward slice: every node from which node is reachable."""
into = {}
for x, y, _ in self.control:
into.setdefault(y, []).append(x)
for d, u, _ in self.data:
into.setdefault(u, []).append(d)
seen, stack = {node}, [node] # @line L15
while stack: # @line L16
z = stack.pop() # @line L17
for x in into.get(z, ()): # @line L18
if x not in seen:
seen.add(x)
stack.append(x)
return seen # @line L19
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_program_dependence_graph.py 249 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/program-dependence-graph/. The authors are listed in prov/AK2XM4.jsonl.
import random
import toyir
from program_dependence_graph import (
ENTRY,
EXIT,
PDG,
START,
augmented_cfg,
block_control_dependences,
control_dependences,
data_dependences,
)
ODD_SUM = """
B1:
i = 0
s = 0
jump B2
B2:
t1 = i < n
br t1 B3 B6
B3:
t2 = i % 2
br t2 B4 B5
B4:
s = s + i
jump B5
B5:
i = i + 1
jump B2
B6:
ret s
"""
# ------------------------------------------------------------ brute force
def reaches(succ, a, b, banned):
"""Does a reach b without passing through banned?"""
if a == banned:
return False
seen, stack = {a}, [a]
while stack:
v = stack.pop()
if v == b:
return True
for w in succ[v]:
if w != banned and w not in seen:
seen.add(w)
stack.append(w)
return False
def pdom(succ, exit_node, y, z):
"""y post-dominates z: every path from z to the exit contains y."""
return y == z or not reaches(succ, z, exit_node, y)
def cd_by_paths(nodes, succ, exit_node):
"""Control dependence by the path definition of Ferrante, Ottenstein and
Warren: y is control dependent on x through the edge x -> s if a path
x, s, ..., y exists on which y post-dominates every node after x, and y
does not strictly post-dominate x. The paths are enumerated."""
pd = {(y, z): pdom(succ, exit_node, y, z) for y in nodes for z in nodes}
out = set()
for x in nodes:
for s in succ[x]:
for y in nodes:
if y != x and pd[(y, x)]:
continue # y strictly post-dominates x
def walk(z, seen):
if not pd[(y, z)]:
return False
if z == y:
return True
for w in succ[z]:
if w not in seen and walk(w, seen | {w}):
return True
return False
if walk(s, {s}):
out.add((x, y, s))
return out
def dd_by_paths(prog):
"""Flow dependences by search over instruction positions: the definition
of v at d reaches the use u if some path from just after d to u has no
other definition of v."""
pos = {}
for label, b in prog.blocks.items():
pos[label] = list(b.instrs) + [b.term]
def after(node):
label, i = node
if i < len(pos[label]) - 1:
return [(label, i + 1)]
return [(s, 0) for s in toyir.succs(prog, label)]
def reads(node):
label, i = node
ins = pos[label][i]
return toyir.term_uses(ins) if i == len(pos[label]) - 1 else toyir.uses(ins)
def writes(node):
label, i = node
if i == len(pos[label]) - 1:
return None
return toyir.defs(pos[label][i])
defs = [(ENTRY, p, [(prog.entry, 0)]) for p in prog.params]
for label in prog.blocks:
for i in range(len(pos[label]) - 1):
v = writes((label, i))
if v is not None:
defs.append(((label, i), v, after((label, i))))
out = set()
for d, v, starts in defs:
seen, stack = set(starts), list(starts)
while stack:
n = stack.pop()
if v in reads(n):
out.add((d, n, v))
if writes(n) == v:
continue
for w in after(n):
if w not in seen:
seen.add(w)
stack.append(w)
return out
def random_cfg(rng, n):
"""A random digraph on 0 .. n-1 with entry 0, exit n-1 and a START node
as in the PDG, kept only if every node is reachable and reaches the exit."""
while True:
succ = {v: [] for v in range(n)}
for v in range(n - 1):
k = rng.randint(1, 2)
succ[v] = sorted(set(rng.randrange(n) for _ in range(k)))
nodes = list(range(n)) + [START]
succ[START] = [0, n - 1]
ok = all(reaches(succ, START, v, None) and reaches(succ, v, n - 1, None) for v in range(n))
if ok:
return nodes, succ
# ------------------------------------------------------------ the page example
def test_page_example_control():
prog = toyir.parse(ODD_SUM)
cd = {(x, y) for x, y, s in block_control_dependences(prog)}
assert cd == {
(START, "B1"), (START, "B2"), (START, "B6"),
("B2", "B2"), ("B2", "B3"), ("B2", "B5"),
("B3", "B4"),
}
labelled = {(x, y, s) for x, y, s in block_control_dependences(prog) if x == "B3"}
assert labelled == {("B3", "B4", "B4")}
def test_page_example_data():
prog = toyir.parse(ODD_SUM)
dd = data_dependences(prog)
names = {}
for label, b in prog.blocks.items():
for i, ins in enumerate(b.instrs):
names[(label, i)] = toyir._show_instr(ins)
names[(label, len(b.instrs))] = toyir._show_term(b.term)
names[ENTRY] = "ENTRY"
got = {(names[d], names[u], v) for d, u, v in dd}
assert got == {
("i = 0", "t1 = i < n", "i"),
("i = 0", "t2 = i % 2", "i"),
("i = 0", "s = s + i", "i"),
("i = 0", "i = i + 1", "i"),
("i = i + 1", "t1 = i < n", "i"),
("i = i + 1", "t2 = i % 2", "i"),
("i = i + 1", "s = s + i", "i"),
("i = i + 1", "i = i + 1", "i"),
("ENTRY", "t1 = i < n", "n"),
("t1 = i < n", "br t1 B3 B6", "t1"),
("t2 = i % 2", "br t2 B4 B5", "t2"),
("s = 0", "s = s + i", "s"),
("s = 0", "ret s", "s"),
("s = s + i", "s = s + i", "s"),
("s = s + i", "ret s", "s"),
}
def test_pdg_nodes_and_edges():
prog = toyir.parse(ODD_SUM)
g = PDG(prog)
assert len(g.nodes) == 1 + 3 + 2 + 2 + 2 + 2 + 1
# s = s + i is the first instruction of B4, which depends on the branch of B3.
assert g.control_parents(("B4", 0)) == {(("B3", 1), "B4")}
assert g.control_parents(("B6", 0)) == {(ENTRY, "B1")}
assert g.control_parents(("B2", 1)) == {(ENTRY, "B1"), (("B2", 1), "B3")}
assert g.data_parents(("B4", 0)) == {(("B1", 1), "s"), (("B4", 0), "s"), (("B1", 0), "i"), (("B5", 0), "i")}
def test_slices():
prog = toyir.parse(ODD_SUM)
g = PDG(prog)
everything = set(g.nodes)
jumps = {("B1", 2), ("B4", 1), ("B5", 1)}
assert g.slice(("B6", 0)) == everything - jumps
assert g.slice(("B5", 0)) == {ENTRY, ("B1", 0), ("B5", 0), ("B2", 0), ("B2", 1)}
def test_diamond():
prog = toyir.parse("B0:\n br a B1 B2\nB1:\n x = 1\n jump B3\nB2:\n x = 2\n jump B3\nB3:\n ret x\n")
cd = block_control_dependences(prog)
assert cd == {(START, "B0", "B0"), (START, "B3", "B0"), ("B0", "B1", "B1"), ("B0", "B2", "B2")}
# ------------------------------------------------------------ against brute force
def test_control_dependence_random_cfgs():
rng = random.Random(20261115)
for _ in range(400):
n = rng.randint(2, 7)
nodes, succ = random_cfg(rng, n)
assert control_dependences(nodes, succ, n - 1) == cd_by_paths(nodes, succ, n - 1)
def test_control_dependence_random_programs():
rng = random.Random(7)
for k in range(300):
prog = toyir.random_program(rng, rng.randint(2, 4), rng.randint(1, 8), acyclic=(k % 2 == 0))
nodes, succ = augmented_cfg(prog)
expected = cd_by_paths(nodes, succ, EXIT)
assert block_control_dependences(prog) == expected
assert PDG(prog).block_cd == expected
def test_data_dependence_random_programs():
rng = random.Random(11)
for k in range(300):
prog = toyir.random_program(rng, rng.randint(2, 5), rng.randint(1, 8), acyclic=(k % 3 == 0))
assert data_dependences(prog) == dd_by_paths(prog)
History
Ferrante, Ottenstein and Warren (1987) defined the PDG as a common graph for control and data dependence, computed control dependence from the post-dominator tree, and showed its use for vectorization, code motion and node splitting. Horwitz, Reps and Binkley (1990) built the system dependence graph for slicing across procedures. Cytron et al. (1991) showed that control dependences are the reverse dominance frontiers, with the same algorithm that places phi-functions in SSA form. Later graph IRs, such as the sea of nodes of Click and Paleczny (1995), keep explicit dependence edges and drop the fixed order of a CFG in the same spirit.
References
- 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, the definition of the PDG, control dependence from the post-dominator tree, region nodes, and the uses for vectorization and code motion
- Ron Cytron, Jeanne Ferrante, Barry K. Rosen, Mark N. Wegman and F. Kenneth Zadeck, Efficiently computing static single assignment form and the control dependence graph, ACM Transactions on Programming Languages and Systems 13(4), 1991, pages 451-490, the section on the control dependence graph
- 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 system dependence graph, a PDG per procedure joined by call and parameter edges, and slicing by reachability
- Steven S. Muchnick, Advanced Compiler Design and Implementation, Morgan Kaufmann, 1997, the chapter on dependence analysis and dependence graphs, the section on program dependence graphs
- James Stanier and Des Watson, Intermediate representations in imperative compilers, a survey, ACM Computing Surveys 45(3), 2013, the sections on graph-based intermediate representations and the PDG family
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 | W4 complete |
|
Tag AK2XM4 Edit this page History Report an error Markdown