You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

341 lines
9.3 KiB

  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. package ssa
  5. // This file defines algorithms related to dominance.
  6. // Dominator tree construction ----------------------------------------
  7. //
  8. // We use the algorithm described in Lengauer & Tarjan. 1979. A fast
  9. // algorithm for finding dominators in a flowgraph.
  10. // http://doi.acm.org/10.1145/357062.357071
  11. //
  12. // We also apply the optimizations to SLT described in Georgiadis et
  13. // al, Finding Dominators in Practice, JGAA 2006,
  14. // http://jgaa.info/accepted/2006/GeorgiadisTarjanWerneck2006.10.1.pdf
  15. // to avoid the need for buckets of size > 1.
  16. import (
  17. "bytes"
  18. "fmt"
  19. "math/big"
  20. "os"
  21. "sort"
  22. )
  23. // Idom returns the block that immediately dominates b:
  24. // its parent in the dominator tree, if any.
  25. // Neither the entry node (b.Index==0) nor recover node
  26. // (b==b.Parent().Recover()) have a parent.
  27. //
  28. func (b *BasicBlock) Idom() *BasicBlock { return b.dom.idom }
  29. // Dominees returns the list of blocks that b immediately dominates:
  30. // its children in the dominator tree.
  31. //
  32. func (b *BasicBlock) Dominees() []*BasicBlock { return b.dom.children }
  33. // Dominates reports whether b dominates c.
  34. func (b *BasicBlock) Dominates(c *BasicBlock) bool {
  35. return b.dom.pre <= c.dom.pre && c.dom.post <= b.dom.post
  36. }
  37. type byDomPreorder []*BasicBlock
  38. func (a byDomPreorder) Len() int { return len(a) }
  39. func (a byDomPreorder) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  40. func (a byDomPreorder) Less(i, j int) bool { return a[i].dom.pre < a[j].dom.pre }
  41. // DomPreorder returns a new slice containing the blocks of f in
  42. // dominator tree preorder.
  43. //
  44. func (f *Function) DomPreorder() []*BasicBlock {
  45. n := len(f.Blocks)
  46. order := make(byDomPreorder, n, n)
  47. copy(order, f.Blocks)
  48. sort.Sort(order)
  49. return order
  50. }
  51. // domInfo contains a BasicBlock's dominance information.
  52. type domInfo struct {
  53. idom *BasicBlock // immediate dominator (parent in domtree)
  54. children []*BasicBlock // nodes immediately dominated by this one
  55. pre, post int32 // pre- and post-order numbering within domtree
  56. }
  57. // ltState holds the working state for Lengauer-Tarjan algorithm
  58. // (during which domInfo.pre is repurposed for CFG DFS preorder number).
  59. type ltState struct {
  60. // Each slice is indexed by b.Index.
  61. sdom []*BasicBlock // b's semidominator
  62. parent []*BasicBlock // b's parent in DFS traversal of CFG
  63. ancestor []*BasicBlock // b's ancestor with least sdom
  64. }
  65. // dfs implements the depth-first search part of the LT algorithm.
  66. func (lt *ltState) dfs(v *BasicBlock, i int32, preorder []*BasicBlock) int32 {
  67. preorder[i] = v
  68. v.dom.pre = i // For now: DFS preorder of spanning tree of CFG
  69. i++
  70. lt.sdom[v.Index] = v
  71. lt.link(nil, v)
  72. for _, w := range v.Succs {
  73. if lt.sdom[w.Index] == nil {
  74. lt.parent[w.Index] = v
  75. i = lt.dfs(w, i, preorder)
  76. }
  77. }
  78. return i
  79. }
  80. // eval implements the EVAL part of the LT algorithm.
  81. func (lt *ltState) eval(v *BasicBlock) *BasicBlock {
  82. // TODO(adonovan): opt: do path compression per simple LT.
  83. u := v
  84. for ; lt.ancestor[v.Index] != nil; v = lt.ancestor[v.Index] {
  85. if lt.sdom[v.Index].dom.pre < lt.sdom[u.Index].dom.pre {
  86. u = v
  87. }
  88. }
  89. return u
  90. }
  91. // link implements the LINK part of the LT algorithm.
  92. func (lt *ltState) link(v, w *BasicBlock) {
  93. lt.ancestor[w.Index] = v
  94. }
  95. // buildDomTree computes the dominator tree of f using the LT algorithm.
  96. // Precondition: all blocks are reachable (e.g. optimizeBlocks has been run).
  97. //
  98. func buildDomTree(f *Function) {
  99. // The step numbers refer to the original LT paper; the
  100. // reordering is due to Georgiadis.
  101. // Clear any previous domInfo.
  102. for _, b := range f.Blocks {
  103. b.dom = domInfo{}
  104. }
  105. n := len(f.Blocks)
  106. // Allocate space for 5 contiguous [n]*BasicBlock arrays:
  107. // sdom, parent, ancestor, preorder, buckets.
  108. space := make([]*BasicBlock, 5*n, 5*n)
  109. lt := ltState{
  110. sdom: space[0:n],
  111. parent: space[n : 2*n],
  112. ancestor: space[2*n : 3*n],
  113. }
  114. // Step 1. Number vertices by depth-first preorder.
  115. preorder := space[3*n : 4*n]
  116. root := f.Blocks[0]
  117. prenum := lt.dfs(root, 0, preorder)
  118. recover := f.Recover
  119. if recover != nil {
  120. lt.dfs(recover, prenum, preorder)
  121. }
  122. buckets := space[4*n : 5*n]
  123. copy(buckets, preorder)
  124. // In reverse preorder...
  125. for i := int32(n) - 1; i > 0; i-- {
  126. w := preorder[i]
  127. // Step 3. Implicitly define the immediate dominator of each node.
  128. for v := buckets[i]; v != w; v = buckets[v.dom.pre] {
  129. u := lt.eval(v)
  130. if lt.sdom[u.Index].dom.pre < i {
  131. v.dom.idom = u
  132. } else {
  133. v.dom.idom = w
  134. }
  135. }
  136. // Step 2. Compute the semidominators of all nodes.
  137. lt.sdom[w.Index] = lt.parent[w.Index]
  138. for _, v := range w.Preds {
  139. u := lt.eval(v)
  140. if lt.sdom[u.Index].dom.pre < lt.sdom[w.Index].dom.pre {
  141. lt.sdom[w.Index] = lt.sdom[u.Index]
  142. }
  143. }
  144. lt.link(lt.parent[w.Index], w)
  145. if lt.parent[w.Index] == lt.sdom[w.Index] {
  146. w.dom.idom = lt.parent[w.Index]
  147. } else {
  148. buckets[i] = buckets[lt.sdom[w.Index].dom.pre]
  149. buckets[lt.sdom[w.Index].dom.pre] = w
  150. }
  151. }
  152. // The final 'Step 3' is now outside the loop.
  153. for v := buckets[0]; v != root; v = buckets[v.dom.pre] {
  154. v.dom.idom = root
  155. }
  156. // Step 4. Explicitly define the immediate dominator of each
  157. // node, in preorder.
  158. for _, w := range preorder[1:] {
  159. if w == root || w == recover {
  160. w.dom.idom = nil
  161. } else {
  162. if w.dom.idom != lt.sdom[w.Index] {
  163. w.dom.idom = w.dom.idom.dom.idom
  164. }
  165. // Calculate Children relation as inverse of Idom.
  166. w.dom.idom.dom.children = append(w.dom.idom.dom.children, w)
  167. }
  168. }
  169. pre, post := numberDomTree(root, 0, 0)
  170. if recover != nil {
  171. numberDomTree(recover, pre, post)
  172. }
  173. // printDomTreeDot(os.Stderr, f) // debugging
  174. // printDomTreeText(os.Stderr, root, 0) // debugging
  175. if f.Prog.mode&SanityCheckFunctions != 0 {
  176. sanityCheckDomTree(f)
  177. }
  178. }
  179. // numberDomTree sets the pre- and post-order numbers of a depth-first
  180. // traversal of the dominator tree rooted at v. These are used to
  181. // answer dominance queries in constant time.
  182. //
  183. func numberDomTree(v *BasicBlock, pre, post int32) (int32, int32) {
  184. v.dom.pre = pre
  185. pre++
  186. for _, child := range v.dom.children {
  187. pre, post = numberDomTree(child, pre, post)
  188. }
  189. v.dom.post = post
  190. post++
  191. return pre, post
  192. }
  193. // Testing utilities ----------------------------------------
  194. // sanityCheckDomTree checks the correctness of the dominator tree
  195. // computed by the LT algorithm by comparing against the dominance
  196. // relation computed by a naive Kildall-style forward dataflow
  197. // analysis (Algorithm 10.16 from the "Dragon" book).
  198. //
  199. func sanityCheckDomTree(f *Function) {
  200. n := len(f.Blocks)
  201. // D[i] is the set of blocks that dominate f.Blocks[i],
  202. // represented as a bit-set of block indices.
  203. D := make([]big.Int, n)
  204. one := big.NewInt(1)
  205. // all is the set of all blocks; constant.
  206. var all big.Int
  207. all.Set(one).Lsh(&all, uint(n)).Sub(&all, one)
  208. // Initialization.
  209. for i, b := range f.Blocks {
  210. if i == 0 || b == f.Recover {
  211. // A root is dominated only by itself.
  212. D[i].SetBit(&D[0], 0, 1)
  213. } else {
  214. // All other blocks are (initially) dominated
  215. // by every block.
  216. D[i].Set(&all)
  217. }
  218. }
  219. // Iteration until fixed point.
  220. for changed := true; changed; {
  221. changed = false
  222. for i, b := range f.Blocks {
  223. if i == 0 || b == f.Recover {
  224. continue
  225. }
  226. // Compute intersection across predecessors.
  227. var x big.Int
  228. x.Set(&all)
  229. for _, pred := range b.Preds {
  230. x.And(&x, &D[pred.Index])
  231. }
  232. x.SetBit(&x, i, 1) // a block always dominates itself.
  233. if D[i].Cmp(&x) != 0 {
  234. D[i].Set(&x)
  235. changed = true
  236. }
  237. }
  238. }
  239. // Check the entire relation. O(n^2).
  240. // The Recover block (if any) must be treated specially so we skip it.
  241. ok := true
  242. for i := 0; i < n; i++ {
  243. for j := 0; j < n; j++ {
  244. b, c := f.Blocks[i], f.Blocks[j]
  245. if c == f.Recover {
  246. continue
  247. }
  248. actual := b.Dominates(c)
  249. expected := D[j].Bit(i) == 1
  250. if actual != expected {
  251. fmt.Fprintf(os.Stderr, "dominates(%s, %s)==%t, want %t\n", b, c, actual, expected)
  252. ok = false
  253. }
  254. }
  255. }
  256. preorder := f.DomPreorder()
  257. for _, b := range f.Blocks {
  258. if got := preorder[b.dom.pre]; got != b {
  259. fmt.Fprintf(os.Stderr, "preorder[%d]==%s, want %s\n", b.dom.pre, got, b)
  260. ok = false
  261. }
  262. }
  263. if !ok {
  264. panic("sanityCheckDomTree failed for " + f.String())
  265. }
  266. }
  267. // Printing functions ----------------------------------------
  268. // printDomTree prints the dominator tree as text, using indentation.
  269. func printDomTreeText(buf *bytes.Buffer, v *BasicBlock, indent int) {
  270. fmt.Fprintf(buf, "%*s%s\n", 4*indent, "", v)
  271. for _, child := range v.dom.children {
  272. printDomTreeText(buf, child, indent+1)
  273. }
  274. }
  275. // printDomTreeDot prints the dominator tree of f in AT&T GraphViz
  276. // (.dot) format.
  277. func printDomTreeDot(buf *bytes.Buffer, f *Function) {
  278. fmt.Fprintln(buf, "//", f)
  279. fmt.Fprintln(buf, "digraph domtree {")
  280. for i, b := range f.Blocks {
  281. v := b.dom
  282. fmt.Fprintf(buf, "\tn%d [label=\"%s (%d, %d)\",shape=\"rectangle\"];\n", v.pre, b, v.pre, v.post)
  283. // TODO(adonovan): improve appearance of edges
  284. // belonging to both dominator tree and CFG.
  285. // Dominator tree edge.
  286. if i != 0 {
  287. fmt.Fprintf(buf, "\tn%d -> n%d [style=\"solid\",weight=100];\n", v.idom.dom.pre, v.pre)
  288. }
  289. // CFG edges.
  290. for _, pred := range b.Preds {
  291. fmt.Fprintf(buf, "\tn%d -> n%d [style=\"dotted\",weight=0];\n", pred.dom.pre, v.pre)
  292. }
  293. }
  294. fmt.Fprintln(buf, "}")
  295. }