Algorithm Search⌘K

Problemintro

Reaching definitions

Also called reaching definitions analysis.

For each program point, find the definitions of variables that can reach it along some path without being overwritten.

Reaching definitions is the forward may problem of dataflow analysis. A definition is an instruction that writes a variable, and a definition dd of xx reaches a program point pp if some path in the control flow graph goes from just after dd to pp with no other definition of xx on it. The problem asks, for every basic block, for the set of definitions that reach its start. The answer links each read of a variable to the writes that may have produced its value; these links are the use-def half of def-use chains. Reaching definitions is a gen-kill problem: it is distributive, so the worklist dataflow algorithm computes the meet-over-all-paths solution exactly.

In plain words

Every line that stores a value into a variable is a definition. Pick a line that reads a variable. Which of the stores could have put the value there? Follow the program backward from the read: a store counts if you can get from it to the read without passing another store into the same variable.

The compiler answers this for every block at once. It walks forward through the program. Each block adds its own stores and removes the older stores that they hide. Where paths join, a store survives if it survives on at least one of them. A loop carries stores from the bottom of the loop back to its top, so the walk repeats until nothing new arrives.

The answer may include a store that no real run delivers, but it never misses one that a run does deliver.

Definition

Input. A control flow graph with nn blocks, mm edges and one entry block, whose instructions are in three-address code. Let DD be the set of definitions, the instructions that write a variable, and let ∣D∣|D| be its size.

Output. For every block BB, the set IN[B]⊆D\mathrm{IN}[B] \subseteq D of definitions that reach the start of BB, and the set OUT[B]\mathrm{OUT}[B] that reach its end.

The framework.

property value
direction forward
may or must may: a definition reaches if it reaches along some path
domain LL the subsets of DD
order ⊑\sqsubseteq ⊇\supseteq (a larger set is a weaker claim)
meet ⊓\sqcap ∪\cup
⊤\top and ⊥\bot ⊤=∅\top = \emptyset, ⊥=D\bot = D
boundary value ι\iota OUT[entry]=∅\mathrm{OUT}[\mathrm{entry}] = \emptyset: no definition of the procedure has run yet
start value elsewhere ∅\emptyset (⊤\top)
transfer functions fB(X)=genB∪(X−killB)f_B(X) = gen_B \cup (X - kill_B), monotone and distributive
height hh ∣D∣\lvert D \rvert

This page and the other dataflow pages use the meet convention: ⊤\top is the start value and the answer is the greatest fixed point. In a may problem the order is ⊇\supseteq, so "greatest" means the smallest sets. Here ι\iota happens to equal ⊤\top; the variant with pseudo definitions below has ι≠⊤\iota \ne \top.

Lattice and height. LL is the set of all subsets of DD, and a strict chain ∅⊐{d1}⊐{d1,d2}⊐⋯⊐D\emptyset \sqsupset \{d_1\} \sqsupset \{d_1, d_2\} \sqsupset \cdots \sqsupset D adds one definition per step. So h=∣D∣h = |D|.

Transfer functions. For one instruction dd that defines xx, gen={d}gen = \{d\} and killkill is the set of the other definitions of xx. A block is the composition of its instructions in order; for two steps the composition is gen=gen2∪(gen1−kill2)gen = gen_2 \cup (gen_1 - kill_2) and kill=kill1∪kill2kill = kill_1 \cup kill_2. So genBgen_B is the set of the last definition of each variable that BB writes, and killBkill_B is the set of all other definitions of the variables that BB writes. A block that writes xx twice keeps only the second write in genBgen_B.

Equations.

OUT[entry]=genentry,IN[B]=⋃P∈pred(B)OUT[P],OUT[B]=genB∪(IN[B]−killB).\mathrm{OUT}[\mathrm{entry}] = gen_{\mathrm{entry}}, \qquad \mathrm{IN}[B] = \bigcup_{P \in \mathrm{pred}(B)} \mathrm{OUT}[P], \qquad \mathrm{OUT}[B] = gen_B \cup (\mathrm{IN}[B] - kill_B).

The entry block has IN[entry]=ι=∅\mathrm{IN}[\mathrm{entry}] = \iota = \emptyset, together with the outputs of any predecessors that it has.

Meet over all paths. For a path π=(entry,B1,…,Bk)\pi = (\mathrm{entry}, B_1, \ldots, B_k) that ends just before BkB_k, fπ(∅)f_\pi(\emptyset) is the set of definitions that are the last write of their variable along π\pi. The meet over all such paths is the union, which is the set of definitions that reach the start of BkB_k along some path. This is the exact meaning of "reaches" on the CFG.

