| 1 | // Copyright 2026 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 | |
| 5 | package flow |
| 6 | |
| 7 | import ( |
| 8 | "container/heap" |
| 9 | "log" |
| 10 | "slices" |
| 11 | |
| 12 | "golang.org/x/tools/internal/graph" |
| 13 | ) |
| 14 | |
| 15 | // Forward performs a forward monotone analysis over a control flow graph. |
| 16 | // |
| 17 | // The entry map provides initial state for entry blocks (blocks with zero |
| 18 | // predecessors). For each edge, it calls transfer(fact, edge), where fact is |
| 19 | // the analysis state on entry to edge.Pred. The transfer function must return |
| 20 | // the outgoing analysis state of the edge (which may be fact, if the edge has |
| 21 | // no effect on the analysis state). |
| 22 | func Forward[L Semilattice[Fact], Fact any, NodeID comparable](g graph.Graph[NodeID], entry map[NodeID]Fact, transfer func(from, to NodeID, fact Fact) Fact) *Analysis[Fact, NodeID] { |
| 23 | cg, nodeMap := graph.Compact(g) |
| 24 | |
| 25 | nNodes := cg.NumNodes() |
| 26 | fb := &fwdBuilder[L, Fact, NodeID]{ |
| 27 | cfg: cg, |
| 28 | nodeMap: nodeMap, |
| 29 | transfer: transfer, |
| 30 | blocks: make([]blockInfo[Fact], nNodes), |
| 31 | } |
| 32 | fb.queue.init(cg) |
| 33 | |
| 34 | // Initialize each node. |
| 35 | totalEdges := 0 |
| 36 | for ni := range nNodes { |
| 37 | b := &fb.blocks[ni] |
| 38 | |
| 39 | // Construct back-edges. |
| 40 | // |
| 41 | // I experimented with making Graph support iterating over in-edges, but |
| 42 | // in practice that just meant each Graph implementation had a copy of |
| 43 | // this logic. So instead we keep Graph as simple as possible and |
| 44 | // compute the auxiliary data in the algorithm. One drawback of this is |
| 45 | // that, for the [Transpose] graph, this information is redundant with |
| 46 | // the underlying graph. We could potentially special-case that. |
| 47 | outs := 0 |
| 48 | for succID := range cg.Out(ni) { |
| 49 | succ := &fb.blocks[succID] |
| 50 | succ.preds = append(succ.preds, blockEdge{ni, outs}) |
| 51 | outs++ |
| 52 | totalEdges++ |
| 53 | } |
| 54 | |
| 55 | // Initialize in & out states. |
| 56 | fact, ok := entry[nodeMap.Value(ni)] |
| 57 | if !ok { |
| 58 | fact = fb.l.Ident() |
| 59 | } |
| 60 | b.in = fact |
| 61 | b.out = slices.Repeat([]Fact{fb.l.Ident()}, outs) |
| 62 | |
| 63 | // Enqueue block. |
| 64 | // |
| 65 | // It's tempting to enqueue only the entry blocks, but this is wrong. |
| 66 | // The entry map may be empty if there are no interesting entry states, |
| 67 | // but the transfer function may still introduce interesting states |
| 68 | // anywhere. |
| 69 | b.dirty = true |
| 70 | fb.queue.enqueue(ni) |
| 71 | } |
| 72 | |
| 73 | // Propagate over blocks. |
| 74 | fb.propagate() |
| 75 | |
| 76 | // Collect the final analysis results. |
| 77 | a := Analysis[Fact, NodeID]{ |
| 78 | nodeMap: nodeMap, |
| 79 | ins: make([]Fact, nNodes), |
| 80 | edges: make([]edgeFact[Fact], 0, totalEdges), |
| 81 | } |
| 82 | for pred := range nNodes { |
| 83 | a.ins[pred] = fb.blocks[pred].in |
| 84 | i := 0 |
| 85 | for succ := range cg.Out(pred) { |
| 86 | edge := edge{pred, succ} |
| 87 | a.edges = append(a.edges, edgeFact[Fact]{edge, fb.blocks[pred].out[i]}) |
| 88 | i++ |
| 89 | } |
| 90 | } |
| 91 | slices.SortFunc(a.edges, func(a, b edgeFact[Fact]) int { return a.edge.compare(b.edge) }) |
| 92 | return &a |
| 93 | } |
| 94 | |
| 95 | // fwdBuilder is the state used during [Forward] analysis. |
| 96 | type fwdBuilder[L Semilattice[Fact], Fact any, NodeID comparable] struct { |
| 97 | l L // Lattice |
| 98 | |
| 99 | cfg graph.Graph[int] // Control flow graph (compact) |
| 100 | nodeMap *graph.Index[NodeID] // Map from cfg to original NodeIDs |
| 101 | |
| 102 | // transfer is the edge transfer function. |
| 103 | transfer func(from, to NodeID, fact Fact) Fact |
| 104 | |
| 105 | blocks []blockInfo[Fact] |
| 106 | |
| 107 | queue nodeHeap |
| 108 | } |
| 109 | |
| 110 | type blockInfo[Fact any] struct { |
| 111 | dirty bool // The in fact has never been propagated. |
| 112 | |
| 113 | preds []blockEdge |
| 114 | |
| 115 | in Fact |
| 116 | out []Fact // Corresponds to i'th out edge |
| 117 | } |
| 118 | |
| 119 | type blockEdge struct { |
| 120 | node int |
| 121 | i int // Out edge index |
| 122 | } |
| 123 | |
| 124 | // nodeHeap implements a heap of NodeIDs, ordered topologically. |
| 125 | // |
| 126 | // We use this ordering so forward analysis converges more quickly. |
| 127 | type nodeHeap struct { |
| 128 | heap []int |
| 129 | inQueue []int64 // Bitmap over node IDs |
| 130 | prio []int // NodeID -> priority |
| 131 | } |
| 132 | |
| 133 | func (h *nodeHeap) init(g graph.Graph[int]) { |
| 134 | nNodes := g.NumNodes() |
| 135 | *h = nodeHeap{ |
| 136 | inQueue: make([]int64, (nNodes+63)/64), |
| 137 | prio: make([]int, nNodes), |
| 138 | } |
| 139 | for p, nid := range graph.ReversePostorder(g) { |
| 140 | h.prio[nid] = p |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | func (h *nodeHeap) enqueue(nid int) { |
| 145 | if h.inQueue[nid/64]&(1<<(nid%64)) != 0 { |
| 146 | return |
| 147 | } |
| 148 | h.inQueue[nid/64] |= 1 << (nid % 64) |
| 149 | heap.Push(h, nid) |
| 150 | } |
| 151 | |
| 152 | func (h *nodeHeap) dequeue() int { |
| 153 | nid := h.heap[0] |
| 154 | heap.Pop(h) |
| 155 | h.inQueue[nid/64] &^= 1 << (nid % 64) |
| 156 | return nid |
| 157 | } |
| 158 | |
| 159 | func (h nodeHeap) Len() int { return len(h.heap) } |
| 160 | func (h nodeHeap) Less(i, j int) bool { return h.prio[h.heap[i]] < h.prio[h.heap[j]] } |
| 161 | func (h nodeHeap) Swap(i, j int) { h.heap[i], h.heap[j] = h.heap[j], h.heap[i] } |
| 162 | func (h *nodeHeap) Push(x any) { h.heap = append(h.heap, x.(int)) } |
| 163 | func (h *nodeHeap) Pop() any { |
| 164 | n := len(h.heap) |
| 165 | x := h.heap[n-1] |
| 166 | h.heap = h.heap[:n-1] |
| 167 | return x |
| 168 | } |
| 169 | |
| 170 | func (fb *fwdBuilder[L, Fact, NodeID]) merge(a, b Fact) Fact { |
| 171 | if fb.l.Equals(a, b) { |
| 172 | return a |
| 173 | } |
| 174 | return fb.l.Merge(a, b) |
| 175 | } |
| 176 | |
| 177 | func (fb *fwdBuilder[L, Fact, NodeID]) propagate() { |
| 178 | for fb.queue.Len() > 0 { |
| 179 | bi := fb.queue.dequeue() |
| 180 | block := &fb.blocks[bi] |
| 181 | |
| 182 | // Merge predecessor facts to compute updated "in" fact. |
| 183 | var in Fact |
| 184 | first := true |
| 185 | for _, edge := range block.preds { |
| 186 | pred := &fb.blocks[edge.node] |
| 187 | var edgeFact Fact |
| 188 | if pred.dirty { |
| 189 | // We haven't visited this predecessor yet, so it doesn't have |
| 190 | // meaningful out facts. |
| 191 | edgeFact = fb.l.Ident() |
| 192 | } else { |
| 193 | edgeFact = pred.out[edge.i] |
| 194 | } |
| 195 | if first { |
| 196 | if debug { |
| 197 | log.Printf("propagate to node %d", bi) |
| 198 | } |
| 199 | in = edgeFact |
| 200 | first = false |
| 201 | } else { |
| 202 | in = fb.merge(in, edgeFact) |
| 203 | } |
| 204 | if debug { |
| 205 | log.Printf(" from node %d: %v", edge.node, edgeFact) |
| 206 | } |
| 207 | } |
| 208 | if first { |
| 209 | // No predecessors. |
| 210 | if debug { |
| 211 | log.Printf("node %d gets initial state", bi) |
| 212 | } |
| 213 | in = block.in |
| 214 | } |
| 215 | |
| 216 | if !block.dirty && fb.l.Equals(in, block.in) { |
| 217 | // No change to block input, which means the transfer function |
| 218 | // results also won't change from the last time we ran it. |
| 219 | if debug { |
| 220 | log.Printf(" initial state unchanged: %v", in) |
| 221 | } |
| 222 | continue |
| 223 | } |
| 224 | if debug { |
| 225 | log.Printf(" new initial state: %v", in) |
| 226 | } |
| 227 | block.in = in |
| 228 | |
| 229 | // Apply transfer function. |
| 230 | predID := fb.nodeMap.Value(bi) |
| 231 | i := 0 |
| 232 | for succNum := range fb.cfg.Out(bi) { |
| 233 | edgeFact := fb.transfer(predID, fb.nodeMap.Value(succNum), in) |
| 234 | if block.dirty || !fb.l.Equals(block.out[i], edgeFact) { |
| 235 | // Out fact changed, so recompute the target block. |
| 236 | if debug { |
| 237 | log.Printf(" to node %d: %v", succNum, edgeFact) |
| 238 | } |
| 239 | block.out[i] = edgeFact |
| 240 | fb.queue.enqueue(succNum) |
| 241 | } else { |
| 242 | if debug { |
| 243 | log.Printf(" to node %d: no change", succNum) |
| 244 | } |
| 245 | } |
| 246 | i++ |
| 247 | } |
| 248 | |
| 249 | block.dirty = false |
| 250 | } |
| 251 | } |