| 1 |
package ir |
| 2 |
|
| 3 |
import ( |
| 4 |
"math" |
| 5 |
) |
| 6 |
|
| 7 |
type sccState struct { |
| 8 |
fn *Function |
| 9 |
index int |
| 10 |
lows BlockMap[int] |
| 11 |
F []int |
| 12 |
sccs []*SCC |
| 13 |
} |
| 14 |
|
| 15 |
func (s *sccState) scc(v *BasicBlock) { |
| 16 |
// This is Tarjan's algorithm, with some optimizations from [1] applied. |
| 17 |
// |
| 18 |
// [1] R. E. Tarjan and U. Zwick, “Finding strong components using depth-first search,” Apr. 11, 2022, arXiv: arXiv:2201.07197. doi: 10.48550/arXiv.2201.07197. |
| 19 |
vi := v.Index |
| 20 |
lows := s.lows |
| 21 |
|
| 22 |
s.index += 2 |
| 23 |
lows[vi] = s.index |
| 24 |
|
| 25 |
for _, w := range v.Succs { |
| 26 |
wi := w.Index |
| 27 |
|
| 28 |
if lows[wi] == 0 { |
| 29 |
s.scc(w) |
| 30 |
} |
| 31 |
|
| 32 |
if lows[wi] < lows[vi] { |
| 33 |
lows[vi] = lows[wi] | 1 |
| 34 |
} |
| 35 |
} |
| 36 |
|
| 37 |
if lows[vi]&1 == 0 { |
| 38 |
leaderLow := lows[vi] |
| 39 |
|
| 40 |
scc := &SCC{ |
| 41 |
Index: len(s.sccs), |
| 42 |
} |
| 43 |
F := s.F |
| 44 |
for lows[F[len(F)-1]] >= leaderLow { |
| 45 |
x := F[len(F)-1] |
| 46 |
F = F[:len(F)-1] |
| 47 |
|
| 48 |
lows[x] = math.MaxInt |
| 49 |
scc.Blocks = append(scc.Blocks, s.fn.Blocks[x]) |
| 50 |
s.fn.Blocks[x].SCC = scc |
| 51 |
} |
| 52 |
s.F = F |
| 53 |
|
| 54 |
lows[vi] = math.MaxInt |
| 55 |
scc.Blocks = append(scc.Blocks, v) |
| 56 |
v.SCC = scc |
| 57 |
s.sccs = append(s.sccs, scc) |
| 58 |
} else { |
| 59 |
s.F = append(s.F, vi) |
| 60 |
} |
| 61 |
} |
| 62 |
|
| 63 |
// buildSCCs computes the strongly connected components of fn's control flow graph. |
| 64 |
func buildSCCs(fn *Function) { |
| 65 |
n := len(fn.Blocks) |
| 66 |
|
| 67 |
if n == 0 { |
| 68 |
return |
| 69 |
} |
| 70 |
|
| 71 |
state := sccState{ |
| 72 |
fn: fn, |
| 73 |
index: 0, |
| 74 |
// The +1 makes space for the sentinel value stored in F. |
| 75 |
lows: make(BlockMap[int], n+1), |
| 76 |
F: []int{n}, |
| 77 |
} |
| 78 |
|
| 79 |
// All blocks are reachable from the entry block. |
| 80 |
state.scc(fn.Blocks[0]) |
| 81 |
|
| 82 |
seen := make([]bool, len(state.sccs)) |
| 83 |
for _, scc := range state.sccs { |
| 84 |
clear(seen) |
| 85 |
for _, b := range scc.Blocks { |
| 86 |
for _, succ := range b.Succs { |
| 87 |
if succ.SCC != b.SCC && !seen[succ.SCC.Index] { |
| 88 |
b.SCC.Succs = append(b.SCC.Succs, succ.SCC) |
| 89 |
succ.SCC.Preds = append(succ.SCC.Preds, b.SCC) |
| 90 |
seen[succ.SCC.Index] = true |
| 91 |
} |
| 92 |
} |
| 93 |
} |
| 94 |
} |
| 95 |
|
| 96 |
fn.SCCs = state.sccs |
| 97 |
|
| 98 |
// This iterates over the SCCs in reverse topological order, i.e., "bottom |
| 99 |
// up". This allows us to build up reachability sets. |
| 100 |
for _, scc := range fn.SCCs { |
| 101 |
scc.reachable.SetBit(&scc.reachable, scc.Index, 1) |
| 102 |
for _, succ := range scc.Succs { |
| 103 |
scc.reachable.Or(&scc.reachable, &succ.reachable) |
| 104 |
} |
| 105 |
} |
| 106 |
} |