The fixed point computed. The worklist dataflow algorithm starts every set at ∅\emptyset, puts ι\iota at the entry, and grows the sets until the equations hold. The result is the maximal fixed-point solution: the smallest sets that satisfy the equations.

Soundness. If a run reaches the start of BB and the last write of xx on that run was dd, then d∈IN[B]d \in \mathrm{IN}[B]. The run follows a CFG path, and on that path dd is the last write of xx, so d∈fπ(∅)⊆MOP[B]d \in f_\pi(\emptyset) \subseteq \mathrm{MOP}[B]. Since gengen and killkill functions are distributive, MFP = MOP when every block is reachable from the entry.

Precision. The answer is exact for CFG paths but not for runs, since some CFG paths are never taken. Two branches on the same unchanged condition c give an example:

entry:
  br c left right
left:
  x = 1
  jump mid
right:
  x = 2
  jump mid
mid:
  br c use other
use:
  y = x
  ret y
other:
  ret c

Both definitions of x reach use, because the CFG has the path through right and then use. No run takes that path: if c is false at the first branch, it is false at the second one too. So the analysis cannot tell that y is always 1.

Cost. With bit vectors of ∣D∣|D| bits, one union or difference costs O(∣D∣/w)O(|D| / w) word operations, where ww is the word size. The worklist algorithm applies at most n(∣D∣+1)n(|D| + 1) transfer functions and does at most m(∣D∣+1)m(|D| + 1) unions, so it runs in O((n+m)∣D∣2/w)O((n + m) |D|^2 / w) time. Processed in reverse postorder, round-robin iteration needs at most d+2d + 2 passes, where dd is the loop-connectedness depth (the Kam-Ullman iteration bound), for a total of O((d+2)(n+m)∣D∣/w)O((d + 2)(n + m) |D| / w). Real programs have small dd.

Variants

  • Pseudo definitions at the entry. Add one pseudo definition δx\delta_x for each variable xx and set ι={δx}\iota = \{\delta_x\}. Then δx\delta_x reaches a read of xx exactly when some path reads xx before writing it. A parameter is fine; any other variable is a possible use before initialization. Here the boundary is not ⊤=∅\top = \emptyset, and starting the entry at ⊤\top would hide every such warning. Nielson, Nielson and Hankin use this form.
  • Instruction level. The same equations with one node per instruction give the answer at every instruction. The usual practice is to solve at block level and then scan each block once.
  • Ambiguous definitions. A store through a pointer or a call may write xx. Such a write generates a definition of xx but does not kill the others, because it might not write xx.
  • Per variable. For a use of xx, only the definitions of xx matter. Splitting DD by variable gives smaller vectors and the same answer.
  • Interprocedural. Across calls, the definitions in the callee and the definitions that reach the call are matched by the interprocedural dataflow analysis and IFDS framework methods.

Examples

The running example of dataflow analysis has seven definitions:

name block instruction
d1d_1 entry i = 0
d2d_2 entry s = 0
d3d_3 head t = i < n
d4d_4 body a = x * 2
d5d_5 body u = i & 1
d6d_6 odd s = s + a
d7d_7 next i = i + 1
entry:
  i = 0
  s = 0
  jump head
head:
  t = i < n
  br t body done
body:
  a = x * 2
  u = i & 1
  br u odd next
odd:
  s = s + a
  jump next
next:
  i = i + 1
  jump head
done:
  ret s

Gen and kill sets, and the solution:

block gengen killkill IN OUT
entry d1,d2d_1, d_2 d6,d7d_6, d_7 none d1,d2d_1, d_2
head d3d_3 none all seven all seven
body d4,d5d_4, d_5 none all seven all seven
odd d6d_6 d2d_2 all seven all but d2d_2
next d7d_7 d1d_1 all seven all but d1d_1
done none none all seven all seven

What the answer says:

  • In head, the read of i sees d1d_1 and d7d_7. Two definitions with different values reach it, so i is not a constant there.
  • In odd, the read of s sees d2d_2 (first odd value) and d6d_6 (an earlier odd value). The read of a sees only d4d_4.
  • In body, a = x * 2 reads only the parameter x, which no definition in the procedure writes. So x * 2 is invariant in the loop and loop-invariant code motion can hoist it.

The worklist in reverse postorder (entry, head, done, body, odd, next) processes 11 blocks: six in the first pass, then head, body, done, odd and next again after d7d_7 comes back along the edge from next to head. It does 13 unions and changes an IN set 11 times. The largest number of changes of one IN set is 3, at next, well below h=7h = 7.

