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.
4
5package ir
6
7// This file defines algorithms related to dominance.
8
9// Dominator tree construction ----------------------------------------
10//
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
14//
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.
19
20import (
21	"bytes"
22	"fmt"
23	"io"
24	"math/big"
25	"os"
26	"sort"
27)
28
29// Idom returns the block that immediately dominates b:
30// its parent in the dominator tree, if any.
31// The entry node (b.Index==0) does not have a parent.
32//
33func (b *BasicBlock) Idom() *BasicBlock { return b.dom.idom }
34
35// Dominees returns the list of blocks that b immediately dominates:
36// its children in the dominator tree.
37//
38func (b *BasicBlock) Dominees() []*BasicBlock { return b.dom.children }
39
40// Dominates reports whether b dominates c.
41func (b *BasicBlock) Dominates(c *BasicBlock) bool {
42	return b.dom.pre <= c.dom.pre && c.dom.post <= b.dom.post
43}
44
45type byDomPreorder []*BasicBlock
46
47func (a byDomPreorder) Len() int           { return len(a) }
48func (a byDomPreorder) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
49func (a byDomPreorder) Less(i, j int) bool { return a[i].dom.pre < a[j].dom.pre }
50
51// DomPreorder returns a new slice containing the blocks of f in
52// dominator tree preorder.
53//
54func (f *Function) DomPreorder() []*BasicBlock {
55	n := len(f.Blocks)
56	order := make(byDomPreorder, n)
57	copy(order, f.Blocks)
58	sort.Sort(order)
59	return order
60}
61
62// domInfo contains a BasicBlock's dominance information.
63type domInfo struct {
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
67}
68
69// buildDomTree computes the dominator tree of f using the LT algorithm.
70// Precondition: all blocks are reachable (e.g. optimizeBlocks has been run).
71//
72func buildDomTree(fn *Function) {
73	// The step numbers refer to the original LT paper; the
74	// reordering is due to Georgiadis.
75
76	// Clear any previous domInfo.
77	for _, b := range fn.Blocks {
78		b.dom = domInfo{}
79	}
80
81	idoms := make([]*BasicBlock, len(fn.Blocks))
82
83	order := make([]*BasicBlock, 0, len(fn.Blocks))
84	seen := fn.blockset(0)
85	var dfs func(b *BasicBlock)
86	dfs = func(b *BasicBlock) {
87		if !seen.Add(b) {
88			return
89		}
90		for _, succ := range b.Succs {
91			dfs(succ)
92		}
93		if fn.fakeExits.Has(b) {
94			dfs(fn.Exit)
95		}
96		order = append(order, b)
97		b.post = len(order) - 1
98	}
99	dfs(fn.Blocks[0])
100
101	for i := 0; i < len(order)/2; i++ {
102		o := len(order) - i - 1
103		order[i], order[o] = order[o], order[i]
104	}
105
106	idoms[fn.Blocks[0].Index] = fn.Blocks[0]
107	changed := true
108	for changed {
109		changed = false
110		// iterate over all nodes in reverse postorder, except for the
111		// entry node
112		for _, b := range order[1:] {
113			var newIdom *BasicBlock
114			do := func(p *BasicBlock) {
115				if idoms[p.Index] == nil {
116					return
117				}
118				if newIdom == nil {
119					newIdom = p
120				} else {
121					finger1 := p
122					finger2 := newIdom
123					for finger1 != finger2 {
124						for finger1.post < finger2.post {
125							finger1 = idoms[finger1.Index]
126						}
127						for finger2.post < finger1.post {
128							finger2 = idoms[finger2.Index]
129						}
130					}
131					newIdom = finger1
132				}
133			}
134			for _, p := range b.Preds {
135				do(p)
136			}
137			if b == fn.Exit {
138				for _, p := range fn.Blocks {
139					if fn.fakeExits.Has(p) {
140						do(p)
141					}
142				}
143			}
144
145			if idoms[b.Index] != newIdom {
146				idoms[b.Index] = newIdom
147				changed = true
148			}
149		}
150	}
151
152	for i, b := range idoms {
153		fn.Blocks[i].dom.idom = b
154		if b == nil {
155			// malformed CFG
156			continue
157		}
158		if i == b.Index {
159			continue
160		}
161		b.dom.children = append(b.dom.children, fn.Blocks[i])
162	}
163
164	numberDomTree(fn.Blocks[0], 0, 0)
165
166	// printDomTreeDot(os.Stderr, fn) // debugging
167	// printDomTreeText(os.Stderr, root, 0) // debugging
168
169	if fn.Prog.mode&SanityCheckFunctions != 0 {
170		sanityCheckDomTree(fn)
171	}
172}
173
174// buildPostDomTree is like buildDomTree, but builds the post-dominator tree instead.
175func buildPostDomTree(fn *Function) {
176	// The step numbers refer to the original LT paper; the
177	// reordering is due to Georgiadis.
178
179	// Clear any previous domInfo.
180	for _, b := range fn.Blocks {
181		b.pdom = domInfo{}
182	}
183
184	idoms := make([]*BasicBlock, len(fn.Blocks))
185
186	order := make([]*BasicBlock, 0, len(fn.Blocks))
187	seen := fn.blockset(0)
188	var dfs func(b *BasicBlock)
189	dfs = func(b *BasicBlock) {
190		if !seen.Add(b) {
191			return
192		}
193		for _, pred := range b.Preds {
194			dfs(pred)
195		}
196		if b == fn.Exit {
197			for _, p := range fn.Blocks {
198				if fn.fakeExits.Has(p) {
199					dfs(p)
200				}
201			}
202		}
203		order = append(order, b)
204		b.post = len(order) - 1
205	}
206	dfs(fn.Exit)
207
208	for i := 0; i < len(order)/2; i++ {
209		o := len(order) - i - 1
210		order[i], order[o] = order[o], order[i]
211	}
212
213	idoms[fn.Exit.Index] = fn.Exit
214	changed := true
215	for changed {
216		changed = false
217		// iterate over all nodes in reverse postorder, except for the
218		// exit node
219		for _, b := range order[1:] {
220			var newIdom *BasicBlock
221			do := func(p *BasicBlock) {
222				if idoms[p.Index] == nil {
223					return
224				}
225				if newIdom == nil {
226					newIdom = p
227				} else {
228					finger1 := p
229					finger2 := newIdom
230					for finger1 != finger2 {
231						for finger1.post < finger2.post {
232							finger1 = idoms[finger1.Index]
233						}
234						for finger2.post < finger1.post {
235							finger2 = idoms[finger2.Index]
236						}
237					}
238					newIdom = finger1
239				}
240			}
241			for _, p := range b.Succs {
242				do(p)
243			}
244			if fn.fakeExits.Has(b) {
245				do(fn.Exit)
246			}
247
248			if idoms[b.Index] != newIdom {
249				idoms[b.Index] = newIdom
250				changed = true
251			}
252		}
253	}
254
255	for i, b := range idoms {
256		fn.Blocks[i].pdom.idom = b
257		if b == nil {
258			// malformed CFG
259			continue
260		}
261		if i == b.Index {
262			continue
263		}
264		b.pdom.children = append(b.pdom.children, fn.Blocks[i])
265	}
266
267	numberPostDomTree(fn.Exit, 0, 0)
268
269	// printPostDomTreeDot(os.Stderr, fn) // debugging
270	// printPostDomTreeText(os.Stderr, fn.Exit, 0) // debugging
271
272	if fn.Prog.mode&SanityCheckFunctions != 0 { // XXX
273		sanityCheckDomTree(fn) // XXX
274	}
275}
276
277// numberDomTree sets the pre- and post-order numbers of a depth-first
278// traversal of the dominator tree rooted at v.  These are used to
279// answer dominance queries in constant time.
280//
281func numberDomTree(v *BasicBlock, pre, post int32) (int32, int32) {
282	v.dom.pre = pre
283	pre++
284	for _, child := range v.dom.children {
285		pre, post = numberDomTree(child, pre, post)
286	}
287	v.dom.post = post
288	post++
289	return pre, post
290}
291
292// numberPostDomTree sets the pre- and post-order numbers of a depth-first
293// traversal of the post-dominator tree rooted at v.  These are used to
294// answer post-dominance queries in constant time.
295//
296func numberPostDomTree(v *BasicBlock, pre, post int32) (int32, int32) {
297	v.pdom.pre = pre
298	pre++
299	for _, child := range v.pdom.children {
300		pre, post = numberPostDomTree(child, pre, post)
301	}
302	v.pdom.post = post
303	post++
304	return pre, post
305}
306
307// Testing utilities ----------------------------------------
308
309// sanityCheckDomTree checks the correctness of the dominator tree
310// computed by the LT algorithm by comparing against the dominance
311// relation computed by a naive Kildall-style forward dataflow
312// analysis (Algorithm 10.16 from the "Dragon" book).
313//
314func sanityCheckDomTree(f *Function) {
315	n := len(f.Blocks)
316
317	// D[i] is the set of blocks that dominate f.Blocks[i],
318	// represented as a bit-set of block indices.
319	D := make([]big.Int, n)
320
321	one := big.NewInt(1)
322
323	// all is the set of all blocks; constant.
324	var all big.Int
325	all.Set(one).Lsh(&all, uint(n)).Sub(&all, one)
326
327	// Initialization.
328	for i := range f.Blocks {
329		if i == 0 {
330			// A root is dominated only by itself.
331			D[i].SetBit(&D[0], 0, 1)
332		} else {
333			// All other blocks are (initially) dominated
334			// by every block.
335			D[i].Set(&all)
336		}
337	}
338
339	// Iteration until fixed point.
340	for changed := true; changed; {
341		changed = false
342		for i, b := range f.Blocks {
343			if i == 0 {
344				continue
345			}
346			// Compute intersection across predecessors.
347			var x big.Int
348			x.Set(&all)
349			for _, pred := range b.Preds {
350				x.And(&x, &D[pred.Index])
351			}
352			if b == f.Exit {
353				for _, p := range f.Blocks {
354					if f.fakeExits.Has(p) {
355						x.And(&x, &D[p.Index])
356					}
357				}
358			}
359			x.SetBit(&x, i, 1) // a block always dominates itself.
360			if D[i].Cmp(&x) != 0 {
361				D[i].Set(&x)
362				changed = true
363			}
364		}
365	}
366
367	// Check the entire relation.  O(n^2).
368	ok := true
369	for i := 0; i < n; i++ {
370		for j := 0; j < n; j++ {
371			b, c := f.Blocks[i], f.Blocks[j]
372			actual := b.Dominates(c)
373			expected := D[j].Bit(i) == 1
374			if actual != expected {
375				fmt.Fprintf(os.Stderr, "dominates(%s, %s)==%t, want %t\n", b, c, actual, expected)
376				ok = false
377			}
378		}
379	}
380
381	preorder := f.DomPreorder()
382	for _, b := range f.Blocks {
383		if got := preorder[b.dom.pre]; got != b {
384			fmt.Fprintf(os.Stderr, "preorder[%d]==%s, want %s\n", b.dom.pre, got, b)
385			ok = false
386		}
387	}
388
389	if !ok {
390		panic("sanityCheckDomTree failed for " + f.String())
391	}
392
393}
394
395// Printing functions ----------------------------------------
396
397// printDomTree prints the dominator tree as text, using indentation.
398//lint:ignore U1000 used during debugging
399func printDomTreeText(buf *bytes.Buffer, v *BasicBlock, indent int) {
400	fmt.Fprintf(buf, "%*s%s\n", 4*indent, "", v)
401	for _, child := range v.dom.children {
402		printDomTreeText(buf, child, indent+1)
403	}
404}
405
406// printDomTreeDot prints the dominator tree of f in AT&T GraphViz
407// (.dot) format.
408//lint:ignore U1000 used during debugging
409func printDomTreeDot(buf io.Writer, f *Function) {
410	fmt.Fprintln(buf, "//", f)
411	fmt.Fprintln(buf, "digraph domtree {")
412	for i, b := range f.Blocks {
413		v := b.dom
414		fmt.Fprintf(buf, "\tn%d [label=\"%s (%d, %d)\",shape=\"rectangle\"];\n", v.pre, b, v.pre, v.post)
415		// TODO(adonovan): improve appearance of edges
416		// belonging to both dominator tree and CFG.
417
418		// Dominator tree edge.
419		if i != 0 {
420			fmt.Fprintf(buf, "\tn%d -> n%d [style=\"solid\",weight=100];\n", v.idom.dom.pre, v.pre)
421		}
422		// CFG edges.
423		for _, pred := range b.Preds {
424			fmt.Fprintf(buf, "\tn%d -> n%d [style=\"dotted\",weight=0];\n", pred.dom.pre, v.pre)
425		}
426	}
427	fmt.Fprintln(buf, "}")
428}
429
430// printDomTree prints the dominator tree as text, using indentation.
431//lint:ignore U1000 used during debugging
432func printPostDomTreeText(buf io.Writer, v *BasicBlock, indent int) {
433	fmt.Fprintf(buf, "%*s%s\n", 4*indent, "", v)
434	for _, child := range v.pdom.children {
435		printPostDomTreeText(buf, child, indent+1)
436	}
437}
438
439// printDomTreeDot prints the dominator tree of f in AT&T GraphViz
440// (.dot) format.
441//lint:ignore U1000 used during debugging
442func printPostDomTreeDot(buf io.Writer, f *Function) {
443	fmt.Fprintln(buf, "//", f)
444	fmt.Fprintln(buf, "digraph pdomtree {")
445	for _, b := range f.Blocks {
446		v := b.pdom
447		fmt.Fprintf(buf, "\tn%d [label=\"%s (%d, %d)\",shape=\"rectangle\"];\n", v.pre, b, v.pre, v.post)
448		// TODO(adonovan): improve appearance of edges
449		// belonging to both dominator tree and CFG.
450
451		// Dominator tree edge.
452		if b != f.Exit {
453			fmt.Fprintf(buf, "\tn%d -> n%d [style=\"solid\",weight=100];\n", v.idom.pdom.pre, v.pre)
454		}
455		// CFG edges.
456		for _, pred := range b.Preds {
457			fmt.Fprintf(buf, "\tn%d -> n%d [style=\"dotted\",weight=0];\n", pred.pdom.pre, v.pre)
458		}
459	}
460	fmt.Fprintln(buf, "}")
461}
462