1 // Copyright 2013 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
7 // This file defines algorithms related to dominance.
9 // Dominator tree construction ----------------------------------------
11 // We use the algorithm described in Lengauer & Tarjan. 1979. A fast
12 // algorithm for finding dominators in a flowgraph.
13 // http://doi.acm.org/10.1145/357062.357071
15 // We also apply the optimizations to SLT described in Georgiadis et
16 // al, Finding Dominators in Practice, JGAA 2006,
17 // http://jgaa.info/accepted/2006/GeorgiadisTarjanWerneck2006.10.1.pdf
18 // to avoid the need for buckets of size > 1.
28 // Idom returns the block that immediately dominates b:
29 // its parent in the dominator tree, if any.
30 // Neither the entry node (b.Index==0) nor recover node
31 // (b==b.Parent().Recover()) have a parent.
33 func (b *BasicBlock) Idom() *BasicBlock { return b.dom.idom }
35 // Dominees returns the list of blocks that b immediately dominates:
36 // its children in the dominator tree.
38 func (b *BasicBlock) Dominees() []*BasicBlock { return b.dom.children }
40 // Dominates reports whether b dominates c.
41 func (b *BasicBlock) Dominates(c *BasicBlock) bool {
42 return b.dom.pre <= c.dom.pre && c.dom.post <= b.dom.post
45 type byDomPreorder []*BasicBlock
47 func (a byDomPreorder) Len() int { return len(a) }
48 func (a byDomPreorder) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
49 func (a byDomPreorder) Less(i, j int) bool { return a[i].dom.pre < a[j].dom.pre }
51 // DomPreorder returns a new slice containing the blocks of f in
52 // dominator tree preorder.
54 func (f *Function) DomPreorder() []*BasicBlock {
56 order := make(byDomPreorder, n)
62 // domInfo contains a BasicBlock's dominance information.
64 idom *BasicBlock // immediate dominator (parent in domtree)
65 children []*BasicBlock // nodes immediately dominated by this one
66 pre, post int32 // pre- and post-order numbering within domtree
69 // ltState holds the working state for Lengauer-Tarjan algorithm
70 // (during which domInfo.pre is repurposed for CFG DFS preorder number).
72 // Each slice is indexed by b.Index.
73 sdom []*BasicBlock // b's semidominator
74 parent []*BasicBlock // b's parent in DFS traversal of CFG
75 ancestor []*BasicBlock // b's ancestor with least sdom
78 // dfs implements the depth-first search part of the LT algorithm.
79 func (lt *ltState) dfs(v *BasicBlock, i int32, preorder []*BasicBlock) int32 {
81 v.dom.pre = i // For now: DFS preorder of spanning tree of CFG
85 for _, w := range v.Succs {
86 if lt.sdom[w.Index] == nil {
87 lt.parent[w.Index] = v
88 i = lt.dfs(w, i, preorder)
94 // eval implements the EVAL part of the LT algorithm.
95 func (lt *ltState) eval(v *BasicBlock) *BasicBlock {
96 // TODO(adonovan): opt: do path compression per simple LT.
98 for ; lt.ancestor[v.Index] != nil; v = lt.ancestor[v.Index] {
99 if lt.sdom[v.Index].dom.pre < lt.sdom[u.Index].dom.pre {
106 // link implements the LINK part of the LT algorithm.
107 func (lt *ltState) link(v, w *BasicBlock) {
108 lt.ancestor[w.Index] = v
111 // buildDomTree computes the dominator tree of f using the LT algorithm.
112 // Precondition: all blocks are reachable (e.g. optimizeBlocks has been run).
114 func buildDomTree(f *Function) {
115 // The step numbers refer to the original LT paper; the
116 // reordering is due to Georgiadis.
118 // Clear any previous domInfo.
119 for _, b := range f.Blocks {
124 // Allocate space for 5 contiguous [n]*BasicBlock arrays:
125 // sdom, parent, ancestor, preorder, buckets.
126 space := make([]*BasicBlock, 5*n)
129 parent: space[n : 2*n],
130 ancestor: space[2*n : 3*n],
133 // Step 1. Number vertices by depth-first preorder.
134 preorder := space[3*n : 4*n]
136 prenum := lt.dfs(root, 0, preorder)
139 lt.dfs(recover, prenum, preorder)
142 buckets := space[4*n : 5*n]
143 copy(buckets, preorder)
145 // In reverse preorder...
146 for i := int32(n) - 1; i > 0; i-- {
149 // Step 3. Implicitly define the immediate dominator of each node.
150 for v := buckets[i]; v != w; v = buckets[v.dom.pre] {
152 if lt.sdom[u.Index].dom.pre < i {
159 // Step 2. Compute the semidominators of all nodes.
160 lt.sdom[w.Index] = lt.parent[w.Index]
161 for _, v := range w.Preds {
163 if lt.sdom[u.Index].dom.pre < lt.sdom[w.Index].dom.pre {
164 lt.sdom[w.Index] = lt.sdom[u.Index]
168 lt.link(lt.parent[w.Index], w)
170 if lt.parent[w.Index] == lt.sdom[w.Index] {
171 w.dom.idom = lt.parent[w.Index]
173 buckets[i] = buckets[lt.sdom[w.Index].dom.pre]
174 buckets[lt.sdom[w.Index].dom.pre] = w
178 // The final 'Step 3' is now outside the loop.
179 for v := buckets[0]; v != root; v = buckets[v.dom.pre] {
183 // Step 4. Explicitly define the immediate dominator of each
184 // node, in preorder.
185 for _, w := range preorder[1:] {
186 if w == root || w == recover {
189 if w.dom.idom != lt.sdom[w.Index] {
190 w.dom.idom = w.dom.idom.dom.idom
192 // Calculate Children relation as inverse of Idom.
193 w.dom.idom.dom.children = append(w.dom.idom.dom.children, w)
197 pre, post := numberDomTree(root, 0, 0)
199 numberDomTree(recover, pre, post)
202 // printDomTreeDot(os.Stderr, f) // debugging
203 // printDomTreeText(os.Stderr, root, 0) // debugging
205 if f.Prog.mode&SanityCheckFunctions != 0 {
206 sanityCheckDomTree(f)
210 // numberDomTree sets the pre- and post-order numbers of a depth-first
211 // traversal of the dominator tree rooted at v. These are used to
212 // answer dominance queries in constant time.
214 func numberDomTree(v *BasicBlock, pre, post int32) (int32, int32) {
217 for _, child := range v.dom.children {
218 pre, post = numberDomTree(child, pre, post)
225 // Testing utilities ----------------------------------------
227 // sanityCheckDomTree checks the correctness of the dominator tree
228 // computed by the LT algorithm by comparing against the dominance
229 // relation computed by a naive Kildall-style forward dataflow
230 // analysis (Algorithm 10.16 from the "Dragon" book).
232 func sanityCheckDomTree(f *Function) {
235 // D[i] is the set of blocks that dominate f.Blocks[i],
236 // represented as a bit-set of block indices.
237 D := make([]big.Int, n)
241 // all is the set of all blocks; constant.
243 all.Set(one).Lsh(&all, uint(n)).Sub(&all, one)
246 for i, b := range f.Blocks {
247 if i == 0 || b == f.Recover {
248 // A root is dominated only by itself.
249 D[i].SetBit(&D[0], 0, 1)
251 // All other blocks are (initially) dominated
257 // Iteration until fixed point.
258 for changed := true; changed; {
260 for i, b := range f.Blocks {
261 if i == 0 || b == f.Recover {
264 // Compute intersection across predecessors.
267 for _, pred := range b.Preds {
268 x.And(&x, &D[pred.Index])
270 x.SetBit(&x, i, 1) // a block always dominates itself.
271 if D[i].Cmp(&x) != 0 {
278 // Check the entire relation. O(n^2).
279 // The Recover block (if any) must be treated specially so we skip it.
281 for i := 0; i < n; i++ {
282 for j := 0; j < n; j++ {
283 b, c := f.Blocks[i], f.Blocks[j]
287 actual := b.Dominates(c)
288 expected := D[j].Bit(i) == 1
289 if actual != expected {
290 fmt.Fprintf(os.Stderr, "dominates(%s, %s)==%t, want %t\n", b, c, actual, expected)
296 preorder := f.DomPreorder()
297 for _, b := range f.Blocks {
298 if got := preorder[b.dom.pre]; got != b {
299 fmt.Fprintf(os.Stderr, "preorder[%d]==%s, want %s\n", b.dom.pre, got, b)
305 panic("sanityCheckDomTree failed for " + f.String())
310 // Printing functions ----------------------------------------
312 // printDomTree prints the dominator tree as text, using indentation.
313 func printDomTreeText(buf *bytes.Buffer, v *BasicBlock, indent int) {
314 fmt.Fprintf(buf, "%*s%s\n", 4*indent, "", v)
315 for _, child := range v.dom.children {
316 printDomTreeText(buf, child, indent+1)
320 // printDomTreeDot prints the dominator tree of f in AT&T GraphViz
322 func printDomTreeDot(buf *bytes.Buffer, f *Function) {
323 fmt.Fprintln(buf, "//", f)
324 fmt.Fprintln(buf, "digraph domtree {")
325 for i, b := range f.Blocks {
327 fmt.Fprintf(buf, "\tn%d [label=\"%s (%d, %d)\",shape=\"rectangle\"];\n", v.pre, b, v.pre, v.post)
328 // TODO(adonovan): improve appearance of edges
329 // belonging to both dominator tree and CFG.
331 // Dominator tree edge.
333 fmt.Fprintf(buf, "\tn%d -> n%d [style=\"solid\",weight=100];\n", v.idom.dom.pre, v.pre)
336 for _, pred := range b.Preds {
337 fmt.Fprintf(buf, "\tn%d -> n%d [style=\"dotted\",weight=0];\n", pred.dom.pre, v.pre)
340 fmt.Fprintln(buf, "}")