upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/tools/cfg_structure.py
diff options
context:
space:
mode:
authoreIBart0 <eIBart0@users.noreply.github.com>2026-11-21 21:53:03 +0000
committereIBart0 <eIBart0@users.noreply.github.com>2026-11-21 19:05:13 -0300
commitab3b0492f22f8f8f7ac4964f91b7907f4e4d027c (patch)
tree6b2255e7c5a6ff2d116ada7b70b31158bae9b723 /tools/cfg_structure.py
parent36ace7135e897c228eede5d1d8c28e972285cb14 (diff)
cfg_structure: add closed-region node splitting for irreducible CFGs
Diffstat (limited to 'tools/cfg_structure.py')
-rw-r--r--tools/cfg_structure.py125
1 files changed, 125 insertions, 0 deletions
diff --git a/tools/cfg_structure.py b/tools/cfg_structure.py
index b2e45a973..e8ef0a086 100644
--- a/tools/cfg_structure.py
+++ b/tools/cfg_structure.py
@@ -142,6 +142,131 @@ def structure(succ):
142 return emit(("l", 0) if 0 in bodies else ("b", 0)) 142 return emit(("l", 0) if 0 in bodies else ("b", 0))
143 143
144 144
145
146def _sccs(nodes, adj):
147 """Iterative Tarjan's algorithm over `nodes` with adjacency `adj`; returns SCCs with >= 2 nodes."""
148 index, low, on_stack, stack, out = {}, {}, set(), [], []
149 nxt = 0
150 for start in nodes:
151 if start in index:
152 continue
153 index[start] = low[start] = nxt
154 nxt += 1
155 stack.append(start)
156 on_stack.add(start)
157 call = [(start, iter(adj[start]))]
158 while call:
159 v, it = call[-1]
160 for w in it:
161 if w not in index:
162 index[w] = low[w] = nxt
163 nxt += 1
164 stack.append(w)
165 on_stack.add(w)
166 call.append((w, iter(adj[w])))
167 break
168 if w in on_stack and index[w] < low[v]:
169 low[v] = index[w]
170 else:
171 if low[v] == index[v]:
172 comp = []
173 while True:
174 x = stack.pop()
175 on_stack.remove(x)
176 comp.append(x)
177 if x == v:
178 break
179 if len(comp) >= 2:
180 out.append(set(comp))
181 call.pop()
182 if call:
183 p = call[-1][0]
184 if low[v] < low[p]:
185 low[p] = low[v]
186 return out
187
188
189def split_irreducible(succ, max_factor=2, max_splits=64):
190 """Make an irreducible CFG reducible by controlled node splitting (cloning the closed region R reachable from a secondary entry e without passing through primary entry h
191 in an irreducible SCC, and redirecting e's external predecessors to clone[e]).
192
193 Returns `(new_succ, orig_of)` where `orig_of[b]` is the original block index that block `b` executes
194 and `new_succ[b]` preserves the exact positional successor order of `succ[orig_of[b]]`.
195 Returns `(succ, list(range(len(succ))))` unchanged if `succ` is already reducible, or `None` if
196 splitting would exceed `max_factor` * len(succ) blocks or `max_splits` duplications.
197 """
198 n0 = len(succ)
199 if n0 == 0:
200 return succ, []
201 max_blocks = min(int(n0 * max_factor), n0 + max_splits)
202 g = None
203 orig = None
204 while True:
205 cur = succ if g is None else g
206 rpo, back, preds = _order(cur)
207 idom, pos = _dominators(rpo, preds)
208
209 def dominates(a, b):
210 while pos[b] > pos[a]:
211 b = idom[b]
212 return a == b
213
214 if all(dominates(w, v) for v, w in back):
215 if g is None:
216 return succ, list(range(n0))
217 return g, orig
218 if g is None:
219 g = [list(s) for s in succ]
220 orig = list(range(n0))
221 if len(g) >= max_blocks:
222 return None
223
224 # Strip dominating back-edges so nested irreducible cycles inside reducible loops surface as SCCs.
225 adj = {v: [w for w in g[v] if not dominates(w, v)] for v in rpo}
226 sccs = _sccs(rpo, adj)
227 if not sccs:
228 return None
229 # Pick the smallest irreducible SCC (tie-break by earliest RPO position).
230 scc = min(sccs, key=lambda c: (len(c), min(pos[x] for x in c)))
231 entries = [x for x in scc if x == 0 or any(p not in scc for p in preds[x])]
232 # Choose a pair (h, e) of SCC entries (e != h, e != 0) minimizing |R|, where R is the closed region of
233 # SCC nodes reachable from e without passing through h. Cloning all of R at once keeps internal cycles
234 # inside the clone instead of re-entering the original SCC and unrolling infinitely.
235 best = None
236 for h in entries:
237 for e in entries:
238 if e == h or e == 0:
239 continue
240 region = {e}
241 work = [e]
242 while work:
243 u = work.pop()
244 for w in g[u]:
245 if w in scc and w != h and w not in region:
246 region.add(w)
247 work.append(w)
248 key = (len(region), pos[h], -pos[e])
249 if best is None or key < best[0]:
250 best = (key, h, e, region)
251 if best is None:
252 return None
253 _, h, e, region = best
254 if len(g) + len(region) > max_blocks:
255 return None
256 # Order cloned nodes deterministically by RPO position.
257 reg_ordered = sorted(region, key=lambda x: pos[x])
258 clone_of = {}
259 for u in reg_ordered:
260 clone_of[u] = len(g)
261 orig.append(orig[u])
262 g.append([])
263 for u in reg_ordered:
264 g[clone_of[u]] = [clone_of[w] if w in clone_of else w for w in g[u]]
265 ext_preds = {p for p in preds[e] if p not in scc}
266 ce = clone_of[e]
267 for p in ext_preds:
268 g[p] = [ce if w == e else w for w in g[p]]
269
145def run(tree, choose, limit): 270def run(tree, choose, limit):
146 """Interpret a tree: the blocks it executes, in order, stopping after `limit`. `choose(b)` gives the block 271 """Interpret a tree: the blocks it executes, in order, stopping after `limit`. `choose(b)` gives the block
147 that b goes to next (END to finish) and stands for whatever b stores in pc.""" 272 that b goes to next (END to finish) and stands for whatever b stores in pc."""