Known algorithms

algorithm time notes
Worklist dataflow algorithm O((n+m)∣D∣2/w)O((n + m) \lvert D \rvert^2 / w) worst case Kildall 1973; the usual choice
Round-robin in reverse postorder O((d+2)(n+m)∣D∣/w)O((d + 2)(n + m) \lvert D \rvert / w) the Kam-Ullman iteration bound for rapid frameworks
One graph search per definition O(∣D∣(n+m))O(\lvert D \rvert (n + m)) see the reduction below
Elimination methods see that page solve by graph reduction instead of iteration; best on reducible graphs
SSA form after SSA construction, each use has exactly one definition phi-functions merge the definitions that reach a join
AlgorithmTimeSpacePropertiesCode
IFDS frameworkO(E D^3) worst · averageO(N D^2 + C D^2) extradeterministiciterative1 language
Worklist dataflow algorithmO((n + m)(h + 1)) worst · averageΘ(n) extradeterministiciterative1 language

Bounds

The output alone can have Θ(n∣D∣)\Theta(n \lvert D \rvert) entries. In a chain of nn blocks where block ii writes its own variable xix_i, every definition reaches every later block, so the answer has n(n−1)/2n(n - 1) / 2 pairs. Any algorithm that lists the sets therefore needs Ω(n∣D∣)\Omega(n \lvert D \rvert) time in the worst case. A search per definition matches this up to the factor (n+m)/n(n + m) / n. The bit-vector algorithms win in practice because one word operation handles ww definitions.

Reductions

  • To graph reachability. Fix a definition dd in block BdB_d with d∈genBdd \in gen_{B_d}. Then d∈IN[B]d \in \mathrm{IN}[B] if and only if the CFG has a path Bd,B1,…,Bk=BB_d, B_1, \ldots, B_k = B with k≥1k \ge 1 in which no inner block B1,…,Bk−1B_1, \ldots, B_{k-1} kills dd. A depth-first search from the successors of BdB_d that enters a killing block but does not leave it finds these blocks. One search per definition solves the problem, so every bit of a gen-kill problem is a graph reachability question.
  • To Datalog. The two rules reach(D, B) :- gen(P, D), edge(P, B). and reach(D, B) :- reach(D, P), not kill(P, D), edge(P, B). compute IN\mathrm{IN}; see Datalog-based program analysis.
  • From uninitialized variables. Possible uses before initialization reduce to reaching definitions with pseudo definitions at the entry, as in Variants.

Applications

  • Def-use and use-def chains. For each read of xx in block BB, the definitions of xx in IN[B]\mathrm{IN}[B] (or the last write before the read in BB) are its use-def chain. Inverting the links gives def-use chains.
  • Constant and copy propagation. If the only definition that reaches a read of x is x = 4, the read can use 4. If it is the copy x = y and y is not written between, copy propagation can read y.
  • Loop-invariant code motion. An operand is invariant in a loop when all its reaching definitions are outside the loop, or it is a constant.
  • Warnings. With pseudo definitions, a read that a pseudo definition reaches is a possible use of an uninitialized variable.
  • Slicing and debugging. Program slicing follows use-def chains backward to find the instructions that can affect a value.

References

  1. Alfred V. Aho, Monica S. Lam, Ravi Sethi and Jeffrey D. Ullman, Compilers, Principles, Techniques, and Tools, second edition, Pearson Addison-Wesley, 2007, Section 9.2.4 (Reaching Definitions, with the gen and kill sets, the equations and the iterative algorithm) and Section 9.6.7 (Speed of Convergence of Iterative Data-Flow Algorithms)
  2. Flemming Nielson, Hanne Riis Nielson and Chris Hankin, Principles of Program Analysis, Springer, 1999, Section 2.1.2 (Reaching Definitions Analysis, stated with a join and with pseudo definitions for the start)
  3. Keith D. Cooper and Linda Torczon, Engineering a Compiler, third edition, Morgan Kaufmann, 2022, Chapter 9 (Data-Flow Analysis), Section 9.2.4 (Other Data-Flow Problems)
  4. Gary A. Kildall, A unified approach to global program optimization, Proceedings of the 1st ACM SIGACT-SIGPLAN Symposium on Principles of Programming Languages (POPL 1973), 194-206, the whole paper (the iterative algorithm on a meet semilattice that solves this and the other bit-vector problems)

Where this leads

About this page

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

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a contract.yaml